ref.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. define("dojox/json/ref", ["dojo/_base/kernel", "dojox", "dojo/date/stamp", "dojo/_base/array", "dojo/_base/json"], function(dojo, dojox){
  2. dojo.getObject("json", true, dojox);
  3. return dojox.json.ref = {
  4. // summary:
  5. // Adds advanced JSON {de}serialization capabilities to the base json library.
  6. // This enhances the capabilities of dojo.toJson and dojo.fromJson,
  7. // adding referencing support, date handling, and other extra format handling.
  8. // On parsing, references are resolved. When references are made to
  9. // ids/objects that have been loaded yet, the loader function will be set to
  10. // _loadObject to denote a lazy loading (not loaded yet) object.
  11. resolveJson: function(/*Object*/ root,/*Object?*/ args){
  12. // summary:
  13. // Indexes and resolves references in the JSON object.
  14. // description:
  15. // A JSON Schema object that can be used to advise the handling of the JSON (defining ids, date properties, urls, etc)
  16. //
  17. // root:
  18. // The root object of the object graph to be processed
  19. // args:
  20. // Object with additional arguments:
  21. //
  22. // The *index* parameter.
  23. // This is the index object (map) to use to store an index of all the objects.
  24. // If you are using inter-message referencing, you must provide the same object for each call.
  25. // The *defaultId* parameter.
  26. // This is the default id to use for the root object (if it doesn't define it's own id)
  27. // The *idPrefix* parameter.
  28. // This the prefix to use for the ids as they enter the index. This allows multiple tables
  29. // to use ids (that might otherwise collide) that enter the same global index.
  30. // idPrefix should be in the form "/Service/". For example,
  31. // if the idPrefix is "/Table/", and object is encountered {id:"4",...}, this would go in the
  32. // index as "/Table/4".
  33. // The *idAttribute* parameter.
  34. // This indicates what property is the identity property. This defaults to "id"
  35. // The *assignAbsoluteIds* parameter.
  36. // This indicates that the resolveJson should assign absolute ids (__id) as the objects are being parsed.
  37. //
  38. // The *schemas* parameter
  39. // This provides a map of schemas, from which prototypes can be retrieved
  40. // The *loader* parameter
  41. // This is a function that is called added to the reference objects that can't be resolved (lazy objects)
  42. // return:
  43. // An object, the result of the processing
  44. args = args || {};
  45. var idAttribute = args.idAttribute || 'id';
  46. var refAttribute = this.refAttribute;
  47. var idAsRef = args.idAsRef;
  48. var prefix = args.idPrefix || '';
  49. var assignAbsoluteIds = args.assignAbsoluteIds;
  50. var index = args.index || {}; // create an index if one doesn't exist
  51. var timeStamps = args.timeStamps;
  52. var ref,reWalk=[];
  53. var pathResolveRegex = /^(.*\/)?(\w+:\/\/)|[^\/\.]+\/\.\.\/|^.*\/(\/)/;
  54. var addProp = this._addProp;
  55. var F = function(){};
  56. function walk(it, stop, defaultId, needsPrefix, schema, defaultObject){
  57. // this walks the new graph, resolving references and making other changes
  58. var i, update, val, id = idAttribute in it ? it[idAttribute] : defaultId;
  59. if(idAttribute in it || ((id !== undefined) && needsPrefix)){
  60. id = (prefix + id).replace(pathResolveRegex,'$2$3');
  61. }
  62. var target = defaultObject || it;
  63. if(id !== undefined){ // if there is an id available...
  64. if(assignAbsoluteIds){
  65. it.__id = id;
  66. }
  67. if(args.schemas && (!(it instanceof Array)) && // won't try on arrays to do prototypes, plus it messes with queries
  68. (val = id.match(/^(.+\/)[^\.\[]*$/))){ // if it has a direct table id (no paths)
  69. schema = args.schemas[val[1]];
  70. }
  71. // if the id already exists in the system, we should use the existing object, and just
  72. // update it... as long as the object is compatible
  73. if(index[id] && ((it instanceof Array) == (index[id] instanceof Array))){
  74. target = index[id];
  75. delete target.$ref; // remove this artifact
  76. delete target._loadObject;
  77. update = true;
  78. }else{
  79. var proto = schema && schema.prototype; // and if has a prototype
  80. if(proto){
  81. // if the schema defines a prototype, that needs to be the prototype of the object
  82. F.prototype = proto;
  83. target = new F();
  84. }
  85. }
  86. index[id] = target; // add the prefix, set _id, and index it
  87. if(timeStamps){
  88. timeStamps[id] = args.time;
  89. }
  90. }
  91. while(schema){
  92. var properties = schema.properties;
  93. if(properties){
  94. for(i in it){
  95. var propertyDefinition = properties[i];
  96. if(propertyDefinition && propertyDefinition.format == 'date-time' && typeof it[i] == 'string'){
  97. it[i] = dojo.date.stamp.fromISOString(it[i]);
  98. }
  99. }
  100. }
  101. schema = schema["extends"];
  102. }
  103. var length = it.length;
  104. for(i in it){
  105. if(i==length){
  106. break;
  107. }
  108. if(it.hasOwnProperty(i)){
  109. val=it[i];
  110. if((typeof val =='object') && val && !(val instanceof Date) && i != '__parent'){
  111. ref=val[refAttribute] || (idAsRef && val[idAttribute]);
  112. if(!ref || !val.__parent){
  113. if(it != reWalk){
  114. val.__parent = target;
  115. }
  116. }
  117. if(ref){ // a reference was found
  118. // make sure it is a safe reference
  119. delete it[i];// remove the property so it doesn't resolve to itself in the case of id.propertyName lazy values
  120. var path = ref.toString().replace(/(#)([^\.\[])/,'$1.$2').match(/(^([^\[]*\/)?[^#\.\[]*)#?([\.\[].*)?/); // divide along the path
  121. if(index[(prefix + ref).replace(pathResolveRegex,'$2$3')]){
  122. ref = index[(prefix + ref).replace(pathResolveRegex,'$2$3')];
  123. }else if((ref = (path[1]=='$' || path[1]=='this' || path[1]=='') ? root : index[(prefix + path[1]).replace(pathResolveRegex,'$2$3')])){ // a $ indicates to start with the root, otherwise start with an id
  124. // if there is a path, we will iterate through the path references
  125. if(path[3]){
  126. path[3].replace(/(\[([^\]]+)\])|(\.?([^\.\[]+))/g,function(t,a,b,c,d){
  127. ref = ref && ref[b ? b.replace(/[\"\'\\]/,'') : d];
  128. });
  129. }
  130. }
  131. if(ref){
  132. val = ref;
  133. }else{
  134. // otherwise, no starting point was found (id not found), if stop is set, it does not exist, we have
  135. // unloaded reference, if stop is not set, it may be in a part of the graph not walked yet,
  136. // we will wait for the second loop
  137. if(!stop){
  138. var rewalking;
  139. if(!rewalking){
  140. reWalk.push(target); // we need to rewalk it to resolve references
  141. }
  142. rewalking = true; // we only want to add it once
  143. val = walk(val, false, val[refAttribute], true, propertyDefinition);
  144. // create a lazy loaded object
  145. val._loadObject = args.loader;
  146. }
  147. }
  148. }else{
  149. if(!stop){ // if we are in stop, that means we are in the second loop, and we only need to check this current one,
  150. // further walking may lead down circular loops
  151. val = walk(
  152. val,
  153. reWalk==it,
  154. id === undefined ? undefined : addProp(id, i), // the default id to use
  155. false,
  156. propertyDefinition,
  157. // if we have an existing object child, we want to
  158. // maintain it's identity, so we pass it as the default object
  159. target != it && typeof target[i] == 'object' && target[i]
  160. );
  161. }
  162. }
  163. }
  164. it[i] = val;
  165. if(target!=it && !target.__isDirty){// do updates if we are updating an existing object and it's not dirty
  166. var old = target[i];
  167. target[i] = val; // only update if it changed
  168. if(update && val !== old && // see if it is different
  169. !target._loadObject && // no updates if we are just lazy loading
  170. !(i.charAt(0) == '_' && i.charAt(1) == '_') && i != "$ref" &&
  171. !(val instanceof Date && old instanceof Date && val.getTime() == old.getTime()) && // make sure it isn't an identical date
  172. !(typeof val == 'function' && typeof old == 'function' && val.toString() == old.toString()) && // make sure it isn't an indentical function
  173. index.onUpdate){
  174. index.onUpdate(target,i,old,val); // call the listener for each update
  175. }
  176. }
  177. }
  178. }
  179. if(update && (idAttribute in it || target instanceof Array)){
  180. // this means we are updating with a full representation of the object, we need to remove deleted
  181. for(i in target){
  182. if(!target.__isDirty && target.hasOwnProperty(i) && !it.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && !(target instanceof Array && isNaN(i))){
  183. if(index.onUpdate && i != "_loadObject" && i != "_idAttr"){
  184. index.onUpdate(target,i,target[i],undefined); // call the listener for each update
  185. }
  186. delete target[i];
  187. while(target instanceof Array && target.length && target[target.length-1] === undefined){
  188. // shorten the target if necessary
  189. target.length--;
  190. }
  191. }
  192. }
  193. }else{
  194. if(index.onLoad){
  195. index.onLoad(target);
  196. }
  197. }
  198. return target;
  199. }
  200. if(root && typeof root == 'object'){
  201. root = walk(root,false,args.defaultId, true); // do the main walk through
  202. walk(reWalk,false); // re walk any parts that were not able to resolve references on the first round
  203. }
  204. return root;
  205. },
  206. fromJson: function(/*String*/ str,/*Object?*/ args){
  207. // summary:
  208. // evaluates the passed string-form of a JSON object.
  209. //
  210. // str:
  211. // a string literal of a JSON item, for instance:
  212. // '{ "foo": [ "bar", 1, { "baz": "thud" } ] }'
  213. // args: See resolveJson
  214. //
  215. // return:
  216. // An object, the result of the evaluation
  217. function ref(target){ // support call styles references as well
  218. var refObject = {};
  219. refObject[this.refAttribute] = target;
  220. return refObject;
  221. }
  222. try{
  223. var root = eval('(' + str + ')'); // do the eval
  224. }catch(e){
  225. throw new SyntaxError("Invalid JSON string: " + e.message + " parsing: "+ str);
  226. }
  227. if(root){
  228. return this.resolveJson(root, args);
  229. }
  230. return root;
  231. },
  232. toJson: function(/*Object*/ it, /*Boolean?*/ prettyPrint, /*Object?*/ idPrefix, /*Object?*/ indexSubObjects){
  233. // summary:
  234. // Create a JSON serialization of an object.
  235. // This has support for referencing, including circular references, duplicate references, and out-of-message references
  236. // id and path-based referencing is supported as well and is based on http://www.json.com/2007/10/19/json-referencing-proposal-and-library/.
  237. //
  238. // it:
  239. // an object to be serialized.
  240. //
  241. // prettyPrint:
  242. // if true, we indent objects and arrays to make the output prettier.
  243. // The variable dojo.toJsonIndentStr is used as the indent string
  244. // -- to use something other than the default (tab),
  245. // change that variable before calling dojo.toJson().
  246. //
  247. // idPrefix: The prefix that has been used for the absolute ids
  248. //
  249. // return:
  250. // a String representing the serialized version of the passed object.
  251. var useRefs = this._useRefs;
  252. var addProp = this._addProp;
  253. var refAttribute = this.refAttribute;
  254. idPrefix = idPrefix || ''; // the id prefix for this context
  255. var paths={};
  256. var generated = {};
  257. function serialize(it,path,_indentStr){
  258. if(typeof it == 'object' && it){
  259. var value;
  260. if(it instanceof Date){ // properly serialize dates
  261. return '"' + dojo.date.stamp.toISOString(it,{zulu:true}) + '"';
  262. }
  263. var id = it.__id;
  264. if(id){ // we found an identifiable object, we will just serialize a reference to it... unless it is the root
  265. if(path != '#' && ((useRefs && !id.match(/#/)) || paths[id])){
  266. var ref = id;
  267. if(id.charAt(0)!='#'){
  268. if(it.__clientId == id){
  269. ref = "cid:" + id;
  270. }else if(id.substring(0, idPrefix.length) == idPrefix){ // see if the reference is in the current context
  271. // a reference with a prefix matching the current context, the prefix should be removed
  272. ref = id.substring(idPrefix.length);
  273. }else{
  274. // a reference to a different context, assume relative url based referencing
  275. ref = id;
  276. }
  277. }
  278. var refObject = {};
  279. refObject[refAttribute] = ref;
  280. return serialize(refObject,'#');
  281. }
  282. path = id;
  283. }else{
  284. it.__id = path; // we will create path ids for other objects in case they are circular
  285. generated[path] = it;
  286. }
  287. paths[path] = it;// save it here so they can be deleted at the end
  288. _indentStr = _indentStr || "";
  289. var nextIndent = prettyPrint ? _indentStr + dojo.toJsonIndentStr : "";
  290. var newLine = prettyPrint ? "\n" : "";
  291. var sep = prettyPrint ? " " : "";
  292. if(it instanceof Array){
  293. var res = dojo.map(it, function(obj,i){
  294. var val = serialize(obj, addProp(path, i), nextIndent);
  295. if(typeof val != "string"){
  296. val = "undefined";
  297. }
  298. return newLine + nextIndent + val;
  299. });
  300. return "[" + res.join("," + sep) + newLine + _indentStr + "]";
  301. }
  302. var output = [];
  303. for(var i in it){
  304. if(it.hasOwnProperty(i)){
  305. var keyStr;
  306. if(typeof i == "number"){
  307. keyStr = '"' + i + '"';
  308. }else if(typeof i == "string" && (i.charAt(0) != '_' || i.charAt(1) != '_')){
  309. // we don't serialize our internal properties __id and __clientId
  310. keyStr = dojo._escapeString(i);
  311. }else{
  312. // skip non-string or number keys
  313. continue;
  314. }
  315. var val = serialize(it[i],addProp(path, i),nextIndent);
  316. if(typeof val != "string"){
  317. // skip non-serializable values
  318. continue;
  319. }
  320. output.push(newLine + nextIndent + keyStr + ":" + sep + val);
  321. }
  322. }
  323. return "{" + output.join("," + sep) + newLine + _indentStr + "}";
  324. }else if(typeof it == "function" && dojox.json.ref.serializeFunctions){
  325. return it.toString();
  326. }
  327. return dojo.toJson(it); // use the default serializer for primitives
  328. }
  329. var json = serialize(it,'#','');
  330. if(!indexSubObjects){
  331. for(var i in generated) {// cleanup the temporary path-generated ids
  332. delete generated[i].__id;
  333. }
  334. }
  335. return json;
  336. },
  337. _addProp: function(id, prop){
  338. return id + (id.match(/#/) ? id.length == 1 ? '' : '.' : '#') + prop;
  339. },
  340. // refAttribute: String
  341. // This indicates what property is the reference property. This acts like the idAttribute
  342. // except that this is used to indicate the current object is a reference or only partially
  343. // loaded. This defaults to "$ref".
  344. refAttribute: "$ref",
  345. _useRefs: false,
  346. serializeFunctions: false
  347. };
  348. });