webapprt/WebappRT.jsm
author Ed Morley <emorley@mozilla.com>
Mon, 14 May 2012 21:05:24 +0100
changeset 96176 3f7291bc4efc003964fb98b1390019771042f3ac
parent 93670 ef55c163a23a0fb7dc361791a53b6149d69f3ca2
child 100710 df17f2f4ab63777c252b88b9e68211422a9c4501
permissions -rw-r--r--
Backout 345ae68f15f4, b3b40121ac8d, 0d18b7a246d7, 9dbb6064ab58, dee9d7fa8eb6, 63eec6bfa948, 323c6be7cfe8 & f4aac7523a48 (bug 732875) for compilation failures

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const EXPORTED_SYMBOLS = ["WebappRT"];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyGetter(this, "FileUtils", function() {
  Cu.import("resource://gre/modules/FileUtils.jsm");
  return FileUtils;
});

let WebappRT = {
  get config() {
    let webappFile = FileUtils.getFile("AppRegD", ["webapp.json"]);
    let inputStream = Cc["@mozilla.org/network/file-input-stream;1"].
                      createInstance(Ci.nsIFileInputStream);
    inputStream.init(webappFile, -1, 0, 0);
    let json = Cc["@mozilla.org/dom/json;1"].createInstance(Ci.nsIJSON);
    let config = json.decodeFromStream(inputStream, webappFile.fileSize);

    // Memoize the getter, freezing the `config` object in the meantime so
    // consumers don't inadvertently (or intentionally) change it, as the object
    // is meant to be a read-only representation of the webapp's configuration.
    config = deepFreeze(config);
    delete this.config;
    Object.defineProperty(this, "config", { get: function getConfig() config });
    return this.config;
  }
};

function deepFreeze(o) {
  // First, freeze the object.
  Object.freeze(o);

  // Then recursively call deepFreeze() to freeze its properties.
  for (let p in o) {
    // If the object is on the prototype, not an object, or is already frozen,
    // skip it.  Note that this might leave an unfrozen reference somewhere in
    // the object if there is an already frozen object containing an unfrozen
    // object.
    if (!o.hasOwnProperty(p) || !(typeof o[p] == "object") ||
        Object.isFrozen(o[p]))
      continue;

    deepFreeze(o[p]);
  }

  return o;
}