UNPKG

shelf.js

Version:

A modular, powerful wrapper library for persistent objects in the browser and Node.js

156 lines (119 loc) 19.7 kB
/* http://www.JSON.org/json2.js 2011-02-23 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. *//*jslint evil: true, strict: false, regexp: false *//*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */// Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON;JSON||(JSON={}),function(){"use strict";function f(e){return e<10?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return typeof t=="string"?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,i,s,o=gap,u,a=t[e];a&&typeof a=="object"&&typeof a.toJSON=="function"&&(a=a.toJSON(e)),typeof rep=="function"&&(a=rep.call(t,e,a));switch(typeof a){case"string":return quote(a);case"number":return isFinite(a)?String(a):"null";case"boolean":case"null":return String(a);case"object":if(!a)return"null";gap+=indent,u=[];if(Object.prototype.toString.apply(a)==="[object Array]"){s=a.length;for(n=0;n<s;n+=1)u[n]=str(n,a)||"null";return i=u.length===0?"[]":gap?"[\n"+gap+u.join(",\n"+gap)+"\n"+o+"]":"["+u.join(",")+"]",gap=o,i}if(rep&&typeof rep=="object"){s=rep.length;for(n=0;n<s;n+=1)typeof rep[n]=="string"&&(r=rep[n],i=str(r,a),i&&u.push(quote(r)+(gap?": ":":")+i))}else for(r in a)Object.prototype.hasOwnProperty.call(a,r)&&(i=str(r,a),i&&u.push(quote(r)+(gap?": ":":")+i));return i=u.length===0?"{}":gap?"{\n"+gap+u.join(",\n"+gap)+"\n"+o+"}":"{"+u.join(",")+"}",gap=o,i}}var global=Function("return this")(),JSON=global.JSON;JSON||(JSON={}),typeof Date.prototype.toJSON!="function"&&(Date.prototype.toJSON=function(e){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(e){return this.valueOf()});var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;typeof JSON.stringify!="function"&&(JSON.stringify=function(e,t,n){var r;gap="",indent="";if(typeof n=="number")for(r=0;r<n;r+=1)indent+=" ";else typeof n=="string"&&(indent=n);rep=t;if(!t||typeof t=="function"||typeof t=="object"&&typeof t.length=="number")return str("",{"":e});throw new Error("JSON.stringify")}),typeof JSON.parse!="function"&&(JSON.parse=function(text,reviver){function walk(e,t){var n,r,i=e[t];if(i&&typeof i=="object")for(n in i)Object.prototype.hasOwnProperty.call(i,n)&&(r=walk(i,n),r!==undefined?i[n]=r:delete i[n]);return reviver.call(e,t,i)}var j;text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)}));if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),typeof reviver=="function"?walk({"":j},""):j;throw new SyntaxError("JSON.parse")}),global.JSON=JSON,JSUS.isNodeJS()&&(module.exports=JSON)}(),typeof JSON.decycle!="function"&&(JSON.decycle=function(t){"use strict";var n=[],r=[];return function i(e,t){var s,o,u;switch(typeof e){case"object":if(!e)return null;for(s=0;s<n.length;s+=1)if(n[s]===e)return{$ref:r[s]};n.push(e),r.push(t);if(Object.prototype.toString.apply(e)==="[object Array]"){u=[];for(s=0;s<e.length;s+=1)u[s]=i(e[s],t+"["+s+"]")}else{u={};for(o in e)Object.prototype.hasOwnProperty.call(e,o)&&(u[o]=i(e[o],t+"["+JSON.stringify(o)+"]"))}return u;case"number":case"string":case"boolean":return e}}(t,"$")}),typeof JSON.retrocycle!="function"&&(JSON.retrocycle=function retrocycle($){"use strict";var px=/^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;return function rez(value){var i,item,name,path;if(value&&typeof value=="object")if(Object.prototype.toString.apply(value)==="[object Array]")for(i=0;i<value.length;i+=1)item=value[i],item&&typeof item=="object"&&(path=item.$ref,typeof path=="string"&&px.test(path)?value[i]=eval(path):rez(item));else for(name in value)typeof value[name]=="object"&&(item=value[name],item&&(path=item.$ref,typeof path=="string"&&px.test(path)?value[name]=eval(path):rez(item)))}($),$}),function(e){var t="5.1",n,r;r="volatile",n=e.store=function(e,t,r,i){r=r||{},i=r.type&&r.type in n.types?r.type:n.type;if(!i||!n.types[i]){n.log("Cannot save/load value. Invalid storage type selected: "+i,"ERR");return}return n.log("Accessing "+i+" storage"),n.types[i](e,t,r)},n.prefix="__shelf__",n.verbosity=0,n.types={};try{Object.defineProperty(n,"type",{set:function(e){return"undefined"==typeof n.types[e]?(n.log("Cannot set store.type to an invalid type: "+e),!1):(r=e,e)},get:function(){return r},configurable:!1,enumerable:!0})}catch(i){n.type=r}n.addType=function(e,t){n.types[e]=t,n[e]=function(t,r,i){return i=i||{},i.type=e,n(t,r,i)};if(!n.type||n.type==="volatile")n.type=e},n.onquotaerror=undefined,n.error=function(){console.log("shelf quota exceeded"),"function"==typeof n.onquotaerror&&n.onquotaerror(null)},n.log=function(e){n.verbosity>0&&console.log("Shelf v."+t+": "+e)},n.isPersistent=function(){return n.types?n.type==="volatile"?!1:!0:!1};try{Object.defineProperty(n,"persistent",{set:function(){},get:n.isPersistent,configurable:!1})}catch(i){n.persistent=!1}n.decycle=function(e){return JSON&&JSON.decycle&&"function"==typeof JSON.decycle&&(e=JSON.decycle(e)),e},n.retrocycle=function(e){return JSON&&JSON.retrocycle&&"function"==typeof JSON.retrocycle&&(e=JSON.retrocycle(e)),e},n.stringify=function(e){if(!JSON||!JSON.stringify||"function"!=typeof JSON.stringify)throw new Error("JSON.stringify not found. Received non-stringvalue and could not serialize.");return e=n.decycle(e),JSON.stringify(e)},n.parse=function(e){if("undefined"==typeof e)return undefined;if(JSON&&JSON.parse&&"function"==typeof JSON.parse)try{e=JSON.parse(e)}catch(t){n.log("Error while parsing a value: "+t,"ERR"),n.log(e)}return e=n.retrocycle(e),e},function(){function r(e){return n.parse(n.stringify(e))}var e={},t={};n.addType("volatile",function(n,i,s){return n?i===undefined?r(e[n]):(t[n]&&(clearTimeout(t[n]),delete t[n]),i===null?(delete e[n],null):(e[n]=i,s.expires&&(t[n]=setTimeout(function(){delete e[n],delete t[n]},s.expires)),i)):r(e)})}()}("undefined"!=typeof module&&"undefined"!=typeof module.exports?module.exports:this),function(e){function r(e,r){t.addType(e,function(i,s,o){var u,a,f,l,c=s,h=(new Date).getTime();if(!i){c={},l=[],f=0;try{i=r.length;while(i=r.key(f++))n.test(i)&&(a=t.parse(r.getItem(i)),a.expires&&a.expires<=h?l.push(i):c[i.replace(rprefix,"")]=a.data);while(i=l.pop())r.removeItem(i)}catch(p){}return c}i=t.prefix+i;if(s===undefined){u=r.getItem(i),a=u?t.parse(u):{expires:-1};if(!(a.expires&&a.expires<=h))return a.data;r.removeItem(i)}else if(s===null)r.removeItem(i);else{a=t.stringify({data:s,expires:o.expires?h+o.expires:null});try{r.setItem(i,a)}catch(p){t[e]();try{r.setItem(i,a)}catch(p){throw t.error()}}}return c})}var t=e.store;if(!t)throw new Error("amplify.shelf.js: shelf.js core not found.");if("undefined"==typeof window)throw new Error("amplify.shelf.js: window object not found.");var n=new RegExp("^"+t.prefix);for(var i in{localStorage:1,sessionStorage:1})try{window[i].setItem(t.prefix,"x"),window[i].removeItem(t.prefix),r(i,window[i])}catch(s){}if(!t.types.localStorage&&window.globalStorage)try{r("globalStorage",window.globalStorage[window.location.hostname]),t.type==="sessionStorage"&&(t.type="globalStorage")}catch(s){}(function(){if(t.types.localStorage)return;var e=document.createElement("div"),n=t.prefix;e.style.display="none",document.getElementsByTagName("head")[0].appendChild(e);try{e.addBehavior("#default#userdata"),e.load(n)}catch(r){e.parentNode.removeChild(e);return}t.addType("userData",function(r,i,s){e.load(n);var o,u,a,f,l,c=i,h=(new Date).getTime();if(!r){c={},l=[],f=0;while(o=e.XMLDocument.documentElement.attributes[f++])u=t.parse(o.value),u.expires&&u.expires<=h?l.push(o.name):c[o.name]=u.data;while(r=l.pop())e.removeAttribute(r);return e.save(n),c}r=r.replace(/[^\-._0-9A-Za-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c-\u200d\u203f\u2040\u2070-\u218f]/g,"-"),r=r.replace(/^-/,"_-");if(i===undefined){o=e.getAttribute(r),u=o?t.parse(o):{expires:-1};if(!(u.expires&&u.expires<=h))return u.data;e.removeAttribute(r)}else i===null?e.removeAttribute(r):(a=e.getAttribute(r),u=t.stringify({data:i,expires:s.expires?h+s.expires:null}),e.setAttribute(r,u));try{e.save(n)}catch(p){a===null?e.removeAttribute(r):e.setAttribute(r,a),t.userData();try{e.setAttribute(r,u),e.save(n)}catch(p){throw a===null?e.removeAttribute(r):e.setAttribute(r,a),t.error()}}return c})})()}(this),function(e){var t=e.store;if(!t)throw new Error("cookie.shelf.js: shelf.js core not found.");if("undefined"==typeof window)throw new Error("cookie.shelf.js: window object not found.");var n=function(){var e,n,r,i,s={expiresAt:null,path:"/",domain:null,secure:!1};return e=function(e){var t,n;return typeof e!="object"||e===null?t=s:(t={expiresAt:s.expiresAt,path:s.path,domain:s.domain,secure:s.secure},typeof e.expiresAt=="object"&&e.expiresAt instanceof Date?t.expiresAt=e.expiresAt:typeof e.hoursToLive=="number"&&e.hoursToLive!==0&&(n=new Date,n.setTime(n.getTime()+e.hoursToLive*60*60*1e3),t.expiresAt=n),typeof e.path=="string"&&e.path!==""&&(t.path=e.path),typeof e.domain=="string"&&e.domain!==""&&(t.domain=e.domain),e.secure===!0&&(t.secure=e.secure)),t},n=function(t){return t=e(t),(typeof t.expiresAt=="object"&&t.expiresAt instanceof Date?"; expires="+t.expiresAt.toGMTString():"")+"; path="+t.path+(typeof t.domain=="string"?"; domain="+t.domain:"")+(t.secure===!0?"; secure":"")},r=function(){var e={},n,r,i,s,o=document.cookie.split(";"),u;for(n=0;n<o.length;n+=1){r=o[n].split("="),i=r[0].replace(/^\s*/,"").replace(/\s*$/,"");try{s=decodeURIComponent(r[1])}catch(a){s=r[1]}e[i]=t.parse(s)}return e},i=function(){},i.prototype.get=function(e){var t,n,i=r();if(typeof e=="string")t=typeof i[e]!="undefined"?i[e]:null;else if(typeof e=="object"&&e!==null){t={};for(n in e)typeof i[e[n]]!="undefined"?t[e[n]]=i[e[n]]:t[e[n]]=null}else t=i;return t},i.prototype.filter=function(e){var t,n={},i=r();typeof e=="string"&&(e=new RegExp(e));for(t in i)t.match(e)&&(n[t]=i[t]);return n},i.prototype.set=function(e,r,i){if(typeof i!="object"||i===null)i={};typeof r=="undefined"||r===null?(r="",i.hoursToLive=-8760):typeof r!="string"&&(r=t.stringify(r));var s=n(i);document.cookie=e+"="+encodeURIComponent(r)+s},i.prototype.del=function(e,t){var n={},r;if(typeof t!="object"||t===null)t={};typeof e=="boolean"&&e===!0?n=this.get():typeof e=="string"&&(n[e]=!0);for(r in n)typeof r=="string"&&r!==""&&this.set(r,null,t)},i.prototype.test=function(){var e=!1,t="cT",n="data";return this.set(t,n),this.get(t)===n&&(this.del(t),e=!0),e},i.prototype.setOptions=function(t){typeof t!="object"&&(t=null),s=e(t)},new i}();n.test()&&t.addType("cookie",function(e,t,r){return"undefined"==typeof e?n.get():"undefined"==typeof t?n.get(e):t===null?(n.del(e),null):n.set(e,t,r)})}(this),function(e){function i(){if(u())return!1;for(var e=0;e<r.length;e++)r[e].call(r[e])}function s(){n=!0}function o(){n=!1}function u(){return n}function a(e){r.push(e)}var t=e.store;if(!t)throw new Error("fs.shelf.js: shelf.js core not found.");var n=!1,r=[],f=0;t.filename="./shelf.out";var l=require("fs"),c=require("path"),h=require("util"),p=65536,d=new Buffer(p),v=function(e,t){var n,r,i,s;r=l.openSync(e,"r"),i=l.openSync(t,"w"),n=1,s=0;while(n>0)n=l.readSync(r,d,0,p,s),l.writeSync(i,d,0,n),s+=n;return l.closeSync(r),l.closeSync(i)},m={},g=function(e,n){if(u())return a(this),!1;s();var r=e||t.filename;if(!r)return t.log("You must specify a valid file.","ERR"),!1;var f=c.dirname(r)+"/."+c.basename(r);v(r,f);var h=t.stringify(n);return h=h.substr(1,h=h.substr(0,h.legth-1)),l.writeFileSync(r,h,"utf-8"),l.unlinkSync(f),o(),i(),!0};if("undefined"!=typeof l.appendFileSync)var y=function(e,n,r){var i=e||t.filename;if(!i)return t.log("You must specify a valid file.","ERR"),!1;if(!n)return;var s=t.stringify(n)+": "+t.stringify(r)+",\n";return l.appendFileSync(i,s,"utf-8")};else var y=function(e,n,r){var i=e||t.filename;if(!i)return t.log("You must specify a valid file.","ERR"),!1;if(!n)return;var s=t.stringify(n)+": "+t.stringify(r)+",\n",o=l.openSync(i,"a","0666");return l.writeSync(o,s,null,"utf8"),l.closeSync(o),!0};var b=function(e,n){var r=e||t.filename;if(!r)return t.log("You must specify a valid file.","ERR"),!1;var i=l.readFileSync(r,"utf-8");i=i.substr(0,i.length-2);var s=t.parse("{"+i+"}");return n?s[n]:s},w=function(e,n){var r=e||t.filename,i=b(r);return delete i[n],g(r,i),null};t.addType("fs",function(e,n,r){var i=r.file||t.filename;return e?n===undefined?b(i,e):(m[e]&&(clearTimeout(m[e]),w(i,e)),n===null?(w(i,e),null):(y(i,e,n),r.expires&&(m[e]=setTimeout(function(){w(i,e)},r.expires)),n)):b(i)})}("undefined"!=typeof module&&"function"==typeof require?module.exports||module.parent.exports:{})