// DO NOT EDIT THIS FILE BY HAND

// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

var Filter = {
  filter : function(docs, req, userCtx) {
    var results = [];
    try {
      for (var i=0; i < docs.length; i++) {
        results.push((funs[0](docs[i], req, userCtx) && true) || false);
      };
      respond([true, results]);
    } catch (error) {
      respond(error);
    }
  }
};
// mimeparse.js
//
// This module provides basic functions for handling mime-types. It can
// handle matching mime-types against a list of media-ranges. See section
// 14.1 of the HTTP specification [RFC 2616] for a complete explanation.
//
//   http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
//
// A port to JavaScript of Joe Gregorio's MIME-Type Parser:
//
//   http://code.google.com/p/mimeparse/
//
// Ported by J. Chris Anderson <jchris@apache.org>, targeting the Spidermonkey runtime.
//
// To run the tests, open mimeparse-js-test.html in a browser.
// Ported from version 0.1.2
// Comments are mostly excerpted from the original.

var Mimeparse = (function() {
  // private helpers
  function strip(string) {
    return string.replace(/^\s+/, '').replace(/\s+$/, '')
  };

  function parseRanges(ranges) {
    var parsedRanges = [], rangeParts = ranges.split(",");
    for (var i=0; i < rangeParts.length; i++) {
      parsedRanges.push(publicMethods.parseMediaRange(rangeParts[i]))
    };
    return parsedRanges;
  };

  var publicMethods = {
    // Carves up a mime-type and returns an Array of the
    //  [type, subtype, params] where "params" is a Hash of all
    //  the parameters for the media range.
    //
    // For example, the media range "application/xhtml;q=0.5" would
    //  get parsed into:
    //
    // ["application", "xhtml", { "q" : "0.5" }]
    parseMimeType : function(mimeType) {
      var fullType, typeParts, params = {}, parts = mimeType.split(';');
      for (var i=0; i < parts.length; i++) {
        var p = parts[i].split('=');
        if (p.length == 2) {
          params[strip(p[0])] = strip(p[1]);
        }
      };
      fullType = parts[0].replace(/^\s+/, '').replace(/\s+$/, '');
      if (fullType == '*') fullType = '*/*';
      typeParts = fullType.split('/');
      return [typeParts[0], typeParts[1], params];
    },

    // Carves up a media range and returns an Array of the
    //  [type, subtype, params] where "params" is a Object with
    //  all the parameters for the media range.
    //
    // For example, the media range "application/*;q=0.5" would
    //  get parsed into:
    //
    // ["application", "*", { "q" : "0.5" }]
    //
    // In addition this function also guarantees that there
    //  is a value for "q" in the params dictionary, filling it
    //  in with a proper default if necessary.
    parseMediaRange : function(range) {
      var q, parsedType = this.parseMimeType(range);
      if (!parsedType[2]['q']) {
        parsedType[2]['q'] = '1';
      } else {
        q = parseFloat(parsedType[2]['q']);
        if (isNaN(q)) {
          parsedType[2]['q'] = '1';
        } else if (q > 1 || q < 0) {
          parsedType[2]['q'] = '1';
        }
      }
      return parsedType;
    },

    // Find the best match for a given mime-type against
    // a list of media_ranges that have already been
    // parsed by parseMediaRange(). Returns an array of
    // the fitness value and the value of the 'q' quality
    // parameter of the best match, or (-1, 0) if no match
    // was found. Just as for qualityParsed(), 'parsed_ranges'
    // must be a list of parsed media ranges.
    fitnessAndQualityParsed : function(mimeType, parsedRanges) {
      var bestFitness = -1, bestFitQ = 0, target = this.parseMediaRange(mimeType);
      var targetType = target[0], targetSubtype = target[1], targetParams = target[2];

      for (var i=0; i < parsedRanges.length; i++) {
        var parsed = parsedRanges[i];
        var type = parsed[0], subtype = parsed[1], params = parsed[2];
        if ((type == targetType || type == "*" || targetType == "*") &&
          (subtype == targetSubtype || subtype == "*" || targetSubtype == "*")) {
          var matchCount = 0;
          for (param in targetParams) {
            if (param != 'q' && params[param] && params[param] == targetParams[param]) {
              matchCount += 1;
            }
          }

          var fitness = (type == targetType) ? 100 : 0;
          fitness += (subtype == targetSubtype) ? 10 : 0;
          fitness += matchCount;

          if (fitness > bestFitness) {
            bestFitness = fitness;
            bestFitQ = params["q"];
          }
        }
      };
      return [bestFitness, parseFloat(bestFitQ)];
    },

    // Find the best match for a given mime-type against
    // a list of media_ranges that have already been
    // parsed by parseMediaRange(). Returns the
    // 'q' quality parameter of the best match, 0 if no
    // match was found. This function bahaves the same as quality()
    // except that 'parsedRanges' must be a list of
    // parsed media ranges.
    qualityParsed : function(mimeType, parsedRanges) {
      return this.fitnessAndQualityParsed(mimeType, parsedRanges)[1];
    },

    // Returns the quality 'q' of a mime-type when compared
    // against the media-ranges in ranges. For example:
    //
    // >>> Mimeparse.quality('text/html','text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
    // 0.7
    quality : function(mimeType, ranges) {
      return this.qualityParsed(mimeType, parseRanges(ranges));
    },

    // Takes a list of supported mime-types and finds the best
    // match for all the media-ranges listed in header. The value of
    // header must be a string that conforms to the format of the
    // HTTP Accept: header. The value of 'supported' is a list of
    // mime-types.
    //
    // >>> bestMatch(['application/xbel+xml', 'text/xml'], 'text/*;q=0.5,*/*; q=0.1')
    // 'text/xml'
    bestMatch : function(supported, header) {
      var parsedHeader = parseRanges(header);
      var weighted = [];
      for (var i=0; i < supported.length; i++) {
        weighted.push([publicMethods.fitnessAndQualityParsed(supported[i], parsedHeader), i, supported[i]])
      };
      weighted.sort();
      return weighted[weighted.length-1][0][1] ? weighted[weighted.length-1][2] : '';
    }
  }
  return publicMethods;
})();
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.


