execjs-xtrn 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 6ea23f93401560e87c30a5e58f9b859021af74fe
4
+ data.tar.gz: ff537afc206da297fc767c8364605c64b4bb3822
5
+ SHA512:
6
+ metadata.gz: 305a66d5d0f545b7e328715436436a2b32ed3a21a5363d5d67d1835b147f105e84005dda3a63e5f3a275a88c4bef07483c87ef91f3abb29aa8f0edde7ce8bb09
7
+ data.tar.gz: 6dd4f27cd97237f42e8fd6d2a98ba2ee6a700e8105be90066cc0cd7ca46eeadc79e2f8ae358599086d948a331f82407e9efcf4d8590d3728a0b23d383969492e
data/.gitignore ADDED
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ node_modules
data/.travis.yml ADDED
@@ -0,0 +1,12 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.1.1
4
+ - 2.0.0
5
+ - 1.9.3
6
+ - 1.9.2
7
+ before_install:
8
+ - sudo apt-get update -qq
9
+ - sudo apt-get install -y npm
10
+ install:
11
+ - bundle install
12
+ - bundle exec rake npm
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in execjs-xtrn.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2014 Stas Ukolov
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,171 @@
1
+ # ExecJS::Xtrn
2
+
3
+ [![Build Status](https://travis-ci.org/ukoloff/execjs-xtrn.svg?branch=master)](https://travis-ci.org/ukoloff/execjs-xtrn)
4
+ [![Gem Version](https://badge.fury.io/rb/execjs-xtrn.svg)](http://badge.fury.io/rb/execjs-xtrn)
5
+
6
+ Drop-in replacement for ExecJS. The latter spawns separate process for every JavaScript compilation
7
+ (when using external runtime),
8
+ while ExecJS::Xtrn spawn long running JavaScript process and communicates with it via stdin & stderr.
9
+
10
+ This is just proof of concept, not suitable for production.
11
+
12
+ When not on MS Windows, one definitely should use ExecJS with excellent `therubyracer` gem instead.
13
+
14
+ ## Installation
15
+
16
+ Add this line to your application's Gemfile:
17
+
18
+ gem 'execjs-xtrn'
19
+
20
+ And then execute:
21
+
22
+ $ bundle
23
+
24
+ Or install it yourself as:
25
+
26
+ $ gem install execjs-xtrn
27
+
28
+ ## Usage
29
+
30
+ Just add/require this gem after/instead (implicit) `execjs` gem.
31
+ The latter will be monkey-patched.
32
+
33
+ ## Engines
34
+
35
+ ExecJS::Xtrn uses two external JavaScript runners:
36
+
37
+ * Windows Script Host
38
+ * Node.js in two modes:
39
+ - Simple (1 execution context = 1 external process)
40
+ - Nvm (all execution contexts share single external process using [vm API](http://nodejs.org/api/vm.html))
41
+
42
+ So, there exist *four* engines:
43
+
44
+ * Engine - absctract engine (smart enough to execute blank lines)
45
+ * Wsh - engine using WSH (CScript)
46
+ * Node - engine using Node.js (separate process for every execution context)
47
+ * Nvm - engine using Node.js and vm API (single process)
48
+
49
+ All engines autodetect their availability at startup (on `require 'execjs/xtrn'`) and sets `Valid` constants.
50
+ Eg on MS Windows ExecJS::Xtrn::Wsh::Valid = true, on Linux - false
51
+
52
+ One of available engines is made default engine for ExecJS.
53
+ If Node.js is available it is Nvm.
54
+ Else, if running on Windows it is Wsh.
55
+ Else it is Engine, so ExecJS is made unusable.
56
+
57
+ Default engine can be shown/changed at any moment with `ExecJS::Xtrn.engine` accessor, eg
58
+
59
+ ```ruby
60
+ ExecJS::Xtrn.engine=ExecJS::Xtrn::Node
61
+ ```
62
+
63
+ ## API
64
+
65
+ ExecJS::Xtrn is primarily designed to power other gems that use popular ExecJS.
66
+
67
+ But it has his own API (similar to ExecJS' API) and can be used itself.
68
+
69
+ In general one should create instance of an Engine and then feed it with JavaScript code:
70
+
71
+ ```ruby
72
+ ctx=ExecJS::Xtrn::Wsh.new
73
+ ctx.exec 'fact = function(n){return n>1 ? n*fact(n-1) : 1}'
74
+ puts "10!=#{ctx.call 'fact', 10}"
75
+ ```
76
+ Every execution context has three methods:
77
+ * exec('`code`') - executes arbitrary JavaScript code. To get result `return` must be called.
78
+ * eval('`expression`') - evaluate JavaScript expression. `return` is not needed
79
+ * call(`function`, arguments...) - special form of eval for function call
80
+
81
+ Engine class also has exec and eval methods, they just create brand new execution context,
82
+ pass argument to it, destroy that context and return its result. Using these class methods
83
+ is not recommended, since it's just what ExecJS does (except for Nvm engine).
84
+
85
+ Engine class also has compile method that combines `new` and `exec` and returns execution context.
86
+ This is how ExecJS is used in most cases.
87
+
88
+ ```ruby
89
+ ctx=ExecJS::Xtrn::Wsh.compile 'fact = function(n){return n>1 ? n*fact(n-1) : 1}'
90
+ puts "10!=#{ctx.call 'fact', 10}"
91
+ ```
92
+
93
+ And finally ExecJS::Xtrn patches ExecJS and installs those 3 class methods (exec, eval, compile) in it.
94
+ So, `ExecJS.compile` is `ExecJS::Xtrn::Nvm.compile` if Nvm engine is available.
95
+
96
+ ## Overriding ExecJS
97
+
98
+ Sometimes ExecJS is required after ExecJS::Xtrn. In that case you can call ExecJS::Xtrn.init and
99
+ it will overwrite ExecJS' methods again.
100
+
101
+ To test whether JavaScript is served by ExecJS::Xtrn, it's convenient to look at ExecJS::Xtrn statistics.
102
+
103
+ ## Statistics
104
+
105
+ Every engine gathers it's own usage statistics. Eg:
106
+
107
+ ```ruby
108
+ > ExecJS::Xtrn::Node.stats # or ExecJS::Xtrn::Nvm.stats or ExecJS::Xtrn::Wsh.stats
109
+ => {:c=>2, :n=>2, :o=>8, :i=>6, :t=>0.131013}
110
+ ```
111
+ Here:
112
+ * c = number of child processes spawned (for Nvm c should always be 1)
113
+ * n = number of request made
114
+ * o = bytes sent to child process(es)
115
+ * i = bytes got from child process(es)
116
+ * t = seconds spent communicating with child process(es)
117
+ * m = number of VMs created (Nvm only)
118
+ * x = number of VMs destroyed (Nvm only)
119
+
120
+ ExecJS::Xtrn.stats combines statistics for all its engines, even unused.
121
+
122
+ ExecJS.stats shows statistics for current engine only.
123
+
124
+ Every execution context has his own statistics too. Eg
125
+
126
+ ```ruby
127
+ s=ExecJS::Xtrn::Nvm.compile '...'
128
+ s.exec '...'
129
+ s.stats
130
+ ```
131
+ but c (and m, x) fields are omitted there.
132
+
133
+ ## Compatibilty
134
+
135
+ Not every JavaScript code behaves identically in ExecJS and ExecJS::Xtrn. In most cases it depends on how
136
+ global JavaScript variables are used. For most modern code it is the same though.
137
+
138
+ As a rule of thumb, JavaScript code must survive after wrapping in anonymous function (`(function(){...})()`).
139
+
140
+ For instance, old versions of `handlebars_assets` didn't work
141
+ in ExecJS::Xtrn (and worked in ExecJS).
142
+
143
+ The following packages have been tested to run under ExecJS::Xtrn out-of-box:
144
+
145
+ * [CoffeeScript](http://coffeescript.org/) via [coffee-script](https://rubygems.org/gems/coffee-script) and [coffee-rails](https://rubygems.org/gems/coffee-rails) gems
146
+ * [UglifyJS2](https://github.com/mishoo/UglifyJS2) via [uglifier](https://github.com/lautis/uglifier)
147
+ * [Handlebars](http://handlebarsjs.com/) via [handlebars_assets](https://github.com/leshill/handlebars_assets) gem
148
+
149
+ ## Testing
150
+
151
+ After git checkout, required NPM modules must be installed. Simply run:
152
+
153
+ ```
154
+ bundle install
155
+ bundle exec rake npm
156
+ ```
157
+
158
+ The testing itself is
159
+
160
+ ```
161
+ bundle exec rake
162
+ ```
163
+
164
+ And `bundle exec` may be ommited in most cases.
165
+
166
+ ## Credits
167
+
168
+ * [ExecJS](https://github.com/sstephenson/execjs)
169
+ * [therubyracer](https://github.com/cowboyd/therubyracer)
170
+ * [Node.js](http://nodejs.org/)
171
+ * [Windows Script Host](http://en.wikipedia.org/wiki/Windows_Script_Host)
data/Rakefile ADDED
@@ -0,0 +1,17 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ desc 'Install NPM modules'
4
+ task :npm do
5
+ system "npm", "install", chdir: "lib/execjs/node"
6
+ end
7
+
8
+ desc 'Run tests'
9
+ task :test do
10
+ require "minitest/autorun"
11
+
12
+ require 'execjs/xtrn'
13
+
14
+ Dir.glob('./test/*.rb'){|f| require f}
15
+ end
16
+
17
+ task default: :test
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'execjs/xtrn/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "execjs-xtrn"
8
+ spec.version = ExecJS::Xtrn::VERSION
9
+ spec.authors = ["Stas Ukolov"]
10
+ spec.email = ["ukoloff@gmail.com"]
11
+ spec.description = "Drop-in replacement for ExecJS with persistent external runtime"
12
+ spec.summary = "Proof-of-concept: make ExecJS fast even without therubyracer"
13
+ spec.homepage = "https://github.com/ukoloff/execjs-xtrn"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files`.split($/)+
17
+ Dir.glob('**/node_modules/*/*.js')
18
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
19
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_development_dependency "bundler", "~> 1.3"
23
+ spec.add_development_dependency "rake"
24
+ spec.add_development_dependency "minitest"
25
+ spec.add_development_dependency "coffee-script"
26
+ spec.add_development_dependency "uglifier"
27
+ end
@@ -0,0 +1,71 @@
1
+ var
2
+ s=require('split'),
3
+ vm = require('vm'),
4
+ vms = {}
5
+
6
+ process.stdin
7
+ .pipe(s(cmd))
8
+ .pipe(process.stderr)
9
+
10
+ function cmd(s)
11
+ {
12
+ return wrap(s)+'\n'
13
+ }
14
+
15
+ function wrap(s)
16
+ {
17
+ try { s=compile(s) }
18
+ catch(e) { s={err: e.message || 'General error'} }
19
+
20
+ try { return JSON.stringify(s) }
21
+ catch(e) { return '{"err":"JSON.stringify error"}' }
22
+ }
23
+
24
+ function compile(s)
25
+ {
26
+ s = JSON.parse(s)
27
+ if('object'==typeof s)
28
+ return vmCmd(s)
29
+ if('string'!=typeof s)
30
+ throw Error('String expected!')
31
+ return ok(new Function(s)())
32
+ }
33
+
34
+ function ok(v)
35
+ {
36
+ return 'undefined'==typeof v ? {} : {ok: v}
37
+ }
38
+
39
+ function vmCmd(s)
40
+ {
41
+ if(!('vm' in s))
42
+ throw Error('VM command expected!')
43
+ if('js' in s)
44
+ return vmEval(s)
45
+ if(!s.vm)
46
+ return {vm: vmNew()}
47
+ delete vms[s.vm]
48
+ return {}
49
+ }
50
+
51
+ function vmEval(s)
52
+ {
53
+ var z = vms[s.vm]
54
+ if(!z)
55
+ throw Error('VM not found')
56
+ if('string'!=typeof s.js)
57
+ throw Error('String expected!')
58
+ return ok(vm.runInContext('new Function('+JSON.stringify(s.js)+')()', z))
59
+ }
60
+
61
+ function vmNew()
62
+ {
63
+ var i, r
64
+ for(i = 10; i>0; i--)
65
+ if((r = /\d{3,}/.exec(Math.random())) && !vms[r = r[0]])
66
+ {
67
+ vms[r] = vm.createContext()
68
+ return r
69
+ }
70
+ throw Error('Cannot generate random number')
71
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "dependencies": {
3
+ "split": "^0.3.0",
4
+ "through": "^2.3.6"
5
+ }
6
+ }
@@ -0,0 +1,481 @@
1
+ /*
2
+ http://www.JSON.org/json2.js
3
+ 2011-01-18
4
+
5
+ Public Domain.
6
+
7
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
8
+
9
+ See http://www.JSON.org/js.html
10
+
11
+
12
+ This code should be minified before deployment.
13
+ See http://javascript.crockford.com/jsmin.html
14
+
15
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
16
+ NOT CONTROL.
17
+
18
+
19
+ This file creates a global JSON object containing two methods: stringify
20
+ and parse.
21
+
22
+ JSON.stringify(value, replacer, space)
23
+ value any JavaScript value, usually an object or array.
24
+
25
+ replacer an optional parameter that determines how object
26
+ values are stringified for objects. It can be a
27
+ function or an array of strings.
28
+
29
+ space an optional parameter that specifies the indentation
30
+ of nested structures. If it is omitted, the text will
31
+ be packed without extra whitespace. If it is a number,
32
+ it will specify the number of spaces to indent at each
33
+ level. If it is a string (such as '\t' or ' '),
34
+ it contains the characters used to indent at each level.
35
+
36
+ This method produces a JSON text from a JavaScript value.
37
+
38
+ When an object value is found, if the object contains a toJSON
39
+ method, its toJSON method will be called and the result will be
40
+ stringified. A toJSON method does not serialize: it returns the
41
+ value represented by the name/value pair that should be serialized,
42
+ or undefined if nothing should be serialized. The toJSON method
43
+ will be passed the key associated with the value, and this will be
44
+ bound to the value
45
+
46
+ For example, this would serialize Dates as ISO strings.
47
+
48
+ Date.prototype.toJSON = function (key) {
49
+ function f(n) {
50
+ // Format integers to have at least two digits.
51
+ return n < 10 ? '0' + n : n;
52
+ }
53
+
54
+ return this.getUTCFullYear() + '-' +
55
+ f(this.getUTCMonth() + 1) + '-' +
56
+ f(this.getUTCDate()) + 'T' +
57
+ f(this.getUTCHours()) + ':' +
58
+ f(this.getUTCMinutes()) + ':' +
59
+ f(this.getUTCSeconds()) + 'Z';
60
+ };
61
+
62
+ You can provide an optional replacer method. It will be passed the
63
+ key and value of each member, with this bound to the containing
64
+ object. The value that is returned from your method will be
65
+ serialized. If your method returns undefined, then the member will
66
+ be excluded from the serialization.
67
+
68
+ If the replacer parameter is an array of strings, then it will be
69
+ used to select the members to be serialized. It filters the results
70
+ such that only members with keys listed in the replacer array are
71
+ stringified.
72
+
73
+ Values that do not have JSON representations, such as undefined or
74
+ functions, will not be serialized. Such values in objects will be
75
+ dropped; in arrays they will be replaced with null. You can use
76
+ a replacer function to replace those with JSON values.
77
+ JSON.stringify(undefined) returns undefined.
78
+
79
+ The optional space parameter produces a stringification of the
80
+ value that is filled with line breaks and indentation to make it
81
+ easier to read.
82
+
83
+ If the space parameter is a non-empty string, then that string will
84
+ be used for indentation. If the space parameter is a number, then
85
+ the indentation will be that many spaces.
86
+
87
+ Example:
88
+
89
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
90
+ // text is '["e",{"pluribus":"unum"}]'
91
+
92
+
93
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
94
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
95
+
96
+ text = JSON.stringify([new Date()], function (key, value) {
97
+ return this[key] instanceof Date ?
98
+ 'Date(' + this[key] + ')' : value;
99
+ });
100
+ // text is '["Date(---current time---)"]'
101
+
102
+
103
+ JSON.parse(text, reviver)
104
+ This method parses a JSON text to produce an object or array.
105
+ It can throw a SyntaxError exception.
106
+
107
+ The optional reviver parameter is a function that can filter and
108
+ transform the results. It receives each of the keys and values,
109
+ and its return value is used instead of the original value.
110
+ If it returns what it received, then the structure is not modified.
111
+ If it returns undefined then the member is deleted.
112
+
113
+ Example:
114
+
115
+ // Parse the text. Values that look like ISO date strings will
116
+ // be converted to Date objects.
117
+
118
+ myData = JSON.parse(text, function (key, value) {
119
+ var a;
120
+ if (typeof value === 'string') {
121
+ a =
122
+ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
123
+ if (a) {
124
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
125
+ +a[5], +a[6]));
126
+ }
127
+ }
128
+ return value;
129
+ });
130
+
131
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
132
+ var d;
133
+ if (typeof value === 'string' &&
134
+ value.slice(0, 5) === 'Date(' &&
135
+ value.slice(-1) === ')') {
136
+ d = new Date(value.slice(5, -1));
137
+ if (d) {
138
+ return d;
139
+ }
140
+ }
141
+ return value;
142
+ });
143
+
144
+
145
+ This is a reference implementation. You are free to copy, modify, or
146
+ redistribute.
147
+ */
148
+
149
+ /*jslint evil: true, strict: false, regexp: false */
150
+
151
+ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
152
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
153
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
154
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
155
+ test, toJSON, toString, valueOf
156
+ */
157
+
158
+
159
+ // Create a JSON object only if one does not already exist. We create the
160
+ // methods in a closure to avoid creating global variables.
161
+
162
+ (function (global) {
163
+ if (!global.JSON) {
164
+ global.JSON = {};
165
+ }
166
+
167
+ var JSON = global.JSON;
168
+
169
+ "use strict";
170
+
171
+ function f(n) {
172
+ // Format integers to have at least two digits.
173
+ return n < 10 ? '0' + n : n;
174
+ }
175
+
176
+ if (typeof Date.prototype.toJSON !== 'function') {
177
+
178
+ Date.prototype.toJSON = function (key) {
179
+
180
+ return isFinite(this.valueOf()) ?
181
+ this.getUTCFullYear() + '-' +
182
+ f(this.getUTCMonth() + 1) + '-' +
183
+ f(this.getUTCDate()) + 'T' +
184
+ f(this.getUTCHours()) + ':' +
185
+ f(this.getUTCMinutes()) + ':' +
186
+ f(this.getUTCSeconds()) + 'Z' : null;
187
+ };
188
+
189
+ String.prototype.toJSON =
190
+ Number.prototype.toJSON =
191
+ Boolean.prototype.toJSON = function (key) {
192
+ return this.valueOf();
193
+ };
194
+ }
195
+
196
+ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
197
+ escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
198
+ gap,
199
+ indent,
200
+ meta = { // table of character substitutions
201
+ '\b': '\\b',
202
+ '\t': '\\t',
203
+ '\n': '\\n',
204
+ '\f': '\\f',
205
+ '\r': '\\r',
206
+ '"' : '\\"',
207
+ '\\': '\\\\'
208
+ },
209
+ rep;
210
+
211
+
212
+ function quote(string) {
213
+
214
+ // If the string contains no control characters, no quote characters, and no
215
+ // backslash characters, then we can safely slap some quotes around it.
216
+ // Otherwise we must also replace the offending characters with safe escape
217
+ // sequences.
218
+
219
+ escapable.lastIndex = 0;
220
+ return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
221
+ var c = meta[a];
222
+ return typeof c === 'string' ? c :
223
+ '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
224
+ }) + '"' : '"' + string + '"';
225
+ }
226
+
227
+
228
+ function str(key, holder) {
229
+
230
+ // Produce a string from holder[key].
231
+
232
+ var i, // The loop counter.
233
+ k, // The member key.
234
+ v, // The member value.
235
+ length,
236
+ mind = gap,
237
+ partial,
238
+ value = holder[key];
239
+
240
+ // If the value has a toJSON method, call it to obtain a replacement value.
241
+
242
+ if (value && typeof value === 'object' &&
243
+ typeof value.toJSON === 'function') {
244
+ value = value.toJSON(key);
245
+ }
246
+
247
+ // If we were called with a replacer function, then call the replacer to
248
+ // obtain a replacement value.
249
+
250
+ if (typeof rep === 'function') {
251
+ value = rep.call(holder, key, value);
252
+ }
253
+
254
+ // What happens next depends on the value's type.
255
+
256
+ switch (typeof value) {
257
+ case 'string':
258
+ return quote(value);
259
+
260
+ case 'number':
261
+
262
+ // JSON numbers must be finite. Encode non-finite numbers as null.
263
+
264
+ return isFinite(value) ? String(value) : 'null';
265
+
266
+ case 'boolean':
267
+ case 'null':
268
+
269
+ // If the value is a boolean or null, convert it to a string. Note:
270
+ // typeof null does not produce 'null'. The case is included here in
271
+ // the remote chance that this gets fixed someday.
272
+
273
+ return String(value);
274
+
275
+ // If the type is 'object', we might be dealing with an object or an array or
276
+ // null.
277
+
278
+ case 'object':
279
+
280
+ // Due to a specification blunder in ECMAScript, typeof null is 'object',
281
+ // so watch out for that case.
282
+
283
+ if (!value) {
284
+ return 'null';
285
+ }
286
+
287
+ // Make an array to hold the partial results of stringifying this object value.
288
+
289
+ gap += indent;
290
+ partial = [];
291
+
292
+ // Is the value an array?
293
+
294
+ if (Object.prototype.toString.apply(value) === '[object Array]') {
295
+
296
+ // The value is an array. Stringify every element. Use null as a placeholder
297
+ // for non-JSON values.
298
+
299
+ length = value.length;
300
+ for (i = 0; i < length; i += 1) {
301
+ partial[i] = str(i, value) || 'null';
302
+ }
303
+
304
+ // Join all of the elements together, separated with commas, and wrap them in
305
+ // brackets.
306
+
307
+ v = partial.length === 0 ? '[]' : gap ?
308
+ '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
309
+ '[' + partial.join(',') + ']';
310
+ gap = mind;
311
+ return v;
312
+ }
313
+
314
+ // If the replacer is an array, use it to select the members to be stringified.
315
+
316
+ if (rep && typeof rep === 'object') {
317
+ length = rep.length;
318
+ for (i = 0; i < length; i += 1) {
319
+ k = rep[i];
320
+ if (typeof k === 'string') {
321
+ v = str(k, value);
322
+ if (v) {
323
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
324
+ }
325
+ }
326
+ }
327
+ } else {
328
+
329
+ // Otherwise, iterate through all of the keys in the object.
330
+
331
+ for (k in value) {
332
+ if (Object.hasOwnProperty.call(value, k)) {
333
+ v = str(k, value);
334
+ if (v) {
335
+ partial.push(quote(k) + (gap ? ': ' : ':') + v);
336
+ }
337
+ }
338
+ }
339
+ }
340
+
341
+ // Join all of the member texts together, separated with commas,
342
+ // and wrap them in braces.
343
+
344
+ v = partial.length === 0 ? '{}' : gap ?
345
+ '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
346
+ '{' + partial.join(',') + '}';
347
+ gap = mind;
348
+ return v;
349
+ }
350
+ }
351
+
352
+ // If the JSON object does not yet have a stringify method, give it one.
353
+
354
+ if (typeof JSON.stringify !== 'function') {
355
+ JSON.stringify = function (value, replacer, space) {
356
+
357
+ // The stringify method takes a value and an optional replacer, and an optional
358
+ // space parameter, and returns a JSON text. The replacer can be a function
359
+ // that can replace values, or an array of strings that will select the keys.
360
+ // A default replacer method can be provided. Use of the space parameter can
361
+ // produce text that is more easily readable.
362
+
363
+ var i;
364
+ gap = '';
365
+ indent = '';
366
+
367
+ // If the space parameter is a number, make an indent string containing that
368
+ // many spaces.
369
+
370
+ if (typeof space === 'number') {
371
+ for (i = 0; i < space; i += 1) {
372
+ indent += ' ';
373
+ }
374
+
375
+ // If the space parameter is a string, it will be used as the indent string.
376
+
377
+ } else if (typeof space === 'string') {
378
+ indent = space;
379
+ }
380
+
381
+ // If there is a replacer, it must be a function or an array.
382
+ // Otherwise, throw an error.
383
+
384
+ rep = replacer;
385
+ if (replacer && typeof replacer !== 'function' &&
386
+ (typeof replacer !== 'object' ||
387
+ typeof replacer.length !== 'number')) {
388
+ throw new Error('JSON.stringify');
389
+ }
390
+
391
+ // Make a fake root object containing our value under the key of ''.
392
+ // Return the result of stringifying the value.
393
+
394
+ return str('', {'': value});
395
+ };
396
+ }
397
+
398
+
399
+ // If the JSON object does not yet have a parse method, give it one.
400
+
401
+ if (typeof JSON.parse !== 'function') {
402
+ JSON.parse = function (text, reviver) {
403
+
404
+ // The parse method takes a text and an optional reviver function, and returns
405
+ // a JavaScript value if the text is a valid JSON text.
406
+
407
+ var j;
408
+
409
+ function walk(holder, key) {
410
+
411
+ // The walk method is used to recursively walk the resulting structure so
412
+ // that modifications can be made.
413
+
414
+ var k, v, value = holder[key];
415
+ if (value && typeof value === 'object') {
416
+ for (k in value) {
417
+ if (Object.hasOwnProperty.call(value, k)) {
418
+ v = walk(value, k);
419
+ if (v !== undefined) {
420
+ value[k] = v;
421
+ } else {
422
+ delete value[k];
423
+ }
424
+ }
425
+ }
426
+ }
427
+ return reviver.call(holder, key, value);
428
+ }
429
+
430
+
431
+ // Parsing happens in four stages. In the first stage, we replace certain
432
+ // Unicode characters with escape sequences. JavaScript handles many characters
433
+ // incorrectly, either silently deleting them, or treating them as line endings.
434
+
435
+ text = String(text);
436
+ cx.lastIndex = 0;
437
+ if (cx.test(text)) {
438
+ text = text.replace(cx, function (a) {
439
+ return '\\u' +
440
+ ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
441
+ });
442
+ }
443
+
444
+ // In the second stage, we run the text against regular expressions that look
445
+ // for non-JSON patterns. We are especially concerned with '()' and 'new'
446
+ // because they can cause invocation, and '=' because it can cause mutation.
447
+ // But just to be safe, we want to reject all unexpected forms.
448
+
449
+ // We split the second stage into 4 regexp operations in order to work around
450
+ // crippling inefficiencies in IE's and Safari's regexp engines. First we
451
+ // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
452
+ // replace all simple value tokens with ']' characters. Third, we delete all
453
+ // open brackets that follow a colon or comma or that begin the text. Finally,
454
+ // we look to see that the remaining characters are only whitespace or ']' or
455
+ // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
456
+
457
+ if (/^[\],:{}\s]*$/
458
+ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
459
+ .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
460
+ .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
461
+
462
+ // In the third stage we use the eval function to compile the text into a
463
+ // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
464
+ // in JavaScript: it can begin a block or an object literal. We wrap the text
465
+ // in parens to eliminate the ambiguity.
466
+
467
+ j = eval('(' + text + ')');
468
+
469
+ // In the optional fourth stage, we recursively walk the new structure, passing
470
+ // each name/value pair to a reviver function for possible transformation.
471
+
472
+ return typeof reviver === 'function' ?
473
+ walk({'': j}, '') : j;
474
+ }
475
+
476
+ // If the text is not JSON parseable, then a SyntaxError is thrown.
477
+
478
+ throw new SyntaxError('JSON.parse');
479
+ };
480
+ }
481
+ }(this));