UNPKG

json-object-editor

Version:

JOE the Json Object Editor | Platform Edition

1,253 lines (1,215 loc) 456 kB
/*/---------------------------------------------------------/*/ /*/ Craydent LLC v1.8.1 /*/ /*/ Copyright 2011 (http://craydent.com/about) /*/ /*/ Dual licensed under the MIT or GPL Version 2 licenses. /*/ /*/ (http://craydent.com/license) /*/ /*/---------------------------------------------------------/*/ /*---------------------------------------------------------------------------------------------------------------- /- Global CONSTANTS and variables /---------------------------------------------------------------------------------------------------------------*/ var __version = "1.8.1", __thisIsNewer = true, $w = typeof window != "undefined" ? window : {location:(typeof location != "undefined"?location:{href:''}),console:(typeof console != "undefined"?console:{})}, $g = $w, $d = typeof document != "undefined" ? document : {}, $l = $w.location; if ($w.__craydentLoaded || typeof($c) != "undefined") { var __current = ($w.__craydentVersion||$c.VERSION||"").split("."), __thisVersion = __version.split("."); if(__thisIsNewer = __isNewer(__current,__thisVersion)) { $c.VERSION = __version; } } function __isNewer(loadedVersion, thisVersion){ if (loadedVersion[0] == thisVersion[0]) { loadedVersion.splice(0,1); thisVersion.splice(0,1); if (!thisVersion.length || !loadedVersion.length) { return false; } return __isNewer(loadedVersion, thisVersion); } return parseInt(loadedVersion[0]) < parseInt(thisVersion[0]); } function __cleanUp() { try { delete $w.__current; delete $w.__thisVersion; delete $w.__thisIsNewer; delete $w.__isNewer; delete $w.__version; delete $w._ie; delete $w._droid; delete $w._amay; delete $w._browser; delete $w._os; delete $w._device; delete $w._engine; } catch(e) { $w.__current = undefined; $w.__thisVersion = undefined; $w.__thisIsNewer = undefined; $w.__isNewer = undefined; $w.__version = undefined; $w._ie = undefined; $w._droid = undefined; $w._amay = undefined; $w._browser = undefined; $w._os = undefined; $w._device = undefined; $w._engine = undefined; } } $w.__craydentVersion = __version; if (__thisIsNewer) { var _ao,_ah, _df, _irregularNouns = { "addendum":"addenda", "alga":"algae", "alumna":"alumnae", "apparatus":"apparatuses", "appendix":"appendices", "bacillus":"bacilli", "bacterium":"bacteria", "beau":"beaux", "bison":"bison", "bureau":"bureaus", "child":"children", "corps":"corps", "corpus":"corpora", "curriculum":"curricula", "datum":"data", "deer":"deer", "die":"dice", "diagnosis":"diagnoses", "erratum":"errata", "fireman":"firemen", "focus":"focuses", "foot":"feet", "genus":"genera", "goose":"geese", "index":"indices", "louse":"lice", "man":"men", "matrix":"matrices", "means":"means", "medium":"media", "memo":"memos", "memorandum":"memoranda", "moose":"moose", "mouse":"mice", "nebula":"nebulae", "ovum":"ova", "ox":"oxen", "person":"people", "radius":"radii", "series":"series", "sheep":"sheep", "scissors":"scissors", "species":"species", "stratum":"strata", "syllabus":"syllabi", "tableau":"tableaux", "that":"those", "this":"these", "tooth":"teeth", "vertebra":"vertebrae", "vita":"vitae", "woman":"women", "zero":"zeros" }; /*---------------------------------------------------------------------------------------------------------------- /- define functions preventing overwriting other framework functions /---------------------------------------------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------------------------------------------- /- private methods /---------------------------------------------------------------------------------------------------------------*/ function __add_fillTemplate_ref (obj){ try { var uid = suid(); fillTemplate.refs["ref_" + fillTemplate.refs.length] = uid; fillTemplate.refs[uid] = obj; fillTemplate.refs.push(obj); return uid; } catch (e) { error('fillTemplate.__add_fillTemplate_ref', e); } } function __and (){ try { var a = 0; for (len = arguments.length; a < len; a++) { var arg = arguments[a]; if (!arg) { return ""; } } return arguments[a - 1]; } catch (e) { error('fillTemplate.__and', e); } } function __clean_micro_templates () { var _micro_templates = fillTemplate._micro_templates; for (var id in _micro_templates) { if (!_micro_templates.hasOwnProperty(id)) { continue; } if (!$CSS("[data-craydent-bind*='"+id+"']").length) { delete _micro_templates[id]; } } } function __contextualizeMethods (ctx) { try { ctx = ctx || {}; ctx.Benchmarker = Benchmarker; ctx.Cursor = Cursor; ctx.JSZip = JSZip; ctx.OrderedList = OrderedList; ctx.Queue = Queue; ctx.Set = Set; ctx.addObjectPrototype = addObjectPrototype; ctx.ajax = ajax; ctx.cout = cout; ctx.cuid = cuid; ctx.emit = emit; ctx.error = error; ctx.fillTemplate = fillTemplate; ctx.foo = foo; ctx.isNull = isNull; ctx.logit = logit; ctx.namespace = namespace; ctx.next = next; ctx.now = now; ctx.parseBoolean = parseBoolean; ctx.parseRaw = parseRaw; ctx.rand = rand; ctx.suid = suid; ctx.syncroit = syncroit; ctx.tryEval = tryEval; ctx.wait = wait; ctx.xmlToJson = xmlToJson; ctx.yieldable = yieldable; ctx.zipit = zipit; return ctx; } catch (e) { error('__contextualizeMethods', e); } } function __convert_regex_safe(reg_str) { try { return reg_str.replace(/\\/gi,"\\\\") .replace(/\$/gi, "\\$") .replace(/\//gi, "\\/") .replace(/\^/gi, "\\^") .replace(/\./gi, "\\.") .replace(/\|/gi, "\\|") .replace(/\*/gi, "\\*") .replace(/\+/gi, "\\+") .replace(/\?/gi, "\\?") .replace(/\!/gi, "\\!") .replace(/\{/gi, "\\{") .replace(/\}/gi, "\\}") .replace(/\[/gi, "\\[") .replace(/\]/gi, "\\]") .replace(/\(/gi, "\\(") .replace(/\)/gi, "\\)") .replace('\n','\\n'); } catch (e) { error('__convert_regex_safe', e); } } function __count(arr){ try { return arr.length; } catch (e) { error('fillTemplate.count', e); } } function __dup (old) { try { for (var prop in old){ if (!old.hasOwnProperty(prop)) { continue; } this[prop] = old[prop]; } } catch (e) { error('__dup', e); } } function __enum(obj, delimiter, prePost){ try { delimiter = delimiter || ", "; prePost = prePost || ["",""]; var props = [], str = ""; if ($c.isArray(obj)) { props = obj.slice(0); } else if ($c.isObject(obj)) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { props.push(prop); } } } for (var i = 0, len = props.length; i < len; i++) { var prop = props[i]; var pre = $c.replace_all(prePost[0],['{ENUM_VAR}','{ENUM_VAL}'],[prop,obj[prop]]), post = $c.replace_all(prePost[1],['{ENUM_VAR}','{ENUM_VAL}'],[prop,obj[prop]]); str += pre + prop + post + delimiter; } return str.slice(0,-1*delimiter.length); } catch (e) { error('fillTemplate.enum', e); } } function __logic_parser (code, obj, bind) { if (!code) { return ""; } var ttc = $c.TEMPLATE_TAG_CONFIG, indexes = [], logic = {}; code = $c.replace_all(code,ttc.IGNORE_CHARS,['']); $c.eachProperty(ttc, function (value) { if (!value.begin) { return; } var index = $c.indexOfAlt(code,value.begin); indexes.push(index); logic[index] = value; }); var index = Math.min.apply(Math,$c.condense(indexes,[-1])); if (!logic[index]) { return code; } return code.substring(0,index) + logic[index].parser(code.substring(index),obj, bind); } function __observe_helper (objs, callback, acceptList, parent) { try { if ($c.isObject(objs)) { return observe(objs, callback, acceptList, parent); } if (!$c.isArray(objs)) { return; } var i = 0, obj; while (obj = objs[i++]) { if (!$c.isObject(obj)) { continue; } observe(obj, callback, acceptList, parent); } } catch(e) { error('observe.observe_helper', e); } } function __on_observable_change (changes) { try { var change = changes[0], obj = change.object, prop = change.name, value = change.oldValue; var _observing = fillTemplate._observing, _micro_templates = fillTemplate._micro_templates; // change values if (obj[prop] != value) { var id_index = _observing.indexOf(obj); var hash = _observing["hash_"+id_index], pattern = new RegExp(hash+"[a-zA-Z0-9,]*\."+prop+";?|$"), nodes = Array.prototype.slice.call($CSS("[data-craydent-bind*='"+hash+"']")||[]).filter(function(node){ return pattern.test(node.getAttribute("data-craydent-bind")); }); if (!$CSS("[data-craydent-bind*='"+hash+"']").length) { delete _observing["hash_" + id_index]; return; } var i = 0, node; while (node = nodes[i++]) { if (node.isOrphan()) { continue; } var id = node.getAttribute("data-craydent-bind").split(":")[0], tobj = $c.getProperty(_observing,"parents_"+id_index + ".0") || obj; nodes[i - 1].replace(fillTemplate(_micro_templates[id].template.replace_all("${craydent_bind}",hash),tobj).toDomElement()); } } } catch(e) { error('observe.on_observable_change', e); } } function __or (){ try { for (var a = 0, len = arguments.length; a < len; a++) { var arg = arguments[a]; if(arg){ return arg; } } return ""; } catch (e) { error('fillTemplate.__or', e); } } function __processBlocks (start, end, code, lookups) { lookups = lookups || {}; var blocks = [], sindexes = [], sindex = 0, eindexes = [], eindex = 0; while ((sindex = $c.indexOfAlt(code,start, sindex)) != -1 && (eindex = $c.indexOfAlt(code,end, eindex)) != -1) { sindex != -1 && (sindexes.push(sindex), sindex++); eindex != -1 && (eindexes.push(eindex), eindex++); } // if true syntax error, start end missmatch if (sindexes.length != eindexes.length) { blocks.push({id: "##" + suid() + "##", block: "", body:"", code: code}); return blocks; } var j, pairs = OrderedList([], function (a, b) { if (a.end < b.end) { return -1; } if (a.end > b.end) { return 1; } return 0; }); while (sindexes.length) { var e = 0; while (eindexes[0] > sindexes[e]) { e++; } e--; pairs.add({begin: sindexes[e], end: eindexes[0]}); $c.removeAt(sindexes,e); $c.removeAt(eindexes,0); } var endlength = code.match(end)[0].length; var k = 0, pair; while (pair = pairs[k++]) { var uid = "##" + suid() + "##", block = code.slice(pair.begin, pair.end + endlength), beginLength = block.match(start)[0].length, body = code.slice(pair.begin + beginLength, pair.end); code = code.replace(block, uid); blocks.push({id: uid, block: block, body: body, code: code}); lookups[uid] = block; var i = k, pair2; while (pair2 = pairs[i++]) { var offset = block.length - uid.length; pair2.end -= offset; if (pair2.begin > pair.end) { pair2.begin -= offset; } } } return blocks.reverse(); } function __parseArithmeticExpr (doc,expr,field) { try { var value; switch (field) { case "$add": value = 0; var i = 0, sexp; while (sexp = expr["$add"][i++]) { value += __processExpression(doc, sexp); } return value; case "$subtract": return __processExpression(doc, expr["$subtract"][0]) - __processExpression(doc, expr["$subtract"][1]); case "$multiply": value = 1; var i = 0, sexp; while (sexp = expr["$multiply"][i++]) { value *= __processExpression(doc, sexp) || 0; } return value; case "$divide": return __processExpression(doc, expr["$divide"][0]) / __processExpression(doc, expr["$divide"][1]); case "$mod": return __processExpression(doc, expr["$mod"][0]) % __processExpression(doc, expr["$mod"][1]); } } catch (e) { error('aggregate.__parseArithmeticExpr', e); } } function __parseArrayExpr (doc,expr,field) { try { switch (field) { case "$size": return (__processExpression(doc, expr[field], field) || []).length; } } catch (e) { error('aggregate.__parseArrayExpr', e); } } function __parseBooleanExpr (doc,expr,field) { try { var arr = [], i = 0, obj; switch (field) { case "$and": arr = expr["$and"]; while (obj = arr[i++]) { if (!__processExpression(doc, arr)) { return false; } } return true; case "$or": arr = expr["$or"]; while (obj = arr[i++]) { if (__processExpression(doc, arr)) { return true; } } return false; case "$not": arr = expr["$not"]; return !__processExpression(doc, arr[0]); } } catch (e) { error('aggregate.__parseBooleanExpr', e); } } function __parseComparisonExpr (doc,expr,field) { try { var sortOrder = [ undefined, null, Number, typeof Symbol != "undefined" ? Symbol : "Symbol", String, Object, Array, typeof BinData != "undefined" ? BinData : "BinData", typeof ObjectId != "undefined" ? ObjectId : "ObjectId", Boolean, Date, typeof Timestamp != "undefined" ? Timestamp : "Timestamp", RegExp], value1 = __processExpression(doc, expr[field][0]), value2 = __processExpression(doc, expr[field][1]), cmp = null; if (value1 == value2) { cmp = 0; } if (value1 < value2) { cmp = -1; } if (value1 > value2) { cmp = 1; } if ($c.isNull(cmp)) { value1 = sortOrder.indexOf([null, undefined].indexOf(value1) != -1 ? value1 : value1.constructor); value2 = sortOrder.indexOf([null, undefined].indexOf(value2) != -1 ? value2 : value2.constructor); if (value1 < value2) { cmp = -1; } if (value1 > value2) { cmp = 1; } } switch (field) { case "$cmp": return cmp; case "$eq": return cmp === 0; case "$gt": return cmp === 1; case "$gte": return cmp === 1 || cmp === 0; case "$lt": return cmp === -1; case "$lte": return cmp === -1 || cmp === 0; case "$ne": return cmp !== 0; } } catch (e) { error('aggregate.__parse', e); } } function __parseCond(doc,expr){ try { if (!$c.isObject(expr) || !expr['$cond']) { return expr; } // parse $cond var condition = expr['$cond'], boolExpression, thenStatement, elseStatement; if ($c.isArray(condition)) { boolExpression = condition[0]; thenStatement = condition[1]; elseStatement = condition[2]; } else { boolExpression = condition["if"]; thenStatement = condition["then"]; elseStatement = condition["else"]; } return __processExpression(doc, boolExpression) ? thenStatement : elseStatement; } catch (e) { error('aggregate.__parseCond', e); } } function __parseConditionalExpr (doc,expr,field) { try { switch (field) { case "$cond": return __parseCond(doc, expr); case "$ifNull": var value = __processExpression(doc, expr["$ifNull"][0]); return isNull(value) ? __processExpression(doc, expr["$ifNull"][1]) : value; } } catch (e) { error('aggregate.__parseConditionExpr', e); } } function __parseDateExpr (doc,expr,field) { var dt = __processExpression(doc, expr[field]); try { switch (field) { case "$dayOfYear": return dt.getDayOfYear(); case "$dayOfMonth": return dt.getDate(); case "$dayOfWeek": return dt.getDay() + 1; case "$year": return dt.getFullYear(); case "$month": return dt.getMonth() + 1; case "$week": return dt.getWeek(); case "$hour": return dt.getHours(); case "$minute": return dt.getMinutes(); case "$second": return dt.getSeconds(); case "$millisecond": return dt.getMilliseconds(); case "$dateToString": dt = __processExpression(doc, expr[field].date); return $c.format(dt,expr[field].format); } } catch (e) { error('aggregate.__parseDateExpr', e); } } function __parseSetExpr (doc,expr,field) { try { var i = 1, exp, j = 0, st; switch (field) { case "$setEquals": while (exp = expr[field][i++]) { var set1 = $c.duplicate(__processExpression(doc, expr[field][i - 2])), set2 = $c.duplicate(__processExpression(doc, exp)); if (!$c.isArray(set1) || !$c.isArray(set2)){ //noinspection ExceptionCaughtLocallyJS throw "Exception: All operands of $setEquals must be arrays. One argument is of type: " + (typeof (!$c.isArray(set1) ? set1 : set2)).captialize(); } $c.toSet(set1); $c.toSet(set2); if (set1.length != set2.length) { return false; } for (var jlen = set1.length; j < jlen; j++) { if (set2.indexOf(set1[j]) == -1) { return false; } } } return true; case "$setIntersection": var rtnSet = $c.duplicate(__processExpression(doc, expr[field][0])), errorMessage = "Exception: All operands of $setIntersection must be arrays. One argument is of type: "; if(!$c.isArray(rtnSet)) { //noinspection ExceptionCaughtLocallyJS throw errorMessage + (typeof rtnSet).captialize(); } $c.toSet(rtnSet); while (exp = expr[field][i++]) { var set1 = $c.duplicate(__processExpression(doc, exp)); if (!$c.isArray(set1)){ //noinspection ExceptionCaughtLocallyJS throw errorMessage + + (typeof set1).captialize(); } $c.toSet(set1); if (set1.length < rtnSet.length) { var settmp = set1; set1 = rtnSet; rtnSet = settmp; } for (var jlen = rtnSet.length; j < jlen; j++) { if (set1.indexOf(rtnSet[j]) == -1) { $c.removeAt(rtnSet,j--); jlen--; } } if (!rtnSet.length) { return rtnSet; } } return rtnSet; case "$setUnion": var rtnSet = $c.duplicate(__processExpression(doc, expr[field][0])), errorMessage = "Exception: All operands of $setUnion must be arrays. One argument is of type: "; if(!$c.isArray(rtnSet)) { //noinspection ExceptionCaughtLocallyJS throw errorMessage + (typeof rtnSet).captialize(); } while (exp = expr[field][i++]) { var arr = $c.duplicate(__processExpression(doc, exp)); if (!$c.isArray(arr)){ //noinspection ExceptionCaughtLocallyJS throw errorMessage + + (typeof arr).captialize(); } rtnSet = rtnSet.concat(arr); } return $c.toSet(rtnSet); case "$setDifference": var arr1 = $c.duplicate(__processExpression(doc, expr[field][0])), arr2 = $c.duplicate(__processExpression(doc, expr[field][1])), rtnSet = []; if (!$c.isArray(arr1) || !$c.isArray(arr2)){ //noinspection ExceptionCaughtLocallyJS throw "Exception: All operands of $setEquals must be arrays. One argument is of type: " + (typeof (!$c.isArray(arr1) ? arr1 : arr2)).captialize(); } for (var jlen = arr1.length; j < jlen; j++) { var st = arr1[j]; if (arr2.indexOf(st) == -1 && rtnSet.indexOf(st) == -1) { rtnSet.push(st); } } return rtnSet; case "$setIsSubset": var arr1 = $c.duplicate(__processExpression(doc, expr[field][0])), arr2 = $c.duplicate(__processExpression(doc, expr[field][1])), rtnSet = []; if (!$c.isArray(arr1) || !$c.isArray(arr2)){ //noinspection ExceptionCaughtLocallyJS throw "Exception: All operands of $setEquals must be arrays. One argument is of type: " + (typeof (!$c.isArray(arr1) ? arr1 : arr2)).captialize(); } return $c.isSubset(arr1,arr2); case "$anyElementTrue": var arr1 = $c.duplicate(__processExpression(doc, expr[field][0])), falseCondition = [undefined,null,0,false]; while (st = arr1[j++]) { if (falseCondition.indexOf(st) == -1) { return true; } } return false; case "$allElementsTrue": var arr1 = $c.duplicate(__processExpression(doc, expr[field][0])), falseCondition = [undefined,null,0,false]; for (var jlen = arr1.length; j < jlen; j++) { if (falseCondition.indexOf(arr1[j]) != -1) { return false; } } return true; } } catch (e) { error('aggregate.__parseSetExpr', e); } } function __parseStringExpr (doc,expr,field) { try { switch (field) { case "$concat": var value = "", i = 0, exp; while (exp = expr["$concat"][i++]) { value += __processExpression(doc, exp); } return value; case "$substr": var index = expr["$substr"][1], length = expr["$substr"][2] < 0 ? undefined : expr["$substr"][2]; return __processExpression(doc, expr["$substr"][0]).substr(index, length); case "$toLower": return (__processExpression(doc, expr["$toLower"]) || "").toLowerCase(); case "$toUpper": return (__processExpression(doc, expr["$toLower"]) || "").toUpperCase(); case "$strcasecmp": var value1 = (__processExpression(doc, expr["$strcasecmp"][0]) || "").toString(), value2 = (__processExpression(doc, expr["$strcasecmp"][1]) || "").toString(); if (value1 == value2) { return 0; } if (value1 < value2) { return -1; } if (value1 > value2) { return 1; } } } catch (e) { error('aggregate.__parseStringExpr', e); } } function __parseVariableExpr (doc,expr,field) { try { switch (field) { case "$map": var input = __processExpression(doc, expr[field].input), v_as = "$" + expr[field].as, v_in = expr[field]["in"]; for (var i = 0, len = input.length; i < len; i++) { doc[v_as] = input[i]; input[i] = __processExpression(doc, v_in); delete doc[v_as]; } return input; case "$let": var vars = expr[field].vars, rmProps = [], rtn = null, i = 0, rmprop; for (var prop in vars) { if (!vars.hasOwnProperty(prop)) { continue; } doc["$" + prop] = __processExpression(doc, vars[prop]); rmProps.push(prop); } rtn = __processExpression(doc, expr[field]["in"]); for (var i = 0, len = rmProps.length; i < len; i++) { delete doc[rmProps[i]]; } return rtn; } } catch (e) { error('aggregate.__parseVariableExpr', e); } } function __processAccumulator (doc,accumulator,previousValue,meta) { try { var value = __processExpression(doc, accumulator["$sum"] || accumulator["$avg"] || accumulator["$first"] || accumulator["$last"] || accumulator["$max"] || accumulator["$min"] || accumulator["$push"] || accumulator["$addToSet"] || accumulator["$stdDevPop"] || accumulator["$stdDevSamp"] ); switch (true) { case !!accumulator["$sum"]: return (value || 0) + (previousValue || 0); case !!accumulator["$avg"]: previousValue = previousValue || []; if (!$c.isNull(value)) { previousValue.push(value); } if (meta.length == meta.index + 1) { previousValue = $c.average(previousValue); } return previousValue; case !!accumulator["$first"]: if($c.isNull(previousValue)) { previousValue = value; } return previousValue; case !!accumulator["$last"]: return $c.isNull(value) ? previousValue : value; case !!accumulator["$max"]: if ($c.isNull(previousValue)) { previousValue = -9007199254740991; } if ($c.isNull(value)) { value = -9007199254740991 } if (meta.length == meta.index + 1 && value == previousValue == -9007199254740991) { return undefined; } return Math.max(value, previousValue); case !!accumulator["$min"]: if ($c.isNull(previousValue)) { previousValue = 9007199254740991; } if ($c.isNull(value)) { value = 9007199254740991 } if (meta.length == meta.index + 1 && value == previousValue == 9007199254740991) { return undefined; } return Math.min(value, (previousValue || 9007199254740991)); case !!accumulator["$push"]: previousValue = previousValue || []; if (!$c.isNull(value)) { previousValue.push(value); } return previousValue; case !!accumulator["$addToSet"]: previousValue = previousValue || []; if (!$c.isNull(value) && previousValue.indexOf(value) == -1) { previousValue.push(value); } return previousValue; case !!accumulator["$stdDevSamp"]: if (meta.sample && meta.sample.indexOf(doc) != -1) { if (!$c.isNull(value)) { previousValue = previousValue || []; previousValue.push(value); } } if (meta.length == meta.index + 1) { previousValue = $c.stdev(previousValue || []); } return $c.isNull(previousValue) ? null : previousValue; case !!accumulator["$stdDevPop"]: if (!$c.isNull(value)) { previousValue = previousValue || []; previousValue.push(value); } if (meta.length == meta.index + 1) { previousValue = $c.stdev(previousValue); } return $c.isNull(previousValue) ? null : previousValue; } } catch (e) { error('aggregate.__processAccumulator', e); } } function __processAttributes(node) { try { var obj = {}, tagend = node.indexOf('>'), tag = node.substring(1, tagend), attIndex = $c.indexOfAlt(tag,/\s|>/), nodename = attIndex == -1 ? tag : tag.substring(0, $c.indexOfAlt(tag,/\s|>/)), attr = attIndex == -1 ? "" : tag.substring($c.indexOfAlt(tag,/\s|>/)), text = node.substring(tagend + 1, node.indexOf('<', tagend)); if (attr) { obj['#text'] = text; var attributes = attr.split(' '); for (var i = 0, len = attributes.length; i < len; i++) { var attribute = attributes[i]; if (!attribute) { continue; } var key_val = attribute.split('='); obj['@attributes'] = obj['@attributes'] || {}; obj['@attributes'][key_val[0].trim()] = $c.tryEval(key_val[1]) || key_val[1].trim(); } } return obj; } catch (e) { error('xmlToJson.__processAttributes', e); } } function __processChildren(nodename, children) { try { var child, i = 0, obj = {}; while (child = children[i++]) { var index = child.indexOf('>'), lindex = child.lastIndexOf('</'), attributes = __processAttributes(child), childXML = $c.strip(child.substring(index + 1, lindex),'\n').trim(); if (children.length == 1) { obj[nodename] = $c.merge(xmlToJson(childXML), attributes); } else { obj[nodename] = obj[nodename] || []; obj[nodename].push($c.merge(attributes,$c.xmlToJson(childXML))); } } return obj; } catch (e) { error('xmlToJson.__processChildren', e); } } function __processExpression (doc,expr) { try { if ($c.isString(expr)) { if (expr[0] == "$") { expr = expr.substr(1); } return $c.getProperty(doc, expr.replace("$CURRENT.", "")); } if (!$c.isObject(expr)) { return expr; } for (var field in expr) { if (!expr.hasOwnProperty(field)) { continue; } var value = expr[field], literalKeys = ["$literal"], boolKeys = ["$and", "$or", "$not"], setKeys = ["$setEquals", "$setIntersection", "$setUnion", "$setDifference", "$setIsSubset", "$anyElementTrue", "$allElementsTrue"], compareKeys = ["$cmp", "$eq", "$gt", "$gte", "$lt", "$lte", "$ne"], arithmeticKeys = ["$add", "$subtract", "$multiply", "$divide", "$mod"], stringKeys = ["$concat", "$substr", "$toLower", "$toUpper", "$strcasecmp"], arrayKeys = ["$size"], variableKeys = ["$map", "$let"], dateKeys = ["$dayOfYear", "$dayOfMonth", "$dayOfWeek", "$year", "$month", "$week", "$hour", "$minute", "$second", "$millisecond", "$dateToString"], conditionalKeys = ["$cond", "$ifNull"]; switch (true) { case literalKeys.indexOf(field) != -1: return expr; case boolKeys.indexOf(field) != -1: return __parseBooleanExpr(doc, expr, field); case setKeys.indexOf(field) != -1: return __parseSetExpr(doc, expr, field); case compareKeys.indexOf(field) != -1: return __parseComparisonExpr(doc, expr, field); case arithmeticKeys.indexOf(field) != -1: return __parseArithmeticExpr(doc, expr, field); case stringKeys.indexOf(field) != -1: return __parseStringExpr(doc, expr, field); case arrayKeys.indexOf(field) != -1: return __parseArrayExpr(doc, expr, field); case variableKeys.indexOf(field) != -1: return __parseVariableExpr(doc, expr, field); case dateKeys.indexOf(field) != -1: return __parseDateExpr(doc, expr, field); case conditionalKeys.indexOf(field) != -1: return __parseConditionalExpr(doc, expr, field); default: __processExpression (doc,value); break; } } } catch (e) { error('aggregate.__parseExpression', e); } } function __processGroup (docs, expr) { try { var _ids = expr._id, i = 0, groupings = {}, results = [], meta = {index:0,length:docs.length, sample:docs.sample/*,stop:false*/}, doc; while(doc = docs[meta.index = i++]) { var result, key = "null", keys = null; if (_ids) { keys = {}; for (var prop in _ids) { if (!_ids.hasOwnProperty(prop)) { continue; } keys[prop] = __processExpression(doc, _ids[prop]); } key = JSON.stringify(keys); } if (!groupings[key]) { result = groupings[key] = {_id:keys}; results.push(result); } else { result = groupings[key]; } for (var prop in expr) { if (!expr.hasOwnProperty(prop) || prop == "_id") { continue; } result[prop] = __processAccumulator(doc, expr[prop],result.hasOwnProperty(prop) ? result[prop] : undefined, meta); } } return results; } catch (e) { error('aggregate.__processGroup', e); } } function __processSiblings(xml) { try { var parts = xml.split('<'), obj = {}, tag = "", node = "", etag; obj['#text'] = obj['#text'] || ""; for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (!part) { continue; } if (!tag) { etag = part.indexOf('>'); if (etag == -1) { if (!i) { obj['#text'] += $c.strip(part, ['\n', ' ']); } else { node += part; } continue; } tag = part.split(/\s|>/)[0]; node += "<" + part; } else if ((etag = part.indexOf('/' + tag + '>')) != -1) { var text = $c.strip(part.substr(etag + tag.length + 2),['\n', ' ']); if (text) { obj['#text'] += text; } node += "<" + part.substring(0, etag + tag.length + 2); obj = $c.merge(obj, xmlToJson(node)); tag = "", node = ""; } } if (!obj['#text']) { delete obj['#text']; } return obj; } catch (e) { error('xmlToJson.__processSiblings', e); } } function __processStage(docs, stage) { try { var operator = "", value = {}; for (var opts in stage) { if (!stage.hasOwnProperty(opts)) { continue; } if (operator) { //noinspection ExceptionCaughtLocallyJS throw "Exception: A pipeline stage specification object must contain exactly one field."; } operator = opts; value = stage[opts]; } switch (opts) { case "$project": return $c.where(docs,{}, value); case "$match": return $c.where(docs,value); case "$redact": return _redact(docs, value); case "$limit": return docs.slice(0, value); case "$skip": return docs.slice(value); case "$unwind": return _unwind(docs, value); case "$group": return __processGroup(docs, value); case "$sort": var sorter = []; for (var prop in value) { if (!value.hasOwnProperty(prop)) { continue; } var pre = ""; if (value[prop] == -1) { pre = "!"; } sorter.push(pre+prop); } return $c.sortBy(docs,sorter); case "$out": var rtnDocs = $c.duplicate(docs,true); if ($c.isString(value)) { $g[value] = rtnDocs; } else if ($c.isArray(value)) { $c.removeAll(value); rtnDocs = $c.merge(value,rtnDocs); } return rtnDocs; case "$sample": var arr = [], i = 0, eindex = docs.length - 1; while (i < value.size) { arr.push(docs[Math.round($c.rand(0,eindex,true))]); i++; } docs.sample = arr; return docs; case "$lookup": var i = 0, doc, arr = value.from,key = value.localField, fkey = value.foreignField, prop = value.as; while(doc = docs[i++]) { var query = {}; query[fkey] = doc[key] || {$exists:false}; doc[prop] = $c.where(arr,query); } } return docs; } catch (e) { error('aggregate.__processStage', e); } } function __pullHelper(target, lookup) { for (var i = 0, len = lookup.length; i < len; i++) { var value = lookup[i]; for (var j = 0, jlen = target.length; j < jlen; j++) { if ($c.equals(value, target[j])) { $c.removeAt(target, j); j--, jlen--; } } } } function __queryNestedProperty(obj, path/*, value*/) { if (obj[path]) { return [obj[path]]; } var parts = path.split('.'), values = [], i = 0, prop; while (prop = parts[i++]) { if (!obj.hasOwnProperty(prop)) { return []; } if ($c.isArray(obj[prop])) { if ($c.isNull(parts[i])) { return obj[prop]; } var subPath = parts.slice(i).join('.'), items = obj[prop]; for (var j = 0, jlen = items.length; j < jlen; j++) { values = values.concat(__queryNestedProperty(items[j], subPath)); } return values; } obj = obj[prop]; } return [obj]; } function __relativePathFinder (path) { var callingPath = "", delimiter = "/"; // first clause is for linux based files systems, second clause is for windows based file system if (!(path.startsWith('/') || /^[a-zA-Z]:\/|^\/\/.*/.test(path))) { callingPath = new Error().stack.split('\n')[3].replace(/.*?\((.*)/,'$1'); if (callingPath.indexOf('\\') != -1) { callingPath = callingPath.replace(/\\/g,'/'); } path = callingPath.substring(0,callingPath.lastIndexOf(delimiter) + 1) + path; } return path; } function __rest_docs(req,res,params){ var routes = { all:$c.where(this.server.routes.all,{path:{$ne:"/craydent/api/docs"}},{path:1,parameters:[]}), delete:$c.where(this.server.routes.delete,{path:{$ne:"/craydent/api/docs"}},{path:1,parameters:[]}), get:$c.where(this.server.routes.get,{path:{$ne:"/craydent/api/docs"}},{path:1,parameters:[]}), post:$c.where(this.server.routes.post,{path:{$ne:"/craydent/api/docs"}},{path:1,parameters:[]}), put:$c.where(this.server.routes.put,{path:{$ne:"/craydent/api/docs"}},{path:1,parameters:[]}) }; if(req.method.toLowerCase() == "post" || params.f == 'json'){ return this.send(routes); } this.header({'Content-Type': 'text/html'},200); this.end(fillTemplate($c.REST_API_TEMPLATE,routes)); } function __run_replace (reg, template, use_run, obj) { try { var pre = "", post = "", split_param = "|", match; //noinspection CommaExpressionJS use_run && (pre="RUN[",post="]", split_param=/;(?!\\)/); while ((match = reg.exec(template)) && match[1]) { var funcValue = [], func = ""; funcValue = $c.replace_all(match[1],['\\[','\\]'],['[',']']).split(split_param); while ($c.count(funcValue[0],"{") != $c.count(funcValue[0],"}")) { if ($c.tryEval(funcValue[0])) { break; } funcValue[0]+= ($c.isString(split_param)?split_param:";")+funcValue[1]; funcValue.splice(1,1); } func = $c.strip(funcValue.splice(0,1)[0],";"); for (var i = 0, len = funcValue.length; i < len; i++) { var fv = funcValue[i]; if (fv.indexOf("${") != -1) { funcValue[i] = fillTemplate(fv, obj); } try { funcValue[i] = eval("(" + $c.replace_all(fv,[';\\'], [';']) + ")"); } catch (e) {} } funcValue = funcValue.map(function(item){ return $c.tryEval(item) || item; }); template = template.indexOf(match[1]) != -1 ? template.replace(match[1], (match[1] = $c.replace_all(match[1],['\\[', '\\]'], ['[', ']']))) : template; template = $c.replace_all(template,"${" + pre + match[1] + post +"}", $c.getProperty($g, func) ? $c.getProperty($g, func).apply(obj, funcValue) : ($c.tryEval("("+func+")")||foo).apply(obj,funcValue) || ""); } return template; } catch (e) { error('fillTemplate.__run_replace', e); } } function __universal_trim(chars) { /*|{ "info": "Array class extension to remove all white space/chars from the beginning and end of all string values in the array & String class extension to remove characters from the beginning and end of the string.", "category": "Array", "parameters":[], "overloads":[ {"parameters":[ {"ref":"(Boolean) Whether or not to mutate the original array."}]}, {"parameters":[ {"character": "(Char[]) Character to remove in the String"}]}], "url": "http://www.craydent.com/library/1.8.1/docs#String.trim", "returnType": "(Bool)" }|*/ try { if ($c.isString(this)) { return _trim(this, undefined, chars); } if ($c.isArray(this)) { var ref = chars, arr = [], alter = false; if ($c.isBoolean(ref)) { alter = true; } for (var i = 0, len = this.length; i < len; i++) { var item = this[i]; $c.isString(item) && (arr[i] = item.toString().trim()) || (arr[i] = item); alter && (this[i] = arr[i]); } return arr; } } catch (e) { error($c.getName(this.constructor) + ".trim", e); return false; } } function _ajaxServerResponse(response) { try { if (response.readyState == 4 && response.status==200) { var objResponse = {}; try { objResponse = eval(response.responseText.trim()); } catch (e) { objResponse = eval("(" + response.responseText.trim() + ")"); } if (!objResponse || objResponse.hasErrors) { return false; } return objResponse; } return false; } catch (e) { error("ajax._ajaxServerResponse", e); return false; } } function _condense (objs, check_values) { try { var skip = [], arr = [], without = false; if (check_values && check_values.constructor == Array) { without = true; } for (var i = 0, len = objs.length; i < len; i++) { var obj = objs[i]; if (check_values) { var index = i; if (without && check_values.indexOf(obj) != -1) { skip.push(i); continue; } if (skip.indexOf(i) != -1) { continue; } while ((index = objs.indexOf(obj,index+1)) != -1) { skip.push(index); } } obj !== "" && !$c.isNull(obj) && (skip.indexOf && skip.indexOf(i) || _indexOf(skip, i)) == -1 && !$c.isNull(obj) && arr.push(obj); } return arr; } catch (e) { error("_condence", e); return false; } } function _copyWithProjection(projection, record, preserveProperties) { var copy = {}, len = 0; projection = projection || "*"; if ($c.isString(projection)) { projection = projection.split(','); } if ($c.isArray(projection)) { if (!(len = projection.length)) { copy = $c.duplicate(recor