// registerType(name, mime-type, mime-type, ...)
// 
// Available in query server sandbox. TODO: The list is cleared on reset.
// This registers a particular name with the set of mimetypes it can handle.
// Whoever registers last wins.
// 
// Example: 
// registerType("html", "text/html; charset=utf-8");

mimesByKey = {};
keysByMime = {};
registerType = function() {
  var mimes = [], key = arguments[0];
  for (var i=1; i < arguments.length; i++) {
    mimes.push(arguments[i]);
  };
  mimesByKey[key] = mimes;
  for (var i=0; i < mimes.length; i++) {
    keysByMime[mimes[i]] = key;
  };
};

// Some default types
// Ported from Ruby on Rails
// Build list of Mime types for HTTP responses
// http://www.iana.org/assignments/media-types/
// http://dev.rubyonrails.org/svn/rails/trunk/actionpack/lib/action_controller/mime_types.rb

registerType("all", "*/*");
registerType("text", "text/plain; charset=utf-8", "txt");
registerType("html", "text/html; charset=utf-8");
registerType("xhtml", "application/xhtml+xml", "xhtml");
registerType("xml", "application/xml", "text/xml", "application/x-xml");
registerType("js", "text/javascript", "application/javascript", "application/x-javascript");
registerType("css", "text/css");
registerType("ics", "text/calendar");
registerType("csv", "text/csv");
registerType("rss", "application/rss+xml");
registerType("atom", "application/atom+xml");
registerType("yaml", "application/x-yaml", "text/yaml");
// just like Rails
registerType("multipart_form", "multipart/form-data");
registerType("url_encoded_form", "application/x-www-form-urlencoded");
// http://www.ietf.org/rfc/rfc4627.txt
registerType("json", "application/json", "text/x-json");

//  Start chunks
var startResp = {};
function start(resp) {
  startResp = resp || {};
};

function sendStart() {
  startResp = applyContentType((startResp || {}), responseContentType);
  respond(["start", chunks, startResp]);
  chunks = [];
  startResp = {};
}

function applyContentType(resp, responseContentType) {
  resp["headers"] = resp["headers"] || {};
  if (responseContentType) {
    resp["headers"]["Content-Type"] = resp["headers"]["Content-Type"] || responseContentType;    
  }
  return resp;
}

//  Send chunk
var chunks = [];
function send(chunk) {
  chunks.push(chunk.toString());
};

function blowChunks(label) {
  respond([label||"chunks", chunks]);
  chunks = [];
};

var gotRow = false, lastRow = false;
function getRow() {
  if (lastRow) return null;
  if (!gotRow) {
    gotRow = true;
    sendStart();
  } else {
    blowChunks();
  }
  var line = readline();
  var json = eval(line);
  if (json[0] == "list_end") {
    lastRow = true;
    return null;
  }
  if (json[0] != "list_row") {
    respond({
      error: "query_server_error",
      reason: "not a row '" + json[0] + "'"});
    quit();
  }
  return json[1];
};

