#!/bin/bash
#Joel Bruner (repo: https://github.com/brunerd, blog: https://brunerd.com/blog)
##iCloudDrive - gets the iCloud Drive status for a console user

#############
# FUNCTIONS #
#############

function iCloudDrive()(

	function jpt()( #v1.0.4 jpt([options] [query] [fileArg])
	{ set +x; } &> /dev/null
		: <<-LICENSE_BLOCK
		jpt - JSON Power Tool (for more info: https://github.com/brunerd/jpt)
		Copyright (c) 2020 Joel Bruner
		Other portions: Copyright (c) 2007 Stefan Goessner (goessner.net), Copyright (c) 2020 "jpaquit" (https://github.com/jpaquit), Copyright (c) 2016 Kris Nye, Copyright (c) 2012 Dharmafly
		Licensed under the MIT License
		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.
		LICENSE_BLOCK

		#JavaScript
		read -r -d '' JSCode <<-'EOT'
		function jsonPath(obj,expr,arg){var P={resultType:arg&&arg.resultType||"VALUE",singleQuoteKeys:arg&&arg.singleQuoteKeys||false,escapeUnicode:arg&&arg.escapeUnicode||false,result:[],normalize:function(expr){if(expr.constructor===null||expr.constructor!==String)return expr},asPath:function(path){if(P.resultType==="PATH_OBJECT")return{"path":path};var qt=P.singleQuoteKeys?"'":'"';var p=P.resultType==="PATH_JSONPOINTER"?"":"$";var x=path.slice();for(var i=0,n=x.length;i<n;i++)if(P.resultType==="PATH_JSONPOINTER")p+="/"+(x[i].constructor===Number?x[i]:x[i].replace(/~/g,"~0").replace(/\//g,"~1"));else p+=x[i].constructor===Number?"["+x[i]+"]":P.resultType==="PATH_DOTTED"&&/^[A-Za-z_$][\w\d$]*$/.test(x[i])?"."+x[i]:"["+qt+x[i].replace(P.escapeUnicode?/[\u0000-\u001f\u007f-\uffff|\\|"|']/g:/[\u0000-\u001f\u007f|\\|"|']/g,function(chr){switch(chr){case "\b":return"\\b";case "\f":return"\\f";case "\n":return"\\n";case "\r":return"\\r";case "\t":return"\\t";case "\\":return"\\\\";case '"':return P.singleQuoteKeys?'"':'\\"';case "'":return P.singleQuoteKeys?"\\'":"'";default:return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)}})+qt+"]";return p},store:function(p,v){if(P.escapeUnicode&&v!==null&&v.constructor===String)v=v.replace(/[\u007F-\uFFFF]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)});if(p)P.result[P.result.length]=/^PATH/.test(P.resultType)?P.asPath(p):v;return!!p},trace:function(expr,val,path){if(expr===false)return expr;if(expr.length){var x=expr.slice();var loc=x.shift();if(val!==null&&Array.isArray(val)&&loc.constructor===String&&loc.match(/^0/)&&loc!=="0")throw new Error("Property name '"+loc+"' is a string with leading zeros and target is an array!");if(loc.constructor===Number&&Math.sign(loc)===-1&&(val instanceof Array||val.constructor===String))loc=val.length+loc;if(Array.isArray(loc))for(i=0;i<loc.length;i++){var tx=x.slice();tx.unshift(loc[i]);P.trace(tx,val,path)}else if(loc.constructor===Object)if(Array.isArray(loc.expression))P.slice(loc.expression,x,val,path);else if(loc.expression==="*")P.walk(loc.expression,x,val,path,function(m,l,x,v,p){var tx=x.slice();tx.unshift(m);P.trace(tx,v,p)});else if(loc.expression===".."){P.trace(x,val,path);P.walk(loc,x,val,path,function(m,l,x,v,p){var tx=x.slice();tx.unshift({"expression":".."});var tp=p.slice();tp.push(m);typeof v[m]==="object"&&P.trace(tx,v[m],tp)})}else if(/^\(.*?\)$/.test(loc.expression)){var tx=x.slice();tx.unshift(P.eval(loc.expression,val,path[path.length-1]));P.trace(tx,val,path)}else if(/^-$/.test(loc.expression)){if(val!==null&&Array.isArray(val)){var tx=x.slice();tx.unshift(P.eval("(@.length)",val,path[path.length-1]));P.trace(tx,val,path)}}else{if(/^\?\(.*?\)$/.test(loc.expression))P.walk(loc.expression,x,val,path,function(m,l,x,v,p){if(P.eval(l.replace(/^\?\((.*?)\)$/,"$1"),v instanceof Array?v[m]:v,m)){var tx=x.slice();tx.unshift(m);P.trace(tx,v,p)}})}else if(val&&val.constructor!==String&&val[loc]!==undefined){var tpath=path.slice();tpath.push(Array.isArray(val)?Number(loc):loc);P.trace(x,val[loc],tpath)}}else P.store(path,val)},walk:function(loc,expr,val,path,f){if(val instanceof Array)for(var i=0,n=val.length;i<n;i++){if(i in val)f(i,loc,expr,val,path)}else if(typeof val==="object")for(var m in val)if(val.hasOwnProperty(m))f(m,loc,expr,val,path)},slice:function(loc,expr,val,path){if(val instanceof Array){var str="",len,start,end,step=1;loc[0]=loc[0]!==undefined?loc[0]:null;loc[1]=loc[1]!==undefined?loc[1]:null;loc[2]=loc[2]!==undefined?loc[2]:null;if((loc[2]===null||loc[2].constructor===Number?loc[2]:P.eval(loc[2].expression,val,path[path.length-1]))===0)throw new RangeError("Slice step cannot be zero: ["+loc.join(":")+"]");else step=parseInt((loc[2]===null||loc[2].constructor===Number?loc[2]:P.eval(loc[2].expression,val,path[path.length-1]))||step);if(Math.sign(step)===-1)len=val.length,start=len-1,end=(len+(loc[1]===null?1:0))*-1;else len=val.length,start=0,end=len;start=parseInt((loc[0]===null||loc[0].constructor===Number?loc[0]:P.eval(loc[0].expression,val,path[path.length-1]))||((loc[0]===null||loc[0].constructor===Number?loc[0]:P.eval(loc[0].expression,val,path[path.length-1]))===0?0:start));end=loc[1]===0?0:parseInt((loc[1]===null||loc[1].constructor===Number?loc[1]:P.eval(loc[1].expression,val,path[path.length-1]))||end);start=start<0?Math.max(Math.sign(step)===-1?-1:0,start+len):Math.min(len,start);end=end<0?Math.max(Math.sign(step)===-1?-1:0,end+len):Math.min(len,end);if(Math.sign(step)===-1)var op=">";else var op="<";for(var i=start;eval(i+op+end);i+=step){var texpr=expr.slice();texpr.unshift(i);P.trace(texpr,val,path)}}},eval:function(x,_v,_vname){var tx=x.slice();if(/^\(.*?\)$/.test(x))tx=tx.replace(/^\((.*?)\)$/,"$1");var forbiddenInvocations=tx.split("").reverse().join("").replace(/(["'])(.*?)\1(?!\\)/g,"").replace(/(\/.*?\/(?!\\)\s*~=)|(=~*\s\/.*?\/(?!\\))/g,"").replace(/\(\s*/g,"(").replace(/([;\.\+\-~!\*\/%><&\^\|:\?,])/g," ").replace(/\s+/g," ").split("").reverse().join("").split(" ").filter(function(f){return/\(/.test(f)}).filter(function(f){return/[!^]\(|[\w\d_$]\(/.test(f)}).filter(function(f){return!/test\(|exec\(|match\(/.test(f)});if(forbiddenInvocations.length)throw new Error("Invocation violation: "+forbiddenInvocations);try{var evalResult=eval(x.replace(/(^|[^\\])@/g,"$1_v").replace(/\\@/g,"@").replace(/(_v(?:(?!(\|\||&&)).)*)=~((?:(?!\)* *(\|\||&&)).)*)/g,function(match,p1,p2,p3,offset,currentString){return match?p3.trim()+".test("+p1.trim()+")":match}).replace(/((?:(?!\)* *(\|\||&&)).)*)\s+=~\s+(_v(?:(?!(\|\||&&)).)*)/g,function(match,p1,p2,p3,offset,currentString){return match?p1.trim()+".test("+p3.trim()+")":match}));return evalResult}catch(e){throw new SyntaxError("eval: "+e.message+": "+x.replace(/(^|[^\\])@/g,"$1_v").replace(/\\@/g,"@").replace(/(_v(?:(?!(\|\||&&)).)*)=~((?:(?!\)* *(\|\||&&)).)*)/g,function(match,p1,p2,p3,offset,currentString){return match?p3.trim()+".test("+p1.trim()+")":match}).replace(/((?:(?!\)* *(\|\||&&)).)*)\s+=~\s+(_v(?:(?!(\|\||&&)).)*)/g,function(match,p1,p2,p3,offset,currentString){return match?p3.trim()+".test("+p1.trim()+")":match}));}}};var $=obj;if(expr&&obj!==undefined&&(P.resultType=="VALUE"||/^PATH/.test(P.resultType))){P.trace(P.normalize(expr),obj,[]);return P.result.length?P.result:[]}}function jscChunkPrint(resultText){var breakIndex,windowEnd,startBytes=0;var totalBytes=resultText.length;var delimiters=["\n",'","','",',',"',"},{",'":"','":{'];do{if(startBytes+maxSize.print>totalBytes)windowEnd=totalBytes;else{for(var i=0;i<=delimiters.length-1;i++){breakIndex=resultText.lastIndexOf(delimiters[i],startBytes+maxSize.print);if(breakIndex!==-1&&breakIndex>startBytes){windowEnd=breakIndex+delimiters[i].length-1;break}}if(breakIndex<startBytes)windowEnd=startBytes+maxSize.print}print(resultText.slice(startBytes,windowEnd));if(windowEnd===totalBytes)break;if(resultText.charAt(windowEnd)==="\n")startBytes=windowEnd+1;else startBytes=windowEnd}while(windowEnd<totalBytes)}function renderObject(obj,pathName,option,level){option=option||{};option.maxDepth=option.maxDepth===undefined||option.maxDepth<-1?-1:option.maxDepth;var keyQuotes=option.q?"'":'"';var stringQuotes=option.Q?"'":'"';var result=[];var indent="";const makeIndent=function(spaceArg,level){var indentComp="";if(spaceArg.constructor===Number)for(var i=0;i<spaceArg;i++)indentComp+=" ";else indentComp=spaceArg;for(var i=0;i<level;i++)indent+=indentComp;return indent};if(isNaN(level))var level=0;else level++;if(option.K&&!(option.J||option.R))option.K=false;if((option.K||option.T)&&option.i)var indent=makeIndent(option.spaceArg,level);if(obj===null){var isNull=true;obj=option.n||pathName?"null":""}var typeString=obj.constructor===Number?": Number":obj.constructor===String&&!isNull?": String":obj.constructor===Array?": Array":obj.constructor===Object?": Object":obj.constructor===Boolean?": Boolean":": null";if(obj.constructor===Array){if((option.J||option.R)&&!option.P&&(pathName||pathName===""))result.push(indent+pathName+(option.C?": Array":""));else if(!option.P&&(pathName||pathName===""))result.push(indent+pathName+(option.K?!option.C?"":typeString:level===option.maxDepth?"="+JSON.stringify(obj,null,0):"=[]"));if(option.maxDepth===-1||level<option.maxDepth)obj.forEach(function(obj,i){result.push(renderObject(obj,pathName||pathName===""?option.K?i.toString():pathName+(option.R?"/"+i:"["+i+"]"):null,option,level))})}else if(obj.constructor===Object){if((option.J||option.R)&&!option.P&&(pathName||pathName===""))result.push(indent+pathName+(option.C?": Object":""));else if((pathName||pathName==="")&&!option.P)result.push(indent+pathName+(option.K?!option.C?"":typeString:level===option.maxDepth?"="+JSON.stringify(obj,null,0):"={}"));if(option.maxDepth===-1||level<option.maxDepth)for(var key in obj)if(obj.hasOwnProperty(key)){if(pathName||pathName==="")if(option.R)var thisPath=(option.K?"":pathName+"/")+key.replace(/~/g,"~0").replace(/\//g,"~1");else if(option.d&&!option.K&&/^[A-Za-z_$][$\w\d]*$/.test(key))var thisPath=(option.K?"":pathName+".")+key;else{if(option.u)var keyEncodeRegex=/[\u0000-\u001f\u007f-\uffff|\\|"|']/g;else var keyEncodeRegex=/[\u0000-\u001f\u007f|\\|"|']/g;var keyEsc=key.replace(keyEncodeRegex,function(chr){switch(chr){case " ":return" ";case "\b":return"\\b";case "\f":return"\\f";case "\n":return"\\n";case "\r":return"\\r";case "\t":return"\\t";case "\\":return"\\\\";case '"':return keyQuotes==="'"?'"':'\\"';case "'":return keyQuotes==="'"?"\\'":"'";default:return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)}});if(option.K&&!option.L)if(option.k)var thisPath=keyEsc;else var thisPath=keyQuotes+keyEsc+keyQuotes;else var thisPath=pathName+"["+keyQuotes+keyEsc+keyQuotes+"]"}result.push(renderObject(obj[key],thisPath,option,level))}}else if(option.T){if(typeof obj==="string"&&!isNull)if(option.encoding.W&&!option.A)obj=encodeURI(obj);else if(option.encoding.w&&!option.A)obj=encodeURIComponent(obj);else{var tempArray=[];var stringPadding="",spc="",open="",close="";if(option.encoding.x)var slice=-2,stringPadding="0",escStr="\\x",stringBase=16;else if(option.encoding["0"])var escStr="\\0",stringBase=8,slice=-3,stringPadding="00";else if(option.encoding.O)var stringPadding="00",escStr="\\",stringBase=8,slice=-3;else if(option.encoding.u)var escStr="\\u",stringPadding="0000",slice=-8,slice=-4,stringBase=16,utfEncoding=16;else if(option.encoding.U)var escStr="\\U",stringPadding="000000",slice=-8,stringBase=16;else if(option.encoding.E)var escStr="\\u",stringPadding="",slice=0,open="{",close="}",stringBase=16;else if(option.encoding.o)var escStr="0o",stringBase=8,spc=" ";else if(option.encoding.b)var escStr="0b",stringBase=2,stringPadding="0000000",spc=" ",slice=-8;else if(option.encoding.B||option.encoding["6"])var escStr="0b",stringBase=2,stringPadding="000000000000000",spc=" ",slice=-16,utfEncoding=16;else if(option.encoding.h||option.encoding.H)var slice=-2,stringPadding="0",escStr="0x",stringBase=16,spc=" ";else if(option.encoding.W||option.encoding.w)var slice=-2,stringPadding="0",escStr="%",stringBase=16;for(var i=0;i<obj.length;i++){var charcode=obj.charCodeAt(i);var rangeRegex;option.W?rangeRegex=/[\u0000-\u001f\u005c\u007f\s\b]/:rangeRegex=/[\u0000-\u001f\u005c\u007f]/;if(charcode<128)if(/[\s|\b|\\]/.test(obj[i])&&!option.A&&(/^\\/.test(escStr)||!option.encoding))if(option.e)tempArray.push(obj[i].replace(/[\s|\b]/g,function(chr){switch(chr){case " ":return" ";case "\b":return"\\b";case "\f":return"\\f";case "\n":return"\\n";case "\r":return"\\r";case "\t":return"\\t";case "\v":return"\\v"}}));else if(option.W){var b=escStr+open+(stringPadding+charcode.toString(stringBase)).slice(slice)+close;tempArray.push(b+spc)}else tempArray.push(obj[i]);else if(option.encoding.b||option.encoding.B||option.encoding["6"]||option.encoding.o||option.encoding.h||option.encoding.H||option.encoding.w||option.encoding.W||(option.encoding.U||option.encoding.E||option.encoding.O||option.encoding["0"]||option.encoding.u||option.encoding.x)&&(rangeRegex.test(obj[i])||option.A))if(/[\s|\b]/.test(obj[i])&&option.U)tempArray.push(obj[i]);else{var b=escStr+open+(stringPadding+charcode.toString(stringBase)).slice(slice)+close;tempArray.push((option.encoding.B?b.slice(0,8)+"_"+b.slice(8):b)+spc)}else tempArray.push(obj[i]);else if(!option.encoding)tempArray.push(obj[i]);else if(utfEncoding===16){var b=(stringPadding+charcode.toString(stringBase)).slice(slice);tempArray.push(escStr+(option.encoding.B?b.slice(0,8)+"_"+b.slice(8):b)+spc)}else if(option.encoding.U||option.encoding.E)if(charcode<55296||charcode>=57344)tempArray.push(escStr,open,(stringPadding+charcode.toString(16)).slice(slice),close);else{i++;tempArray.push(escStr,open,(stringPadding+((charcode-55296)*1024+obj.charCodeAt(i)-56320+65536).toString(16)).slice(slice),close)}else if(charcode<2048)tempArray.push(escStr,(192|charcode>>6).toString(stringBase),spc,escStr,(128|charcode&63).toString(stringBase),spc);else if(charcode<55296||charcode>=57344)tempArray.push(escStr,(224|charcode>>12).toString(stringBase),spc,escStr,(128|charcode>>6&63).toString(stringBase),spc,escStr,(128|charcode&63).toString(stringBase),spc);else{i++;charcode=65536+((charcode&1023)<<10|obj.charCodeAt(i)&1023);tempArray.push(escStr,(240|charcode>>18).toString(stringBase),spc,escStr,(128|charcode>>12&63).toString(stringBase),spc,escStr,(128|charcode>>6&63).toString(stringBase),spc,escStr,(128|charcode&63).toString(stringBase),spc)}}obj=tempArray.join("");if(option.encoding.H)obj=obj.toUpperCase()}else if(obj.constructor===Number){if(Math.sign(obj)===-1){var possibleNegative="-";obj=obj*-1}else var possibleNegative="";if(obj===Infinity)if(option.I)obj=possibleNegative+"Infinity";else if(option.n)obj="null";else obj="";else if(option.encoding.b||option.encoding.B||option.encoding["6"]){obj=Math.floor(obj).toString(2);if(option.encoding.b){var width=8;var delineation=8}else if(option.encoding.B){var width=16;var delineation=8}else if(option.encoding["6"]){var width=16;var delineation=16}if(obj.length<width)var padding=width-obj.length;else if(obj.length%width!=0)var padding=width-obj.length%width;else var padding=0;var widthMultiple=obj.length+padding;if(option.encoding.b)obj=("0000000"+obj).slice(-widthMultiple);else if(option.encoding.B||option.encoding["6"])obj=("000000000000000"+obj).slice(-widthMultiple);for(var c=0,tempObj="";c<obj.length;c=c+delineation)var tempObj=tempObj+(c===0?"":"_")+obj.slice(c,c+delineation);obj=possibleNegative+"0b"+tempObj}else if(option.encoding.h||option.encoding.H)obj=possibleNegative+"0x"+((obj<16?"0":"")+(option.encoding.h?Math.floor(obj).toString(16):Math.floor(obj).toString(16).toUpperCase()));else if(option.encoding.o)obj=possibleNegative+"0o"+Math.floor(obj).toString(8);else if(option.encoding.O)obj=possibleNegative+"0"+Math.floor(obj).toString(8)}result=[indent+obj]}else if(option.R||option.J)result=[indent+pathName+(option.C?typeString:"")];else if(typeof obj==="string"&&!isNull){var thisString=obj.replace(option.u?/[\u0000-\u001f\u007f-\uffff|\\|"|']/g:/[\u0000-\u001f\u007f|\\|"|']/g,function(chr){switch(chr){case "\b":return"\\b";case "\f":return"\\f";case "\n":return"\\n";case "\r":return"\\r";case "\t":return"\\t";case "\\":return"\\\\";case '"':return stringQuotes==="'"?'"':'\\"';case "'":return stringQuotes==="'"?"\\'":"'";default:return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)}});result=[pathName+"="+stringQuotes+thisString+stringQuotes]}else result=[pathName+"="+obj];return result.flat()}function objectifyExpressions(array,option){option=option||{};function fixFilterString(str){str=str.split("");var mode={inDoubleQuote:false,inSingleQuote:false,inEscape:false,inRegexp:false,inPath:false,inKeyName:false,inBracket:false};var lastPathChar;var comparatorOp=false;var negationCount=0;var parenStack=[];for(var i=0;i<str.length;i++){if(mode.inKeyName&&!/[$_A-Za-z0-9.]/.test(str[i]))mode.inKeyName=false;if(mode.inDoubleQuote||mode.inSingleQuote)if(mode.inEscape)mode.inEscape=false;else if(str[i]==='"'&&mode.inDoubleQuote)mode.inDoubleQuote=false;else if(str[i]==="'"&&mode.inSingleQuote)mode.inSingleQuote=false;else{if(str[i]==="\\")mode.inEscape=true}else if(mode.inRegexp)if(mode.inEscape)mode.inEscape=false;else if(str[i]==="[")mode.inBracket=true;else if(str[i]==="]")mode.inBracket=false;else if(str[i]==="/"&&!mode.inBracket)mode.inRegexp=false;else{if(str[i]==="\\")mode.inEscape=true}else if(mode.inKeyName)lastPathChar=i;else if(str[i]==='"'||str[i]==="'"){if(str[i]==='"')mode.inDoubleQuote=true;else mode.inSingleQuote=true;lastPathChar=i}else if(str[i]==="$"||str[i]==="@"){lastPathChar=i;if(str[i+1]==="."){mode.inKeyName=true;lastPathChar=i}}else if(str[i]==="]"){lastPathChar=i;mode.inBracket=false;if(str[i+1]==="."){mode.inKeyName=true;i++}}else if(str[i]==="/")mode.inRegexp=true;else if((str[i]==="="||str[i]==="!"||str[i]==="<"||str[i]===">"||str[i]==="=")&&str[i+1]==="="){lastPathChar=undefined;i=i+1;mode.inPath=false;comparatorOp=true}else if(str[i]==="<"||str[i]===">"){lastPathChar=undefined;mode.inPath=false;comparatorOp=true}else if(str[i]==="="&&str[i+1]==="~"){lastPathChar=undefined;mode.inPath=false;comparatorOp=true;i=i+1}else if(str[i]==="&"&&str[i+1]==="&"||str[i]==="|"&&str[i+1]==="|"){if(comparatorOp!=true&&lastPathChar!==undefined){str.splice(lastPathChar+1,0,"!==undefined");i++}mode.inPath=false;comparatorOp=false;if(negationCount)for(var loop=0;loop<negationCount;negationCount--){str.splice(i,0,")");i++}}else if(str[i]==="!"){str.splice(i+1,0,"(");negationCount++;i++}else if(str[i]==="("){parenStack.unshift(negationCount);negationCount=0}else if(str[i]===")"){if(negationCount)for(var loop=0;loop<negationCount;negationCount--){str.splice(i+1,0,")");i++}negationCount=parenStack.shift()}if(i==str.length-2){if(comparatorOp!=true&&lastPathChar!==undefined){str.splice(lastPathChar+1,0,"!==undefined");i++}if(negationCount)for(var loop=0;loop<negationCount;negationCount--){str.splice(i+1,0,")");i++}}}var finalString=str.join("");return finalString}try{array=array.map(function(expr){var pathStack=[];var baldRecursion=false;var assignmentLocations=[];expr=expr.replace(/^\s*/,"").replace(/\s*$/,"");if(expr==="."){if(option.c)printErr("jq-style query '.' treated as JSONPath '$'");expr="$"}if(expr===""||expr[0]==="/"){if(/~[^0-1]/g.test(expr+" "))throw new SyntaxError("JSON Pointer allows ~0 and ~1 only: "+expr);option.allowExpressions=false;pathStack=expr.split("/");pathStack.shift();pathStack=pathStack.map(function(f){return f.replace(/~1/g,"/").replace(/~0/g,"~")});if(pathStack[pathStack.length-1]==="-")pathStack[pathStack.length-1]={"expression":"-"}}else{if(expr[0]==="."&&expr[1]==="["){expr="$"+expr.slice(1);if(option.c)printErr("jq-style '.[' beginning, treated as JSONPath '$['")}else if(expr[0]==="."&&expr[1]!=="."||expr[0]==="["){expr="$"+expr;if(option.c)printErr("Query lacks root '$', trying as JSONPath...")}else if(expr[0]!=="$"){if(option.c)printErr("Query lacks root '$', trying as keypath...");expr="$"+expr.replace("\\.","\udead").split(".").map(function(f){return"["+JSON.stringify(f.replace("\udead","."))+"]"}).join("")}var revExpr=expr.split("").reverse().join("");var tempExpr=revExpr.replace(/(["'])(.*?)\1(?!\\)|(\/.*?\/(?!\\)\s*~=)|=~*\s(\/.*?\/(?!\\))|(={2,3})[^=]|[^=](==?!)|[^=]((?:=!|=<|=>|~=))/g,function(a){return a.replace(/./g," ")});var assignmentRegex=/=/g;var assignmentLocations=[];var lastAssignmentLastIndex=0;var assignmentMatch=[];do{assignmentMatch=assignmentRegex.exec(tempExpr);if(assignmentMatch===null||assignmentRegex.lastIndex===0||lastAssignmentLastIndex===assignmentRegex.lastIndex)break;lastAssignmentLastIndex=assignmentRegex.lastIndex;assignmentLocations.unshift(lastAssignmentLastIndex)}while(assignmentRegex.lastIndex!==0&&assignmentRegex.lastIndex!==tempExpr.length);if(option.disallowData&&assignmentLocations.length)throw new SyntaxError("Data assignment (=) not allowed in path specification");else if(assignmentLocations.length>1)throw new SyntaxError("Multiple assignment operators detected: "+expr);if(expr.length-lastAssignmentLastIndex>0)var revExpr=expr.substring(0,expr.length-lastAssignmentLastIndex).split("").reverse().join("");else throw new Error("Error parsing: "+expr);var hasRoot,lastLastIndex=0;var Level1Regex=/([\w\d$]*[A-Za-z_$])(\.{1,2})|(\*?)(\.{1,2})|(\])|(\$)/g;do{var L1Match=Level1Regex.exec(revExpr);if(L1Match===null)break;if(lastLastIndex+L1Match[0].length!==Level1Regex.lastIndex||L1Match[0]==="")throw new SyntaxError("Malformed path expression: "+expr);if(L1Match[1]||L1Match[3]){if(baldRecursion)throw new SyntaxError("Additional operators (./..) disallowed after recursive descent: "+expr);L1Match=L1Match.filter(function(p){return p!=null});if(L1Match[1]==="*"){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+expr);pathStack.unshift({"expression":"*"})}else if(L1Match[1])pathStack.unshift(L1Match[1].split("").reverse().join(""));if(L1Match[2]===".."){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+expr);pathStack.unshift({"expression":".."})}else if(L1Match[1]===""){Level1Regex.lastIndex=lastLastIndex;break}}else if(L1Match[4]){if(L1Match[4]===".")break;else if(!pathStack.length){baldRecursion=true;break}else if(pathStack[0].expression==="..")throw new SyntaxError("Additional operators (./..) disallowed after recursive descent: "+expr);pathStack.unshift({"expression":".."})}else if(L1Match[5]){baldRecursion=false;var Level2Regex=/\s*(["'])(.*?)\1(?!\\)|(\*(?!:\*))|(\d+\-?)|(-)|(,)|(:)|(\))|(\[)|\s/g;var subArray=[],L2Match=[],subLastLastIndex=Level1Regex.lastIndex,pendingData=[],intraSlice=false,needsDelimiter=false,isSlice=false;var openBracket=0,closedBracket=1;Level2Regex.lastIndex=Level1Regex.lastIndex;do{L2Match=Level2Regex.exec(revExpr);if(L2Match===null||subLastLastIndex===Level2Regex.lastIndex||subLastLastIndex+L2Match[0].length!==Level2Regex.lastIndex)throw new SyntaxError("Malformed path expression : "+expr);L2Match=L2Match.map(function(s){return!s?s:s.split("").reverse().join("")});if(L2Match[2]==="")subArray.unshift(L2Match[2]);else if(L2Match[2]){if(needsDelimiter){Level2Regex.lastIndex=subLastLastIndex;break}else needsDelimiter=true;if(intraSlice)break;pendingData.unshift(JSON.parse('"'+(L2Match[1]==="'"?L2Match[2].replace(/\\'/g,"'").replace(/"/g,'\\"'):L2Match[2])+'"',null,0))}else if(L2Match[3]){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+expr);if(needsDelimiter){Level2Regex.lastIndex=subLastLastIndex;break}else needsDelimiter=true;if(intraSlice)break;else pendingData.unshift({"expression":"*"})}else if(L2Match[4]){if(needsDelimiter&&!isSlice){Level2Regex.lastIndex=subLastLastIndex;break}else needsDelimiter=true;if(isSlice&&intraSlice)intraSlice=false;if(L2Match[4]!=="0"&&(L2Match[4][0]==="0"||L2Match[4][0]==="-"&&L2Match[4][1]==="0"))throw new Error("Octal indices are disallowed: "+L2Match[4]);else pendingData.unshift(Number(L2Match[4]))}else if(L2Match[5]){if(needsDelimiter){Level2Regex.lastIndex=subLastLastIndex;break}else needsDelimiter=true;pendingData.unshift({"expression":"-"})}else if(L2Match[6]){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+expr);if(pendingData.length&&!isSlice)subArray.unshift(pendingData[0]);else if(pendingData.length){if(isSlice&&intraSlice)pendingData.unshift(null);subArray.unshift({"expression":pendingData})}pendingData=[],needsDelimiter=false;if(isSlice){intraSlice=false;isSlice=false}}else if(L2Match[7]){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+expr);isSlice=true;if(pendingData.length===1&&pendingData[0]!==null&&(pendingData[0].constructor===String||!(pendingData[0].constructor===Number||pendingData[0].expression[0]==="(")))break;if(!pendingData.length||intraSlice)pendingData.unshift(null);if(!intraSlice)intraSlice=true}else if(L2Match[8]){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+expr);var openParens=0,closeParens=1,L3Match=[];var filterText=L2Match[8];var Level3Regex=/(["'])(.*?)\1(?!\\)|(\()|(\))|(\/.*?\/(?!\\)\s*~=)|(~=\s*\/.*?\/(?!\\))|(==?((?:=|!)))|(.)/g;if(isSlice)intraSlice=false;else if(needsDelimiter)break;Level3Regex.lastIndex=Level2Regex.lastIndex;do{L3Match=Level3Regex.exec(revExpr);if(L3Match[1])filterText+=L3Match[0].replace(/@/g,"@\\");else if(L3Match[3]){filterText+=L3Match[3];openParens+=1}else if(L3Match[4]){filterText+=L3Match[4];closeParens+=1}else if(L3Match[5]||L3Match[6])filterText+=L3Match[0].replace(/@/g,"@\\");else if(L3Match[7])filterText+="=="+L3Match[8];else if(L3Match[9]){if(L3Match[9]==="="&&!/[<>!]/.test(revExpr[Level3Regex.lastIndex]))break;filterText+=L3Match[9]}if(closeParens===openParens){needsDelimiter=true;if(revExpr[Level3Regex.lastIndex]==="?"){if(isSlice){Level3Regex.lastIndex=0;break}filterText+="?";Level3Regex.lastIndex=Level3Regex.lastIndex+1}Level2Regex.lastIndex=Level3Regex.lastIndex;var filterTextFinal=fixFilterString(filterText.split("").reverse().join(""));pendingData.unshift({"expression":filterTextFinal});break}}while(Level3Regex.lastIndex!==0&&Level3Regex.lastIndex!==revExpr.length);if(closeParens!==openParens)break}else if(L2Match[9])if(Level2Regex.lastIndex-Level1Regex.lastIndex===1)break;else{Level1Regex.lastIndex=Level2Regex.lastIndex;break}subLastLastIndex=Level2Regex.lastIndex}while(Level2Regex.lastIndex!==0&&Level2Regex.lastIndex!==revExpr.length);if(pendingData.length===1&&!isSlice)subArray.unshift(pendingData[0]);else if(pendingData.length){if(isSlice&&intraSlice)pendingData.unshift(null);if(pendingData[2]===undefined)pendingData[2]=null;subArray.unshift({"expression":pendingData})}if(subArray.length>1){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+expr);pathStack.unshift(subArray)}else pathStack.unshift(subArray[0])}else if(L1Match[6])if(Level1Regex.lastIndex===revExpr.length)hasRoot=true;else break;lastLastIndex=Level1Regex.lastIndex}while(Level1Regex.lastIndex!==0&&Level1Regex.lastIndex!==revExpr.length);if(!hasRoot||baldRecursion||Level1Regex.lastIndex!==revExpr.length&&!lastAssignmentLastIndex)throw new SyntaxError("Malformed path expression: "+expr);}if(assignmentLocations.length===1){if(expr.charAt(expr.length-lastAssignmentLastIndex-1)==="=")return"";var assignmentData=expr.substring(expr.length-lastAssignmentLastIndex+1,expr.length);if(assignmentData.match(/^'(.*)'$/))assignmentData='"'+assignmentData.substring(1,assignmentData.length-1).replace(/\\"/g,'"').replace(/\\'/g,"'").replace(/"/g,'\\"')+'"';try{var assignmentData_obj=JSON.parse(assignmentData)}catch(e){throw new SyntaxError(e+": "+assignmentData);}}if(pathStack.length&&pathStack[pathStack.length-1].constructor===Array&&option.expandTrailingUnion){var returnObject=[];var basePath=pathStack.slice();var childUnion=basePath.pop();for(var i=0;i<childUnion.length;i++){var thisChild=childUnion[i];var tempBasePath=basePath.slice();tempBasePath.push(thisChild);returnObject.push({"path":tempBasePath,"data":assignmentData_obj})}return returnObject}else{var returnObject={"path":pathStack,"data":assignmentData_obj};return returnObject}})}catch(e){throw new Error(e);}return array.filter(function(e){return e}).flat()}function sortObject(obj){if(Array.isArray(obj))var seed=[];else if(typeof obj==="object"&&obj!==null)var seed={};else return obj;return Object.keys(obj).sort().reduce(function(result,key){if(typeof obj[key]==="object")result[key]=sortObject(obj[key]);else result[key]=obj[key];return result},seed)}function flatten(){var flat=[];for(var i=0;i<arguments.length;i++)if(arguments[i]instanceof Array)flat.push.apply(flat,flatten.apply(this,arguments[i]));else flat.push(arguments[i]);return flat}if(!Array.prototype.flat)Object.defineProperty(Array.prototype,"flat",{configurable:true,value:function flat(){var depth=isNaN(arguments[0])?1:Number(arguments[0]);return depth?Array.prototype.reduce.call(this,function(acc,cur){if(Array.isArray(cur))acc.push.apply(acc,flat.call(cur,depth-1));else acc.push(cur);return acc},[]):Array.prototype.slice.call(this)},writable:true});Object.defineProperty(Array.prototype,"sortVarWidth",{configurable:true,value:function sortVarWidth(){var that=this;var sortedUniqLengths=Array.prototype.map.call(this,function(e){return e.length}).filter(function(v,i,arr){return i==arr.indexOf(v)}).sort(function(a,b){return a-b});var sortedArray=[];Array.prototype.forEach.call(sortedUniqLengths,function(l){var chunk=Array.prototype.filter.call(that,function(e){return e.length==l});sortedArray.push(chunk.sort())});return sortedArray.flat()},writable:true});RegExp.quote=function(str){return str.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")};if(!Math.sign)Math.sign=function(x){return(x>0)-(x<0)||+x};(function(root,factory){if(typeof exports==="object")factory(module.exports);else if(typeof define==="function"&&define.amd)define(["exports"],factory);else{root.jsonpatch={};root.returnExports=factory(root.jsonpatch)}})(this,function(exports){var apply_patch,JSONPatch,JSONPointer,_operationRequired,isArray;isArray=Array.isArray||function(obj){return Object.prototype.toString.call(obj)=="[object Array]"};exports.apply_patch=apply_patch=function(doc,patch){return(new JSONPatch(patch)).apply(doc)};function InvalidPatch(message){Error.call(this,message);this.message=message}exports.InvalidPatch=InvalidPatch;InvalidPatch.prototype=new Error;function PatchApplyError(message){Error.call(this,message);this.message=message}exports.PatchApplyError=PatchApplyError;PatchApplyError.prototype=new Error;exports.JSONPointer=JSONPointer=function JSONPointer(pathStr){var i,split,path=[];split=pathStr.split("/");if(""!==split[0])throw new InvalidPatch("JSONPointer must start with a slash (or be an empty string)!");for(i=1;i<split.length;i++)path[i-1]=split[i].replace(/~1/g,"/").replace(/~0/g,"~");this.path=path;this.length=path.length};JSONPointer.prototype._get_segment=function(index,node){var segment=this.path[index];if(isArray(node))if("-"===segment)segment=node.length;else{if(!segment.match(/^0$|^[1-9][0-9]*$/))throw new RangeError("Invalid array index: "+segment);segment=parseInt(segment,10)}return segment};function clone(o){var cloned,key;if(isArray(o))return o.slice();if(o===null)return o;else if(typeof o==="object"){cloned={};for(key in o)if(Object.hasOwnProperty.call(o,key))cloned[key]=o[key];return cloned}else return o}JSONPointer.prototype._action=function(doc,handler,mutate){var that=this;function follow_pointer(node,index){var segment,subnode;if(!mutate)node=clone(node);segment=that._get_segment(index,node);if(index==that.path.length-1)node=handler(node,segment);else{if(isArray(node)){if(node.length<=segment)throw new PatchApplyError("Path not found in document");}else if(typeof node==="object"){if(!Object.hasOwnProperty.call(node,segment))throw new PatchApplyError("Path not found in document");}else throw new PatchApplyError("Path not found in document");subnode=follow_pointer(node[segment],index+1);if(!mutate)node[segment]=subnode}return node}return follow_pointer(doc,0)};JSONPointer.prototype.add=function(doc,value,mutate){if(0===this.length)return value;return this._action(doc,function(node,lastSegment){if(node===null)throw new Error("Unable to add to null!");else if(isArray(node)){if(lastSegment>node.length)throw new RangeError("Array index '"+lastSegment+"' does not exist. Use '-' to add to the end.");node.splice(lastSegment,0,value)}else node[lastSegment]=value;return node},mutate)};JSONPointer.prototype.remove=function(doc,mutate){if(0===this.length)return[];return this._action(doc,function(node,lastSegment){if(!Object.hasOwnProperty.call(node,lastSegment))throw new PatchApplyError("Remove operation must point to an existing value!");if(isArray(node))node.splice(lastSegment,1);else delete node[lastSegment];return node},mutate)};JSONPointer.prototype.replace=function(doc,value,mutate){if(0===this.length)return value;return this._action(doc,function(node,lastSegment){if(node===null)throw new Error("Unable to replace to null!");else if(!Object.hasOwnProperty.call(node,lastSegment))throw new RangeError("Replace requires an existing location. Property '"+lastSegment+"' not found.");if(isArray(node))node.splice(lastSegment,1,value);else node[lastSegment]=value;return node},mutate)};JSONPointer.prototype.get=function(doc){var value;if(0===this.length)return doc;this._action(doc,function(node,lastSegment){if(!Object.hasOwnProperty.call(node,lastSegment))throw new PatchApplyError("Path not found in document");value=node[lastSegment];return node},true);return value};JSONPointer.prototype.subsetOf=function(otherPointer){if(this.length<=otherPointer.length)return false;for(var i=0;i<otherPointer.length;i++)if(otherPointer.path[i]!==this.path[i])return false;return true};_operationRequired={add:["value"],replace:["value"],test:["value"],remove:[],move:["from"],copy:["from"]};function deepEqual(a,b){var key;if(a===b)return true;else if(typeof a!==typeof b)return false;else if("object"===typeof a){var aIsArray=isArray(a),bIsArray=isArray(b);if(aIsArray!==bIsArray)return false;else if(aIsArray)if(a.length!=b.length)return false;else{for(var i=0;i<a.length;i++)if(!deepEqual(a[i],b[i]))return false;return true}else{if(Object.keys(a).length!==Object.keys(b).length)return false;for(key in a)if(!b.hasOwnProperty(key)||!deepEqual(a[key],b[key]))return false;return true}}else return false}function validateOp(operation){var i,required;if(!operation.op)throw new InvalidPatch("Operation missing");if(!_operationRequired.hasOwnProperty(operation.op))throw new InvalidPatch("Invalid JSON Patch operation");if(!("path"in operation))throw new InvalidPatch("Path missing");required=_operationRequired[operation.op];for(i=0;i<required.length;i++)if(operation[required[i]]===undefined)throw new InvalidPatch(operation.op+" must have key "+required[i]);}function compileOperation(operation,mutate){validateOp(operation);var op=operation.op;var path=new JSONPointer(operation.path);var value=operation.value;var from=operation.from!==undefined?new JSONPointer(operation.from):null;switch(op){case "add":return function(doc){return path.add(doc,value,mutate)};case "remove":return function(doc){return path.remove(doc,mutate)};case "replace":return function(doc){return path.replace(doc,value,mutate)};case "move":if(path.subsetOf(from))throw new InvalidPatch("destination must not be a child of source");return function(doc){var value=from.get(doc);var intermediate=from.remove(doc,mutate);return path.add(intermediate,value,mutate)};case "copy":return function(doc){var value=from.get(doc);return path.add(doc,value,mutate)};case "test":return function(doc){if(!deepEqual(path.get(doc),value))throw new PatchApplyError("Test operation failed. Values did not match.");return doc}}}exports.JSONPatch=JSONPatch=function JSONPatch(patch,mutate){this._compile(patch,mutate)};JSONPatch.prototype._compile=function(patch,mutate){var i,_this=this;this.compiledOps=[];if("string"===typeof patch)patch=JSON.parse(patch);if(!isArray(patch))throw new InvalidPatch("Patch must be an array of operations");for(i=0;i<patch.length;i++){var compiled=compileOperation(patch[i],mutate);_this.compiledOps.push(compiled)}};exports.JSONPatch.prototype.apply=function(doc){var i;for(i=0;i<this.compiledOps.length;i++)doc=this.compiledOps[i](doc);return doc}});function isObject(a){var type=typeof a;return a!=null&&(type==="object"||type=="function")}function diff(oldValue,newValue){if(oldValue==newValue)return undefined;if(!(oldValue!=null&&newValue!=null&&typeof newValue==="object"&&typeof oldValue==="object"))return newValue!=null?newValue:null;if(!Array.isArray(oldValue)&&Array.isArray(newValue))return newValue;if(Array.isArray(oldValue)&&!Array.isArray(newValue)){var newValue=JSON.parse(JSON.stringify(newValue));newValue.length=null;return newValue}var patch=undefined;for(var name in oldValue)if(oldValue.hasOwnProperty(name))if(!newValue.hasOwnProperty(name)){if(patch==null)patch={};patch[name]=null}else{var propertyDiff=diff(oldValue[name],newValue[name]);if(propertyDiff!==undefined){if(patch==null)patch={};patch[name]=propertyDiff}}for(var name in newValue)if(newValue.hasOwnProperty(name)&&!oldValue.hasOwnProperty(name)){if(patch==null)patch={};patch[name]=newValue[name]}if(Array.isArray(oldValue)&&Array.isArray(newValue)&&newValue.length<oldValue.length){patch.length=newValue.length;for(var i=newValue.length;i<oldValue.length;i++)delete patch[i]}return patch}function merge(target,patch,deleteNull,mergeOption){if(Array.isArray(target)&&patch!=null&&patch.length===null){target={};delete patch.length}if(patch==null||patch!=null&&patch.constructor!==Object)if(Array.isArray(patch))return JSON.parse(JSON.stringify(patch));else return patch;if(!isObject(target))target={};var deletedValues=false;for(var key in patch){var value=patch[key];if(deleteNull&&value==null){deletedValues=true;delete target[key]}else{if(target[key]===undefined&&mergeOption&&mergeOption.existingOnly==true)continue;else if(target[key]!==undefined&&mergeOption&&mergeOption.nonexistingOnly==true)continue;target[key]=merge(target[key],value,deleteNull,mergeOption)}}if(deletedValues&&Array.isArray(target))for(var i=target.length;i>0;i--)if(target[i-1]==null)target.length=i-1;return target}function ingestLiterals(valueString,option,$){var literalStrings=valueString.split("\n").filter(function(p){return p!=null&&p!=""});try{var literalObjects=objectifyExpressions(literalStrings)}catch(e){throw new Error(e);}for(var i=0;i<literalObjects.length;i++){var thisLitObj=literalObjects[i];var thisPath=thisLitObj.path;var thisData=thisLitObj.data;var thisNode=$;if(!thisPath.length)if($!==undefined&&option.G)printErr("Guarding $ from root overwrite, line: "+(i+1));else if(thisData!==undefined)$=thisData;else{if(option.g)$=null}else{if(thisPath[0].constructor===String&&($===undefined||$===null||$.constructor!==Object))if($!==undefined&&option.G)printErr("Guarding $["+thisPath[0]+"] from changing array to object, line: "+(i+1));else{if(thisPath[0]!=="-"){$={};thisNode=$}}else if(thisPath[0].constructor===Number&&($===undefined||$===null||$.constructor!==Array))if($!==undefined&&option.G)printErr("Guarding $["+thisPath[0]+"] from changing object to array, line: "+(i+1));else{$=[];thisNode=$}for(var j=0;j<=thisPath.length-1;j++){if(thisNode.constructor===Array&&(thisPath[j].expression==="-"||thisPath[j]==="-"))var thisKeyName=thisNode.length;else var thisKeyName=thisPath[j];if(thisData===undefined&&!option.g||thisKeyName===undefined)break;if(j===thisPath.length-1)if(thisNode[thisKeyName]!==undefined&&option.G)printErr("Guarding against re-assignment of '"+thisKeyName+"' to: "+JSON.stringify(thisData));else if(thisData!==undefined)thisNode[thisKeyName]=thisData;else{if(option.g)thisNode[thisKeyName]=null}else{if(!thisNode.hasOwnProperty(thisKeyName))if(thisPath[j+1].constructor===String)thisNode[thisKeyName]={};else{if(thisPath[j+1].constructor===Number)thisNode[thisKeyName]=[]}else if(thisPath[j+1].constructor===String&&(thisNode[thisKeyName]===undefined||thisNode[thisKeyName]===null||thisNode[thisKeyName].constructor!==Object))thisNode[thisKeyName]={};else if(thisPath[j+1].constructor===Number&&(thisNode[thisKeyName]===undefined||thisNode[thisKeyName]===null||thisNode[thisKeyName].constructor!==Array))thisNode[thisKeyName]=[];thisNode=thisNode[thisKeyName]}}}}return $!==undefined?JSON.parse(JSON.stringify($)):[]}function alterObject(obj,valueArg,fromArg,pathArg,option,JSONTextNumber,JSONPatchArg){if(!(option.x||option.X)){var opArg,pathArgValidated=[],fromArgValidated;if(Object.keys(option.opArg)[0]!==undefined)opArg=Object.keys(option.opArg)[0];if(valueArg!==undefined){if(option.V)try{valueArg=readFile(valueArg)}catch(error){throw new Error(error);}if(option.s)valueArg='"'+valueArg.replace(/[\u0000-\u001f\u007f|"|\\]/g,function(chr){switch(chr){case '"':return'\\"';case "\\":return"\\\\";case "\b":return"\\b";case "\f":return"\\f";case "\n":return"\\n";case "\r":return"\\r";case "\t":return"\\t";default:return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)}})+'"';try{valueArg=JSON.parse(valueArg)}catch(e){if(option.c&&option.H)printErr("Truncation help will be attmepted on value input (-v/-V)");var tempJSONValueArray=rehabJSON(valueArg);if(!tempJSONValueArray.length||tempJSONValueArray.length>1)throw new Error("Multiple JSON texts are not allowed in as a value");try{valueArg=JSON.parse(tempJSONValueArray[0])}catch(error){printErr("Error in supplied JSON value (-v/-V): "+tempJSONValueArray[0].substring(0,24).replace(/[\n|\r]/g,"")+"\u2026");throw new Error(e);}}}if(fromArg!==undefined)if(fromArg==="$")fromArgValidated="";else if(fromArg[0]==="$"){try{fromArgValidated=jsonPath(obj,objectifyExpressions([fromArg],null)[0].path,{resultType:"PATH_JSONPOINTER"})}catch(error){throw new Error(error);}if(!fromArgValidated.length)throw new Error("Unable to resolve from path: "+fromArg);else if(fromArgValidated.length>1)throw new RangeError('Error: "From" path returned multiple results: '+fromArg+"\n"+fromArgValidated.join("\n"));else fromArgValidated=fromArgValidated[0]}else fromArgValidated=fromArg;if(pathArg!==undefined)if(pathArg==="$")pathArgValidated=[""];else if(pathArg[0]==="$"){try{pathArgValidated=objectifyExpressions([pathArg],{"expandTrailingUnion":true,"allowExpressions":true})}catch(error){throw new Error(error);}pathArgValidated=pathArgValidated.map(function(p){try{var xp=jsonPath(obj,p.path,{resultType:"PATH_JSONPOINTER"})}catch(error){throw new Error(error);}if(xp.length)return xp;else if(option.opArg.remove||option.opArg.replace||option.opArg.test){if(option.G)return"/"+p.path.map(function(p){return p.toString().replace(/~/g,"~0").replace(/\//g,"~1")}).join("/");return""}var pp=p.path.slice();var pc=pp.pop();if(!pp.length&&pc.expression==="-")var possiblePaths="/-";else if(pp.length){var ppv=jsonPath(obj,pp,{resultType:"PATH_OBJECT"});if(!ppv.length)return"";var possiblePaths=ppv.map(function(ppve){ppve.path.push(pc.expression==="-"?"-":pc);if(pc!==null&&(pc.constructor===String||pc.constructor===Array||pc.expression==="-")){var ppve_jp="/"+ppve.path.map(function(p){return p.toString().replace(/~/g,"~0").replace(/\//g,"~1")}).join("/");return ppve_jp}else return""})}else var possiblePaths="/"+p.path.map(function(p){return p.toString().replace(/~/g,"~0").replace(/\//g,"~1")}).join("/");return possiblePaths}).flat().sortVarWidth().reverse().filter(function(p){return p!=null&&p!=""}).filter(function(item,pos,ary){return!pos||item!=ary[pos-1]});if(pathArgValidated.length>1)if(option.opArg.move)throw new Error("Move operation cannot have multiple destinations: "+pathArg+"\n"+pathArgValidated.join("\n"));}else if(pathArg===""||pathArg[0]==="/")pathArgValidated=[pathArg];else throw SyntaxError("Unrecognized query syntax: "+pathArg);}if(option.opArg.mergepatch||option.opArg.merge||option.opArg.merge0||option.opArg.merge1)if(valueArg!==undefined&&fromArgValidated!==undefined)throw new Error("Merge source ambiguous. Specify a value (-v/-V) or a path (-p), or neither.");else if(valueArg===undefined&&fromArgValidated===undefined)throw new SyntaxError("Merge source not given, specify a path (-p) or a JSON value (-v/-V).");else{if(fromArgValidated){try{var rawVal=jsonPath(obj,objectifyExpressions([fromArgValidated])[0].path,null)[0]}catch(e){throw new Error(e);}valueArg=rawVal;if(valueArg===undefined)throw new Error("From path does not exist: "+fromArgValidated);}else if(fromArgValidated==="")valueArg=jsonPath(obj,[],null)[0];if(!pathArgValidated.length)obj=merge(obj,valueArg,option.opArg.mergepatch?true:false,option.opArg.merge1?{"existingOnly":true}:option.opArg.merge0?{"nonexistingOnly":true}:null);else pathArgValidated.forEach(function(p){try{var pval=jsonPath(obj,objectifyExpressions([p])[0].path,null)[0]}catch(e){throw new Error(e);}var mergedValue=merge(pval,valueArg,option.opArg.mergepatch?true:false,option.opArg.merge1?{"existingOnly":true}:option.opArg.merge0?{"nonexistingOnly":true}:null);try{obj=jsonpatch.apply_patch(obj,[{"op":"replace","path":p,"value":mergedValue}])}catch(e){throw new Error(e);}})}else if(option.opArg.diff)if(valueArg!==undefined)obj=diff(obj,valueArg,true);else throw new SyntaxError("No value specified!");else{if(option.x||option.X){if(option.X)var JSONPatch=readFile(JSONPatchArg);else var JSONPatch=JSONPatchArg;try{var opArray=JSON.parse(JSONPatch)}catch(e){if(option.c&&option.H)printErr("Truncation help will be attmepted on JSON Patch input");var tempJSONValueArray=rehabJSON(JSONPatch);if(tempJSONValueArray.length>1)throw new Error("Multiple JSON texts are not allowed for JSON Patch");else if(!tempJSONValueArray.length)throw new Error("No JSON supplied for JSON Patch!");try{opArray=JSON.parse(tempJSONValueArray[0])}catch(error){printErr("Error in supplied JSON Patch input: "+tempJSONValueArray[0].substring(0,24).replace(/[\n|\r]/g,"")+"\u2026");throw new Error(e);}}}else if(pathArgValidated.length){var opArray=[{}];var i;for(var i=0;i<pathArgValidated.length;i++)opArray[i]={"op":opArg,"path":pathArgValidated[i],"from":fromArgValidated,"value":valueArg}}else throw new Error("JSON Patch operation with no path provided!");try{obj=jsonpatch.apply_patch(obj,opArray)}catch(e){throw new Error("JSON Text ("+JSONTextNumber+") "+e);}}return obj}function rehabJSON(str){str=str.split("");var mode={doubleQuote:false,singleQuote:false,inEscape:false,blockComment:false,blockCommentXML:false,lineComment:false};var JSONTextStartIndex=0;var objStack=[];var makeNewText=false;var JSONTexts=[];var lastCharIndex;for(var i=0,l=str.length;i<l;i++){if(mode.doubleQuote||mode.singleQuote)if(mode.inEscape){mode.inEscape=false;if(str[i]==="0"&&!/\d/.test(str[i+1])){if(option.c)printErr("Byte "+(i+1)+": null notation \\0 (JSON5)");str[i]="u0000"}else if(str[i]==="v"){if(option.c)printErr("Byte "+(i+1)+": vertical tab \\v (JSON5)");str[i]="u000b"}else if(str[i]==="x"&&/\d|[A-Fa-f]/.test(str[i+1])&&/\d|[A-Fa-f]/.test(str[i+2])){if(option.c)printErr("Byte "+(i+1)+": hex notation \\x (JSON5)");str[i]="u00";i=i+2}else if(str[i]==="\r"&&str[i+1]==="\n"){if(option.c)printErr("Byte "+(i+1)+": \\ escaped newlines (\\r\\n) (JSON5)");str[i]="";str[i+1]="";i=i+1}else if(str[i]==="\n"||str[i]==="\r"||str[i]==="\u2028"||str[i]==="\u2029"){if(option.c)printErr("Byte "+(i+1)+": \\ escaped newline in string (JSON5)");str[i]=""}}else if(str[i]==='"'&&mode.doubleQuote||str[i]==="'"&&mode.singleQuote){if(mode.singleQuote){mode.singleQuote=false;str[i]='"'}else mode.doubleQuote=false;if(!objStack.length)makeNewText=true;else lastCharIndex=i}else if(str[i]==='"'&&mode.singleQuote)str[i]='\\"';else if(str[i]==="\\"){mode.inEscape=true;lastCharIndex=i;if(str[i+1]==="\n"||str[i+1]==="\r"&&str[i+2]==="\n")str[i]="";else if(str[i+1]==="'")str[i]=""}else if(str[i]==="\t"){if(option.c)printErr("Byte "+(i+1)+": literal tab character in string");str[i]=""}else{if(str[i]==="\n"){if(option.c)printErr("Byte "+(i+1)+": literal newline in quotes");if(option.w){if(option.c)printErr("Ignoring newline (-w)");str[i]=""}else if(option.H){if(option.c)printErr("Truncation help for JSON Text ("+(JSONTexts.length+1)+"), bytes: "+(JSONTextStartIndex+1)+"-"+(i+1));str[i]="";mode.singleQuote=false;mode.doubleQuote=false;if(objStack.length){var a;for(a=0;a<objStack.length;a++)if(objStack[a].type==="Object")if(objStack[a].state==="NEEDS_NAMESEP"){if(option.c)if(a===0)printErr("Truncation help after byte "+i+', open string, missing separator, value, object end: ":null}');else printErr("Truncation help after byte "+i+", missing separator, value, object end: :null}");str[i]+=(a===0?'"':"")+":null}"}else{if(objStack[a].state==="NEEDS_ENDER"){if(option.c)if(a===0)printErr("Truncation help after byte "+i+', open string and object end: "}');else printErr("Truncation help after byte "+i+", object end: }");str[i]+=(a===0?'"':"")+"}"}}else if(objStack[a].type==="Array")if(objStack[a].state==="NEEDS_ENDER"){if(option.c)if(a===0)printErr("Truncation help after byte "+i+', open string and array end: "]');else printErr("Truncation help after byte "+i+", array end: ]");str[i]+=(a===0?'"':"")+"]"}objStack=[]}else{if(option.c)printErr("Truncation help after byte "+i+", open string");str[i]+='"'}makeNewText=true}else makeNewText=true}}else if(mode.lineComment){if(str[i]==="\n"||str[i]==="\r"||str[i]==="\u2028"||str[i]==="\u2029")mode.lineComment=false;str[i]=""}else if(mode.blockComment)if(str[i]==="*"&&str[i+1]==="/"){str[i]="";str[i+1]="";i=i+1;mode.blockComment=false}else str[i]="";else if(mode.blockCommentXML)if(str[i]==="-"&&str[i+1]==="-"&&str[i+2]===">"){str[i]="";str[i+1]="";str[i+2]="";i=i+2;mode.blockCommentXML=false}else str[i]="";else if(/[\s\ufefe]/.test(str[i])){if(option.c&&!/[ \n\r\t]/g.test(str[i]))if(option.c)printErr("Byte "+(i+1)+": additional whitespace character +("+JSON.stringify(str[i],null,0)+") (JSON5)");if(/[\f\r\v\u2028\u2029]/g.test(str[i]))if(str[i]==="\r"&&str[i+1]==="\n")i=i+1;else str[i]="\n";else if(/[^ \n]/g.test(str[i]))str[i]=" ";if(lastCharIndex===undefined){JSONTextStartIndex=i+1;continue}if(!objStack.length&&lastCharIndex!==undefined||i===l-1)makeNewText=true}else if(str[i]==='"'||str[i]==="'"){if(str[i]==='"')mode.doubleQuote=true;else{mode.singleQuote=true;str[i]='"';if(option.c)printErr("Byte "+(i+1)+": single quoted string (JSON5)")}if(objStack.length)if(objStack.length&&objStack[0].type==="Object")if(objStack[0].state==="OBJECT_BEGIN"||objStack[0].state==="NEEDS_PROPNAME")objStack[0].state="NEEDS_NAMESEP";else{if(objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER"}else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="ARRAY_BEGIN"||objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";lastCharIndex=i}else if(str[i]===":"){if(objStack.length&&objStack[0].type==="Object"&&objStack[0].state==="NEEDS_NAMESEP")objStack[0].state="NEEDS_VALUE";lastCharIndex=i}else if(str[i]==="{")if(option.D&&objStack.length&&(str[i-1]==="\n"||objStack[0].state!=="NEEDS_VALUE"&&objStack[0].state!=="ARRAY_BEGIN")){i=i-1;if(option.c)printErr("Byte "+(i+1)+": Truncation Detected");makeNewText=true}else{if(objStack.length&&objStack[0].type==="Object"&&objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="ARRAY_BEGIN"||objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";objStack.unshift({"type":"Object","state":"OBJECT_BEGIN"});lastCharIndex=i}else if(str[i]==="[")if(option.D&&objStack.length&&(str[i-1]==="\n"||objStack[0].state!=="NEEDS_VALUE"&&objStack[0].state!=="ARRAY_BEGIN")){i=i-1;if(option.c)printErr("Byte "+(i+1)+": Truncation Detected");makeNewText=true}else{if(objStack.length&&objStack[0].type==="Object"&&objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="ARRAY_BEGIN"||objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";objStack.unshift({"type":"Array","state":"ARRAY_BEGIN"});lastCharIndex=i}else if(str[i]==="}"){if(str[lastCharIndex]===","){if(option.c)printErr("Byte "+(lastCharIndex-1)+": trailing comma (JSON5)");str[lastCharIndex]=""}objStack.shift();if(!objStack.length)makeNewText=true;else lastCharIndex=i}else if(str[i]==="]"){if(str[lastCharIndex]===","){if(option.c)printErr("Byte "+(lastCharIndex-1)+": trailing comma (JSON5)");str[lastCharIndex]=""}objStack.shift();if(!objStack.length)makeNewText=true;else lastCharIndex=i}else if(str[i]===","){lastCharIndex=i;if(objStack.length&&objStack[0].type==="Object"&&objStack[0].state==="NEEDS_ENDER")objStack[0].state="NEEDS_PROPNAME";else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="NEEDS_ENDER")objStack[0].state="NEEDS_VALUE"}else if(str[i]==="n"&&str[i+1]==="u"&&str[i+2]==="l"&&str[i+3]==="l"||str[i]==="t"&&str[i+1]==="r"&&str[i+2]==="u"&&str[i+3]==="e"||(str[i]==="f"&&str[i+1]==="a"&&str[i+2]==="l"&&str[i+3]==="s"||str[i+4]==="e")){if(objStack.length&&objStack[0].type==="Object"&&objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="ARRAY_BEGIN"||objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";var candidate=str.slice(i,i+5).join("");if(candidate.slice(i,i+4)==="true"||candidate.slice(i,i+4)==="true")lastCharIndex=i+4;if(candidate.slice(i,i+5)==="false")lastCharIndex=i+5}else if(str[i]==="+"&&(/\d/.test(str[i+1])||str[i+1]===".")){if(option.c)printErr("Byte "+(i+1)+": explicit plus + for value (JSON5)");if(objStack.length&&objStack[0].type==="Object"&&objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="ARRAY_BEGIN"||objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";str[i]=""}else if(str[i]==="."&&!/\d/.test(str[i-1])){if(option.c)printErr("Byte "+(i+1)+": decimal point wihtout preceding digit (JSON5)");if(objStack.length&&objStack[0].type==="Object"&&objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="ARRAY_BEGIN"||objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";str[i]="0.";lastCharIndex=i}else if(str[i]==="."&&!/\d/.test(str[i+1])){if(option.c)printErr("Byte "+(i+1)+": trailing decimal lacking mantissa (JSON5)");str[i]=""}else if(str[i]==="N"&&str[i+1]==="a"&&str[i+2]==="N"&&(!objStack.length||objStack[0].type==="Object"&&str[lastCharIndex]!=="{"&&str[lastCharIndex]!==","||objStack[0].type==="Array")){if(option.c)printErr("Byte "+(i+1)+": NaN for value (JSON5)");if(option["8"]){str[i]='"';str[i+1]="NaN";str[i+2]='"';i=i+2}else{str[i]="";str[i+1]="";str[i+2]="null";i=i+2}lastCharIndex=i}else if((str[i]==="-"||str[i]==="+")&&str[i+1]==="I"&&str[i+2]==="n"&&str[i+3]==="f"&&str[i+4]==="i"&&str[i+5]==="n"&&str[i+6]==="i"&&str[i+7]==="t"&&str[i+8]==="y"){if(!objStack.length||objStack[0].type==="Object"&&str[lastCharIndex]!=="{"&&str[lastCharIndex]!==","||objStack[0].type==="Array"){if(option.c)printErr("Byte "+(i+1)+": "+str[i]+"Infinity as value (JSON5)");if(option.I){str[i+6]='"';str[i+7]=str[i]+"Infinity";str[i+8]='"'}else{str[i+6]="";str[i+7]="";str[i+8]="null"}str[i]="";str[i+1]="";str[i+2]="";str[i+3]="";str[i+4]="";str[i+5]="";i=i+5}}else if(str[i]==="I"&&str[i+1]==="n"&&str[i+2]==="f"&&str[i+3]==="i"&&str[i+4]==="n"&&str[i+5]==="i"&&str[i+6]==="t"&&str[i+7]==="y"){if(option.c)printErr("Byte "+(i+1)+": Infinity as value (JSON5)");str[i]="";str[i+1]="";str[i+2]="";str[i+3]="";str[i+4]="";if(option.I){str[i+5]='"';str[i+6]="Infinity";str[i+7]='"'}else{str[i+5]="";str[i+6]="";str[i+7]="null"}i=i+4}else if(str[i]==="0"&&str[i+1]==="x"&&(!objStack.length||objStack[0].type==="Array"||objStack[0].type==="Object"&&str[lastCharIndex]===":")){if(str[i-1]==="-")var hexIndexBegin=i-1;else var hexIndexBegin=i;if(option.c)printErr("Byte "+(hexIndexBegin-1)+": 0x hex value (JSON5)");for(i=i+2;i<l;i++)if(!/[0-9A-Fa-f]/.test(str[i])||/\s/.test(str[i])||str[i]===","||str[i]==="]"||str[i]==="}"||str[i]===" "||str[i]==="\t"||str[i]==="\r"||str[i]==="\n"||str[i]===":"||str[i]==="\ufefe"){i=i-1;break}var hexIndexEnd=i;var hexString=str.slice(hexIndexBegin,hexIndexEnd+1).join("");var hexToDecimalValue=eval(hexString);str[hexIndexEnd]=hexToDecimalValue;for(var o=hexIndexBegin;o<hexIndexEnd;o++)str[o]="";if(objStack.length&&objStack[0].type==="Object"&&objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="ARRAY_BEGIN"||objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";lastCharIndex=i}else if(str[i]==="-"||/\d/.test(str[i])){if(objStack.length&&objStack[0].type==="Object"&&objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="ARRAY_BEGIN"||objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER";if(/\d/.test(str[i]))lastCharIndex=i}else if(/[$_A-Za-z]/.test(str[i])&&objStack.length&&objStack[0].type==="Object"&&(str[lastCharIndex]==="{"||str[lastCharIndex]===",")){if(option.c)printErr("Byte "+(i+1)+": unquoted object key name (JSON5)");str[i]='"'+str[i];for(i=i+1;i<str.length;i++)if(/[^$_A-Za-z0-9]/.test(str[i])){i=i-1;break}str[i]=str[i]+'"';lastCharIndex=i;if(objStack.length)if(objStack.length&&objStack[0].type==="Object")if(objStack[0].state==="OBJECT_BEGIN"||objStack[0].state==="NEEDS_PROPNAME")objStack[0].state="NEEDS_NAMESEP";else{if(objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER"}else if(objStack.length&&objStack[0].type==="Array")if(objStack[0].state==="ARRAY_BEGIN"||objStack[0].state==="NEEDS_VALUE")objStack[0].state="NEEDS_ENDER"}else if(str[i]==="/"&&str[i+1]==="*"){if(option.c)printErr("Byte "+(i+1)+": /* block comment (JSON5)");str[i]="";mode.blockComment=true}else if(str[i]==="/"&&str[i+1]==="/"){if(option.c)printErr("Byte "+(i+1)+": // line comment (JSON5)");str[i]="";mode.lineComment=true}else if(str[i]==="-"&&str[i+1]==="-"){if(option.c)printErr("Byte "+(i+1)+": -- line comment");str[i]="";mode.lineComment=true}else if(str[i]==="<"&&str[i+1]==="!"&&str[i+2]==="-"&&str[i+3]==="-"){if(option.c)printErr("Byte "+(i+1)+": \x3c!-- block comment");str[i]="";mode.blockCommentXML=true}else if(str[i]==="*"&&str[i+1]==="*"&&str[i+2]==="*"){if(option.c)printErr("Byte "+(i+1)+": *** line comment");str[i]="";mode.lineComment=true}else if(str[i]==="#"){if(option.c)printErr("Byte "+(i+1)+": # line comment");str[i]="";mode.lineComment=true}else if(str[i]===";"){if(option.c)printErr("Byte "+(i+1)+": ; line comment");str[i]="";mode.lineComment=true}else lastCharIndex=i;if(makeNewText){var tempString="";if(objStack.length&&option.H){if(option.c)printErr("Truncation help for JSON Text ("+(JSONTexts.length+1)+"), bytes: "+(JSONTextStartIndex+1)+"-"+(i+1));var a;for(a=0;a<objStack.length;a++)if(objStack[a].type==="Object")if(objStack[a].state==="NEEDS_ENDER"||objStack[a].state==="OBJECT_BEGIN"){if(option.c)printErr("Truncation help after byte "+(i+1)+", object end: }");tempString+="}"}else if(objStack[a].state==="NEEDS_PROPNAME"){if(option.c)printErr("Truncation help after byte "+(i+1)+', open string, missing value and object end: "":null}');tempString+='"":null}'}else if(objStack[a].state==="NEEDS_VALUE"){if(option.c)printErr("Truncation help after byte "+(i+1)+", missing value and object end: null}");tempString+="null}"}else{if(objStack[a].state==="NEEDS_NAMESEP"){if(option.c)printErr("Truncation help after byte "+(i+1)+", missing separator,value, and object end: :null}");tempString+=":null}"}}else if(objStack[a].type==="Array")if(objStack[a].state==="NEEDS_ENDER"||objStack[a].state==="ARRAY_BEGIN"){if(option.c)printErr("Truncation help after byte "+(i+1)+", array end: ]");tempString+="]"}else if(objStack[a].state==="NEEDS_VALUE"){if(option.c)printErr("Truncation help after byte "+(i+1)+", missing value and array end: null]");tempString+="null]"}}JSONTexts[JSONTexts.length]=str.slice(JSONTextStartIndex,i+1).join("")+tempString;if(option.c&&JSONTexts.length===1){var JSONTextStartIndex_1=JSONTextStartIndex;var JSONTextEndIndex_1=i}if(option.c&&JSONTexts.length>1){if(JSONTexts.length===2)printErr("Bytes "+(JSONTextStartIndex_1+1)+"-"+(JSONTextEndIndex_1+1)+": JSON Text (1)");printErr("Bytes "+(JSONTextStartIndex+1)+"-"+(i+1)+": JSON Text ("+JSONTexts.length+")")}JSONTextStartIndex=i+1;lastCharIndex=undefined;objStack=[];newLineCount=0;makeNewText=false;mode.singleQuote=false;mode.doubleQuote=false;mode.inEscape=false;mode.blockComment=false;mode.blockCommentXML=false;mode.lineComment=false}}return JSONTexts}if(typeof printErr==="undefined")eval("function printErr(string) { debug(string) }");var option={};var maxSize={};maxSize.print=715827882-2;maxSize.file=2147483647;var query=decodeURIComponent(escape(arguments[0]))||"$";var fileArg=decodeURIComponent(escape(arguments[1]))||"/dev/stdin";var optionsArg=arguments[2]||"";for(var i=0;i<optionsArg.length;i++)switch(optionsArg.charAt(i)){case "Q":option.Q=true;option.q=true;break;default:option[optionsArg.charAt(i)]=true;break}var spaceArgString=decodeURIComponent(escape(arguments[3]))||"2";var spaceArg=/^\s*$/.test(spaceArgString)||isNaN(spaceArgString)?spaceArgString:Number(spaceArgString);option.spaceArg=spaceArg;if(option.v||option.V)var valueArg=decodeURIComponent(escape(arguments[4]));else var valueArg=undefined;if(option.p)var pathArg=decodeURIComponent(escape(arguments[5]));option.maxDepth=arguments[6]!==""&&!isNaN(Number(arguments[6]))?Number(arguments[6]):-1;if(arguments[7][0]){option.encoding={};option.encoding[decodeURIComponent(escape(arguments[7][0]))]=true}else option.encoding="";option.opArg={};if(option.o)option.opArg[decodeURIComponent(escape(arguments[8]))]=true;if(option.f)var fromArg=decodeURIComponent(escape(arguments[9]));var JSONPatchArg=decodeURIComponent(escape(arguments[10]))||"";var multiJSONArg=decodeURIComponent(escape(arguments[11]))||"";if(option.k)option.K=true;if(option.K)option.i=true;if(typeof readFile==="function")try{var fileText=readFile(fileArg)}catch(error){printErr("File error (note: jsc max size is "+maxSize.file+" bytes): "+error);quit()}else{if(option.V){printErr('-V not available for this version of jsc\nUse -v "$(< file)" as a workaround');quit()}var fileText="";while(line=decodeURIComponent(escape(this.readline())))fileText+=line+"\n"}var JSONObjectArray=[];if(option.S){if(fileArg==="/dev/stdin")fileText=fileText.slice(0,-1);fileText='"'+fileText.replace(/[\u0000-\u001f\u007f-\uffff|"|\\]/g,function(chr){switch(chr){case '"':return'\\"';case "\\":return"\\\\";case "\b":return"\\b";case "\f":return"\\f";case "\n":return"\\n";case "\r":return"\\r";case "\t":return"\\t";default:return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)}})+'"';try{JSONObjectArray[0]=JSON.parse(fileText)}catch(error){printErr("JSON Input Data: "+error);quit()}}else if(/\u001e/.test(fileText)){var tempJSONArray=fileText.split("\u001e");var tempJSONArray_preRS=tempJSONArray.shift();if(tempJSONArray_preRS)printErr("Error: JSON Sequence text (0) lacking leading Record Seperator (\\u001e): "+tempJSONArray_preRS);for(var i=0,j=0;i<tempJSONArray.length;i++){if(tempJSONArray[i]===""||!/\S/.test(tempJSONArray[i]))continue;if(/^\s*\$/.test(tempJSONArray[i])){try{JSONObjectArray[j]=ingestLiterals(tempJSONArray[i],option);var lastParse=1}catch(e){printErr(e);var lastParse=0}if(lastParse)j=j+1}else{try{JSONObjectArray[j]=JSON.parse(tempJSONArray[i]);var lastParse=1}catch(error){printErr("Error: Unable to parse JSON Sequence text ("+i+"): "+tempJSONArray[i]);var lastParse=0}if(lastParse&&(JSONObjectArray[j]===null||JSONObjectArray[j].constructor===Number||JSONObjectArray[j].constructor===Boolean)&&!/\s/.test(tempJSONArray[i][tempJSONArray[i].length-1])){printErr("Error: JSON text sequence ("+(i+1)+") lacking trailing whitespace: "+tempJSONArray[i]);JSONObjectArray[j]=undefined}else if(lastParse)j=j+1}}}else if(/^\s*\$/.test(fileText))try{JSONObjectArray[0]=ingestLiterals(fileText,option)}catch(e){printErr(e);quit()}else try{JSONObjectArray[0]=JSON.parse(fileText)}catch(error){var primaryParseErrorString=error;if(option.c)printErr("Original error: "+error);var tempJSONArray=rehabJSON(fileText);for(var i=0,j=0;i<tempJSONArray.length;i++,j++)try{JSONObjectArray[j]=JSON.parse(tempJSONArray[i])}catch(error){printErr("Error in JSON Text ("+(i+1)+"): "+tempJSONArray[i].substring(0,24).replace(/[\n|\r]/g,"")+"\u2026");printErr(error);j=j-1}}if(multiJSONArg=="a"){var JSONObjectArray_temp=[];for(var i=0;i<=JSONObjectArray.length-1;i++)JSONObjectArray_temp[i]=JSONObjectArray[i];JSONObjectArray=[];JSONObjectArray[0]=JSONObjectArray_temp}var resultObjects=[];for(var i=0;i<JSONObjectArray.length;i++){if(option.x||option.X||option.opArg.constructor===Object&&Object.keys(option.opArg).length)try{JSONObjectArray[i]=alterObject(JSONObjectArray[i],valueArg,fromArg,pathArg,option,i+1,JSONPatchArg)}catch(e){printErr(e);continue}if((query==="$"||query==="")&&!option.j&&!option.r)resultObjects[i]=[JSONObjectArray[i]];else{try{var queryObject=objectifyExpressions([query],{"disallowData":true,"allowExpressions":true,"c":option.c})[0].path}catch(error){printErr(error);quit()}try{resultObjects[i]=jsonPath(JSONObjectArray[i],queryObject,option.j||option.r?{"resultType":option.d?"PATH_DOTTED":option.r?"PATH_JSONPOINTER":"PATH","singleQuoteKeys":option.q,"P.escapeUnicode":option.u?true:false}:null)}catch(error){printErr(error);quit()}}if(!resultObjects[i].length){printErr("No nodes matching "+query+(JSONObjectArray.length>1?" in JSON text "+(i+1):""));resultObjects[i]=undefined}}for(var i=0;i<=resultObjects.length-1;i++){if(resultObjects[i]===undefined)continue;if(Array.isArray(resultObjects[i])&&resultObjects[i].length===1)resultObjects[i]=resultObjects[i][0];if(option.N&&resultObjects[i]!==null)while(Array.isArray(resultObjects[i])&&resultObjects[i].length===1){if(!resultObjects[i]===null&&(option.a&&resultObjects[i][0].constructor===Object))break;if(!resultObjects[i].some(function(val){return val!=null&&typeof val==="object"}));resultObjects[i]=resultObjects[i][0]}if(option.a&&!Array.isArray(resultObjects[i]))resultObjects[i]=[resultObjects[i]];if(option.t&&(resultObjects[i]===null||!(Array.isArray(resultObjects[i])||resultObjects[i].constructor===Object)))option.T=true;if(option.l){if(resultObjects[i]===null)print("0");else if(resultObjects[i].constructor===Number)print("1");else if(resultObjects[i].constructor===Boolean)print("1");else if(resultObjects[i].constructor===String)print(resultObjects[i].length);else if(Array.isArray(resultObjects[i]))print(resultObjects[i].length);else if(resultObjects[i].constructor===Object)print(Object.keys(resultObjects[i]).length);continue}if(option.O)resultObjects[i]=sortObject(resultObjects[i]);if(option.F&&Array.isArray(resultObjects[i]))resultObjects[i]=flatten(resultObjects[i])}if(option.l)quit();if(multiJSONArg=="A"){var resultObjects_new=[[]];for(var i=0;i<=resultObjects.length-1;i++)resultObjects_new[0][i]=resultObjects[i];resultObjects=resultObjects_new}for(var i=0;i<=resultObjects.length-1;i++){if(resultObjects[i]===undefined)continue;if(option.T||option.L||option.J||option.R||option.j||option.r){if(!option.j&&!option.r)resultObjects[i]=renderObject(resultObjects[i],!option.T?option.R?"":"$":null,option);if(resultObjects[i]===null)var resultText=option.n?"null":undefined;else if(Array.isArray(resultObjects[i]))var resultText=resultObjects[i].join("\n");else var resultText=resultObjects[i].toString()}else{if(multiJSONArg=="N")spaceArg=0;try{var resultText=JSON.stringify(resultObjects[i],null,spaceArg).replace(option.u?/[\u007f-\uFFFF]/g:/[\u007f]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)}).replace(option["/"]?/[\/]/g:undefined,"\\/")}catch(error){printErr("JSON.stringify: "+error)}}if((option.encoding.w||option.encoding.W)&&(option.r||option.R))resultText=resultText.split("\n").map(function(a){return"#"+encodeURI(a)}).join("\n");if(!option.T&&(multiJSONArg=="S"||resultObjects.length>1&&!multiJSONArg))var possibleRS="\u001e";else var possibleRS="";if(resultText===undefined)continue;else if(resultText.length>maxSize.print)jscChunkPrint(possibleRS+resultText);else try{print(possibleRS+resultText)}catch(error){printErr("print "+error)}};
EOT

		#shell script
		locations=( "/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Helpers/jsc" "/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc" );for loc in ${locations[@]}; do [ -x "${loc}" ] && jsc="${loc}" && break; done;[ -z "${jsc}" ] && jsc=$(which jsc);if [ -z "${jsc}" ]; then locations=( "/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current" "/usr/bin/jsc" "/usr/libexec/webkit2gtk*" );for loc in ${locations[@]}; do jsc=$(find -L "${loc}" -name 'jsc' -maxdepth 2 2>/dev/null);[ -n "${jsc}" ] && break;done;fi;[ -z "${jsc}" ] && echo "Unable to locate a jsc binary!" && exit 1;[ -n "$BASH_VERSION" ] && unset OPTIND OPTARG;while getopts ":8cKkDSQPAE:Ff:lNLOuo:i:aCIeHhdnqgGJzjsRrTtUWwZ:v:V:x:X:p:M:%/" option; do case "${option}" in 'J'|'L'|'R'|'t'|'j'|'l'|'r'|'t') [ -z "${outputOpt}" ] && outputOpt="${option}" ;;'o')[ -z "${alterOp}" ] && { options+="${option}"; alterOp="${OPTARG}"; } ;;'p')[ -z "${pathArg}" ] && { options+="${option}"; pathArg="${OPTARG}"; } ;;'v'|'V')[ -z "${valueArg}" ] && { options+="${option}"; valueArg="${OPTARG}"; } ;;'f')[ -z "${fromArg}" ] && { options+="${option}"; fromArg="${OPTARG}"; } ;;'x'|'X')[ -z "${JSONPatchArg}" ] && { options+="${option}"; JSONPatchArg="${OPTARG}"; } ;;'i')options+="${option}"; spaceArg="${OPTARG}";;'M')options+="${option}"; multiOutArg="${OPTARG}";;'Z')depthArg="${OPTARG}";;'E')[ -z "${encodingArg}" ] && encodingArg+="${OPTARG/\%/W}";;'h')echo -e "${helpText}" | less; exit;;'?'):;;*)options+="${option}";;esac;done;options+="${outputOpt}";[ $OPTIND -ge 2 ] && shift $((OPTIND-1));queryArg="${1}";fileArg="${2}";[ -f "${queryArg}" ] && [ -z "${fileArg}" ] && { fileArg="${queryArg}"; unset queryArg; };readFileSupport="$(${jsc} -e 'print(typeof readFile === "function")')";if [ -n "${fileArg}" ]; then if [ "${fileArg}" != '/dev/stdin' ] && ! [ -f "${fileArg}" ]; then echo "--> File not found: ${fileArg}" >&2;return 1;elif ! [ -r "${fileArg}" ]; then echo "--> File not readable: ${fileArg}" >&2;return 1;fi;if [ "${readFileSupport}" = "true" ]; then if stat -f %z . &> /dev/null; then fileSize=$(stat -f %z "${fileArg}");elif stat -c %s . &> /dev/null; then fileSize=$(stat -c %s "${fileArg}");elif stat --format %s . &> /dev/null; then fileSize=$(stat --format %s "${fileArg}");fi;if [ "${fileSize}" -ge 2147483648 ]; then echo "--> File exceeds readFile() maximum size (2GiB)!" >&2;return 1;fi;fi;fi;if [ "${readFileSupport}" = "false" ]; then { errOut=$( { { "${jsc}" -e "${JSCode}" -- "${queryArg}" "" "${options}" "${spaceArg}" "${valueArg}" "${pathArg}" "${depthArg}" "${encodingArg}" "${alterOp}" "${fromArg}" "${JSONPatchArg}" "${multiOutArg}" <<< "$(sed '/^$/d' "${fileArg:-/dev/stdin}")" ; } 1>&3 ; } 2>&1); } 3>&1;elif [ -f "${fileArg:=/dev/stdin}" ]; then { errOut=$( { { "${jsc}" -e "${JSCode}" -- "${queryArg}" "${fileArg}" "${options}" "${spaceArg}" "${valueArg}" "${pathArg}" "${depthArg}" "${encodingArg}" "${alterOp}" "${fromArg}" "${JSONPatchArg}" "${multiOutArg}"; } 1>&3 ; } 2>&1); } 3>&1;else [ -t '0' ] && echo -e "$(echo -e "${helpText}" | head -n 1)\nUsage: jpt [options] [query] [filepath] (see jpt -h for more help...)" >/dev/stderr && exit 0; { errOut=$( { { "${jsc}" -e "${JSCode}" -- "${queryArg}" "/dev/stdin" "${options}" "${spaceArg}" "${valueArg}" "${pathArg}" "${depthArg}" "${encodingArg}" "${alterOp}" "${fromArg}" "${JSONPatchArg}" "${multiOutArg}" <<< "$(cat)"; } 1>&3 ; } 2>&1); } 3>&1;fi;if [ -n "$(sed -e '/^--> Debug:/d' <<< "${errOut}")" ]; then /bin/echo "$errOut" >&2; return 1; fi
	)

	consoleUser=$(stat -f %Su /dev/console);

	#if root grab the last console user
	if [ "${consoleUser}" = "root" ]; then
		consoleUser=$(/usr/bin/last -1 -t console | awk '{print $1}')
	fi


	userPref_json=$(sudo -u $consoleUser defaults export MobileMeAccounts - | plutil -convert json - -o -)

	#pref domain not found an empty object is returned
	if [ "${userPref_json}" = "{}" ]; then
		return 1
	else
		#returns the number paths that match
		matchingPathCount=$(jpt -r '$.Accounts[*].Services[?(@.Name == "MOBILE_DOCUMENTS" && @.Enabled == true)]' <<< "${userPref_json}" 2>/dev/null | wc -l | tr -d "[[:space:]]")
	
		if [ ${matchingPathCount:=0} -eq 0 ]; then
			return 1
		else
			return 0
		fi
	fi

)
########
# MAIN #
########

#example function usage, if leverages the return values
if iCloudDrive; then
	echo "iCloud Drive is ON"
	exit 0
else
	echo "iCloud Drive is OFF"
	exit 1
fi