var mimeFuns = [], providesUsed, responseContentType;
function provides(type, fun) {
  providesUsed = true;
  mimeFuns.push([type, fun]);
};

function runProvides(req) {
  var supportedMimes = [], bestFun, bestKey = null, accept = req.headers["Accept"];
  if (req.query && req.query.format) {
    bestKey = req.query.format;
    responseContentType = mimesByKey[bestKey][0];
  } else if (accept) {
    // log("using accept header: "+accept);
    mimeFuns.reverse().forEach(function(mimeFun) {
      var mimeKey = mimeFun[0];
      if (mimesByKey[mimeKey]) {
        supportedMimes = supportedMimes.concat(mimesByKey[mimeKey]);
      }
    });
    responseContentType = Mimeparse.bestMatch(supportedMimes, accept);
    bestKey = keysByMime[responseContentType];
  } else {
    // just do the first one
    bestKey = mimeFuns[0][0];
    responseContentType = mimesByKey[bestKey][0];
  }
  
  if (bestKey) {
    for (var i=0; i < mimeFuns.length; i++) {
      if (mimeFuns[i][0] == bestKey) {
        bestFun = mimeFuns[i][1];
        break;
      }
    };
  };
  
  if (bestFun) {
    // log("responding with: "+bestKey);
    return bestFun();
  } else {
    var supportedTypes = mimeFuns.map(function(mf) {return mimesByKey[mf[0]].join(', ') || mf[0]});
    throw({error:"not_acceptable", reason:"Content-Type "+(accept||bestKey)+" not supported, try one of: "+supportedTypes.join(', ')});
  }
};



////
////  Render dispatcher
////
////
////
////

var Render = {
  show : function(funSrc, doc, req) {
    var showFun = compileFunction(funSrc);
    runShow(showFun, doc, req, funSrc);
  },
  update : function(funSrc, doc, req) {
    var upFun = compileFunction(funSrc);
    runUpdate(upFun, doc, req, funSrc);
  },
  list : function(head, req) {
    runList(funs[0], head, req, funsrc[0]);
  }
};

function maybeWrapResponse(resp) {
  var type = typeof resp;
  if ((type == "string") || (type == "xml")) {
    return {body:resp};
  } else {
    return resp;
  }
};

function resetProvides() {
  // set globals
  providesUsed = false;
  mimeFuns = [];
  responseContentType = null;  
};

function runShow(showFun, doc, req, funSrc) {
  try {
    resetProvides();
    var resp = showFun.apply(null, [doc, req]);
    
    if (providesUsed) {
      resp = runProvides(req);
      resp = applyContentType(maybeWrapResponse(resp), responseContentType);
    }
    
    if (resp) {
      respond(["resp", maybeWrapResponse(resp)]);
    } else {
      renderError("undefined response from show function");
    }
  } catch(e) {
    respondError(e, funSrc, true);
  }
};

function runUpdate(renderFun, doc, req, funSrc) {
  try {
    var result = renderFun.apply(null, [doc, req]);
    var doc = result[0];
    var resp = result[1];
    if (resp) {
      respond(["up", doc, maybeWrapResponse(resp)]);
    } else {
      renderError("undefined response from update function");
    }
  } catch(e) {
    respondError(e, funSrc, true);
  }
};

function resetList() {
  gotRow = false;
  lastRow = false;
  chunks = [];
  startResp = {};
};

function runList(listFun, head, req, funSrc) {
  try {
    if (listFun.arity > 2) {
      throw("the list API has changed for CouchDB 0.10, please upgrade your code");
    }
    
    resetProvides();
    resetList();
    
    var tail = listFun.apply(null, [head, req]);
    
    if (providesUsed) {
      tail = runProvides(req);
    }
    
    if (!gotRow) {
      getRow();
    }
    if (typeof tail != "undefined") {
      chunks.push(tail);
    }
    blowChunks("end");
  } catch(e) {
    respondError(e, funSrc, false);
  }
};

function renderError(m) {
  respond({error : "render_error", reason : m});
}

function respondError(e, funSrc, htmlErrors) {
  if (e.error && e.reason) {
    respond(e);
  } else {
    var logMessage = "function raised error: "+e.toString();
    log(logMessage);
    log("stacktrace: "+e.stack);
    var errorMessage = htmlErrors ? htmlRenderError(e, funSrc) : logMessage;
    renderError(errorMessage);
  }
}

function escapeHTML(string) {
  return string.replace(/&/g, "&amp;")
               .replace(/</g, "&lt;")
               .replace(/>/g, "&gt;");
}

function htmlRenderError(e, funSrc) {
  var msg = ["<html><body><h1>Render Error</h1>",
    "<p>JavaScript function raised error: ",
    e.toString(),
    "</p><h2>Stacktrace:</h2><code><pre>",
    escapeHTML(e.stack),
    "</pre></code><h2>Function source:</h2><code><pre>",
    escapeHTML(funSrc),
    "</pre></code></body></html>"].join('');
  return {body:msg};
};
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

// globals used by other modules and functions
var funs = [];        // holds functions used for computation
var funsrc = [];      // holds function source for debug info
var query_config = {};
var State = (function() {
  return {
    reset : function(config) {
      // clear the globals and run gc
      funs = [];
      funsrc = [];
      query_config = config;
      gc();
      print("true"); // indicates success
    },
    addFun : function(newFun) {
      // Compile to a function and add it to funs array
      funsrc.push(newFun);
      funs.push(compileFunction(newFun));
      print("true");
    }
  }
})();
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

toJSON.subs = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f',
              '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
toJSON.dispatcher = {
    "Array": function(v) {
      var buf = [];
      for (var i = 0; i < v.length; i++) {
        buf.push(toJSON(v[i]));
      }
      return "[" + buf.join(",") + "]";
    },
    "Boolean": function(v) {
      return v.toString();
    },
    "Date": function(v) {
      var f = function(n) { return n < 10 ? '0' + n : n };
      return '"' + v.getUTCFullYear()   + '-' +
                 f(v.getUTCMonth() + 1) + '-' +
                 f(v.getUTCDate())      + 'T' +
                 f(v.getUTCHours())     + ':' +
                 f(v.getUTCMinutes())   + ':' +
                 f(v.getUTCSeconds())   + 'Z"';
    },
    "Number": function(v) {
      return isFinite(v) ? v.toString() : "null";
    },
    "Object": function(v) {
      //if (v === null) return "null";
      var buf = [];
      for (var k in v) {
        if (!v.hasOwnProperty(k) || typeof(k) !== "string" || v[k] === undefined) {
          continue;
        }
        buf.push(toJSON(k) + ": " + toJSON(v[k]));
      }
      return "{" + buf.join(",") + "}";
    },
    "String": function(v) {
      if (/["\\\x00-\x1f]/.test(v)) {
        v = v.replace(/([\x00-\x1f\\"])/g, function(a, b) {
          var c = toJSON.subs[b];
          if (c) return c;
          c = b.charCodeAt();
          return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
        });
      }
      return '"' + v + '"';
    }
};

function toJSON(val) {
  if (typeof(val) == "undefined") {
    throw "Cannot encode 'undefined' value as JSON";
  }
  if (typeof(val) == "xml") { // E4X support
    val = val.toXMLString();
  }
  if (val === null) { return "null"; }
  return (toJSON.dispatcher[val.constructor.name])(val);
}

function compileFunction(source) {
  try {
    var functionObject = sandbox ? evalcx(source, sandbox) : eval(source);
  } catch (err) {
    throw {error: "compilation_error",
      reason: err.toString() + " (" + source + ")"};
  }
  if (typeof(functionObject) == "function") {
    return functionObject;
  } else {
    throw {error: "compilation_error",
      reason: "expression does not eval to a function. (" + source + ")"};
  }
}

function recursivelySeal(obj) {
  seal(obj);
  for (var propname in obj) {
    if (typeof doc[propname] == "object") {
      recursivelySeal(doc[propname]);
    }
  }
}

// prints the object as JSON, and rescues and logs any toJSON() related errors
function respond(obj) {
  try {
    print(toJSON(obj));
  } catch(e) {
    log("Error converting object to JSON: " + e.toString());
  }
};

log = function(message) {
  // return;
  if (typeof message == "undefined") {
    message = "Error: attempting to log message of 'undefined'.";
  } else if (typeof message != "string") {
    message = toJSON(message);
  }
  respond(["log", message]);
};
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

var Validate = {
  validate : function(funSrc, newDoc, oldDoc, userCtx) {
    var validateFun = compileFunction(funSrc);
    try {
      validateFun(newDoc, oldDoc, userCtx);
      print("1");
    } catch (error) {
      respond(error);
    }
  }
};
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

// globals used by views
var map_results = []; // holds temporary emitted values during doc map

// view helper functions
emit = function(key, value) {
  map_results.push([key, value]);
}

sum = function(values) {
  var rv = 0;
  for (var i in values) {
    rv += values[i];
  }
  return rv;
}

var Views = (function() {

  function runReduce(reduceFuns, keys, values, rereduce) {
    for (var i in reduceFuns) {
      reduceFuns[i] = compileFunction(reduceFuns[i]);
    }
    var reductions = new Array(reduceFuns.length);
    for(var i = 0; i < reduceFuns.length; i++) {
      try {
        reductions[i] = reduceFuns[i](keys, values, rereduce);
      } catch (err) {
        if (err == "fatal_error") {
          throw {
            error: "reduce_runtime_error",
            reason: "function raised fatal exception"};
        }
        log("function raised exception (" + err + ")");
        reductions[i] = null;
      }
    }
    var reduce_line = toJSON(reductions);
    var reduce_length = reduce_line.length;
    if (query_config && query_config.reduce_limit &&
          reduce_length > 200 && ((reduce_length * 2) > line.length)) {
      var reduce_preview = "Current output: '"+(reduce_line.substring(0,100) + "'... (first 100 of "+reduce_length+' bytes)');

      throw {
        error:"reduce_overflow_error",
        reason: "Reduce output must shrink more rapidly: "+reduce_preview+""
      };
    } else {
      print("[true," + reduce_line + "]");
    }
  };

  return {
    reduce : function(reduceFuns, kvs) {
      var keys = new Array(kvs.length);
      var values = new Array(kvs.length);
      for(var i = 0; i < kvs.length; i++) {
          keys[i] = kvs[i][0];
          values[i] = kvs[i][1];
      }
      runReduce(reduceFuns, keys, values, false);
    },
    rereduce : function(reduceFuns, values) {
      runReduce(reduceFuns, null, values, true);
    },
    mapDoc : function(doc) {
      // Compute all the map functions against the document.
      //
      // Each function can output multiple key/value pairs for each document.
      //
      // Example output of map_doc after three functions set by add_fun cmds:
      // [
      //  [["Key","Value"]],                    <- fun 1 returned 1 key value
      //  [],                                   <- fun 2 returned 0 key values
      //  [["Key1","Value1"],["Key2","Value2"]] <- fun 3 returned 2 key values
      // ]
      //

      /*
      Immutable document support temporarily removed.

      Removed because the seal function no longer works on JS 1.8 arrays,
      instead returning an error. The sealing is meant to prevent map
      functions from modifying the same document that is passed to other map
      functions. However, only map functions in the same design document are
      run together, so we have a reasonable expectation they can trust each
      other. Any map fun that can't be trusted can be placed in its own
      design document, and it cannot affect other map functions.

      recursivelySeal(doc); // seal to prevent map functions from changing doc
      */
      var buf = [];
      for (var i = 0; i < funs.length; i++) {
        map_results = [];
        try {
          funs[i](doc);
          buf.push(toJSON(map_results));
        } catch (err) {
          if (err == "fatal_error") {
            // Only if it's a "fatal_error" do we exit. What's a fatal error?
            // That's for the query to decide.
            //
            // This will make it possible for queries to completely error out,
            // by catching their own local exception and rethrowing a
            // fatal_error. But by default if they don't do error handling we
            // just eat the exception and carry on.
            throw {
              error: "map_runtime_error",
              reason: "function raised fatal exception"};
          }
          log("function raised exception (" + err + ") with doc._id " + doc._id);
          buf.push("[]");
        }
      }
      print("[" + buf.join(", ") + "]");
    }
  }
})();
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

var sandbox = null;

try {
  // if possible, use evalcx (not always available)
  sandbox = evalcx('');
  sandbox.emit = emit;
  sandbox.sum = sum;
  sandbox.log = log;
  sandbox.toJSON = toJSON;
  sandbox.provides = provides;
  sandbox.registerType = registerType;
  sandbox.start = start;
  sandbox.send = send;
  sandbox.getRow = getRow;
} catch (e) {}

// Commands are in the form of json arrays:
// ["commandname",..optional args...]\n
//
// Responses are json values followed by a new line ("\n")

var line, cmd, cmdkey;

var dispatch = {
  "reset"    : State.reset,
  "add_fun"  : State.addFun,
  "map_doc"  : Views.mapDoc,
  "reduce"   : Views.reduce,
  "rereduce" : Views.rereduce,
  "validate" : Validate.validate,
  "show"     : Render.show,
  "update"   : Render.update,
  "list"     : Render.list,
  "filter"   : Filter.filter
};

while (line = eval(readline())) {
  cmd = eval(line);
  line_length = line.length;
  try {
    cmdkey = cmd.shift();
    if (dispatch[cmdkey]) {
      // run the correct responder with the cmd body
      dispatch[cmdkey].apply(this, cmd);
    } else {
      // unknown command, quit and hope the restarted version is better
      respond({
        error: "query_server_error",
        reason: "unknown command '" + cmdkey + "'"});
      quit();
    }
  } catch(e) {
    respond(e);
  }
};
