All files / module fluid.js

86.32% Statements 82/95
73.08% Branches 19/26
87.5% Functions 14/16
86.17% Lines 81/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268                                1x 1x 1x 1x   1x   1x 23x     1x 23x                         1x                     1x         1x 21x 21x 21x     1x 2x 2x 20x       1x   1x     1x         1x 5x     1x       1x 51x 51x 1x   51x       1x 24x 24x     1x 32x         1x 32x 32x 32x 32x 32x 32x 32x             32x       1x 1x   1x             1x   2x 1x 1x             1x 3x 3x       2x             1x   1x 6x     1x     1x 1x 1x                       1x 1x 1x               1x         1x               1x                   1x   1x     1x           1x 1x     1x         1x               1x           1x     1x         1x       1x       1x  
/*
Copyright 2012-2016 OCAD University
Copyright 2012 Raising the Floor - US
Copyright 2014-2016 Raising the Floor - International
 
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
 
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
/* eslint-env node */
/* global global */
"use strict";
 
var fs = require("fs"),
    path = require("path"),
    vm = require("vm"),
    resolve = require("fluid-resolve");
 
var moduleBaseDir = path.resolve(__dirname, "../..");
 
var getBaseDir = function () {
    return __dirname;
};
 
var buildPath = function (pathSeg) {
    return path.join(getBaseDir(), pathSeg);
};
 
// Report of experiments performed with node.js globals done on 1/9/14 - what we might like to write at this point is
// fluid: {global: GLOBAL}; - this "nearly" works but unfortunately the process of transporting the "pan-global" object
// across the sandbox initialization boundary ends up shredding it. We end up with a situation where in this file,
// fluid.global.fluid === fluid - but from within Fluid.js, fluid.global.fluid === undefined. node.js docs on sandboxing
// do report that the results can be fragile and version unstable. However, we need to continue with sandboxing because of
// the delicate expectations, for example, on visible globals caused by QUnit's sniffing code.
// Experiment performed with node.js 0.8.6 on Windows.
// We achieve a lot of what we might want via "global.fluid = fluid" below. However, other top-level names constructed
// via fluid.registerNamespace will not be exported up to the pan-global.
 
var context = vm.createContext({
    console: console,
    setTimeout: setTimeout,
    clearTimeout: clearTimeout,
    setInterval: setInterval,
    clearInterval: clearInterval,
    __dirname: __dirname,
    path: path,
    require: require
});
 
context.window = context;
 
/** Load a standard, non-require-aware Fluid framework file into the Fluid context, given a filename
 * relative to this directory (src/module) **/
 
var loadInContext = function (path) {
    var fullpath = buildPath(path);
    var data = fs.readFileSync(fullpath);
    vm.runInContext(data, context, fullpath);
};
 
var loadIncludes = function (path) {
    var includes = require(buildPath(path));
    for (var i = 0; i < includes.length; ++i) {
        loadInContext(includes[i]);
    }
};
 
loadIncludes("includes.json");
 
var fluid = context.fluid;
// FLUID-4913: QUnit calls window.addEventListener on load. We need to add
// it to the context it will be loaded in.
context.addEventListener = fluid.identity;
 
// As well as for efficiency, it's useful to customise this because an uncaught
// exception fired from a a setTimeout handler in node.js will prevent any
// further from being serviced, which impedes testing these handlers
fluid.invokeLater = function (func) {
    process.nextTick(func);
};
 
fluid.logObjectRenderChars = 1024;
 
// Convert an argument intended for console.log in the node environment to a readable form (the
// default action of util.inspect censors at depth 1)
fluid.renderLoggingArg = function (arg) {
    var togo = arg && fluid.isPrimitive(arg) ? arg : fluid.prettyPrintJSON(arg, {maxRenderChars: fluid.logObjectRenderChars});
    if (typeof(togo) === "string" && togo.length > fluid.logObjectRenderChars) {
        togo = togo.substring(0, fluid.logObjectRenderChars) + " .... [output suppressed at " + fluid.logObjectRenderChars + " chars - for more output, increase fluid.logObjectRenderChars]";
    }
    return togo;
};
 
// Monkey-patch the built-in fluid.doLog utility to improve its behaviour within node.js - see FLUID-5475
fluid.doLog = function (args) {
    args = fluid.transform(args, fluid.renderLoggingArg);
    console.log(args.join(""));
};
 
fluid.prepareV8StackTrace = function (err, stack) {
    return stack;
};
 
// Monkey-patch the fluid.getCallerInfo utility from FluidDebugging.js for the V8 API - see https://github.com/v8/v8/wiki/Stack-Trace-API
 
fluid.getCallerInfo = function (atDepth) {
    var origPrepare = Error.prepareStackTrace;
    try {
        Error.prepareStackTrace = fluid.prepareV8StackTrace;
        var err = new Error();
        var element = err.stack[atDepth];
        var filename = element.getFileName();
        return {
            path: path.dirname(filename),
            filename: path.basename(filename),
            index: element.getLineNumber() + ":" + element.getColumnNumber()
        };
    } catch (e) {
    } finally {
        Error.prepareStackTrace = origPrepare;
    }
};
 
fluid.loadInContext = loadInContext;
fluid.loadIncludes = loadIncludes;
 
fluid.testingSupportLoaded = false;
 
/**
 * Set up testing environment with jqUnit and IoC Test Utils in node.
 * This function will load the Infusion internal dependencies (QUnit, jqUnit and the IoC Testing Framework) necessary
 * for running node-jqUnit - the node-jqunit module itself must still be loaded by the user via their own devDependencies.
 */
fluid.loadTestingSupport = function () {
    // Guard against multiple inclusion of QUnit - FLUID-6188
    if (!fluid.testingSupportLoaded) {
        fluid.loadIncludes("devIncludes.json");
        fluid.testingSupportLoaded = true;
    }
};
 
/** Implementation for FLUID-5822 to avoid requirement for dedupe-infusion **/
 
// Version of resolve.sync which does not throw when module is not found
fluid.module.resolveSync = function (moduleId, fromPath) {
    try {
        return resolve.sync(moduleId, {
            basedir: fromPath
        });
    } catch (e) {
        return null;
    }
};
 
// Method 1: Resolve to the highest infusion which is observable through the "pre-inspection" method of looking
// literally into the filesystem for package.json files which can be successfully loaded
 
var moduleInfo = fluid.module.modulesToRoot(__dirname);
 
var highestInfusionIndex = fluid.find(moduleInfo.names, function (name, index) {
    return name === "infusion" ? index : undefined;
});
 
Eif (highestInfusionIndex !== undefined) {
    // If this require throws, there is some other undesirable problem with the thing appearing to be an Infusion at
    // this path which should be reported as an uncaught exception
    var highestInfusionPath = moduleInfo.paths[highestInfusionIndex];
    var infusionModule = require(highestInfusionPath);
    Iif (infusionModule.module && infusionModule.module.modules.infusion.baseDir !== moduleBaseDir) {
        console.log("Pre-inspection from path " + __dirname + " resolved to infusion at higher path " + highestInfusionPath);
        module.exports = infusionModule;
        return;
    }
}
 
// Method 2: Resolve to any infusion which is observable to the standard node loader at a path strictly higher than ours
// TODO: Is this completely subsumed by Method 1?
 
var upInfusion;
 
var upPath = path.resolve(__dirname, "../../../../..");
var upInfusionPath = fluid.module.resolveSync("infusion", upPath);
Iif (upInfusionPath) {
    upInfusion = require(upInfusionPath);
}
 
// Fix for FLUID-5940, when Infusion is a dependency of a Node.js project that is located in the
// root of a filesystem we were resolving to the current version of Infusion. Doing a 'require'
// on the same version of Infusion results in an empty object since we have not completed our own assignment to
// module.exports yet
Iif (upInfusion && upInfusion.module) {
    console.log("Resolved infusion from path " + __dirname + " to " + upInfusion.module.modules.infusion.baseDir);
    module.exports = upInfusion;
    return;
} else {
    console.log("Infusion at path " + moduleBaseDir + " is at top level ");
}
 
// If we reach here without hitting the "return" statements above, we believe ourselves to be the highest resolvable
// Infusion in the filesystem. If we are wrong, some other Infusion has already registered itself in node's
// pan-module global registry - if we find it there, we should bail out with a fatal error since corruption will
// shortly soon result in the grade registry and component tree.
 
Iif (global.fluid) {
    var oldPath = global.fluid.module.modules.infusion.baseDir;
    fluid.fail("Error loading infusion - infusion has already been loaded from the path \n\t" + path.resolve(oldPath) +
        "\n - please delete the duplicate copy which is found at \n\t" + path.resolve(__dirname) +
        "\n This can be done automatically by running the task \"grunt dedupe-infusion\"");
}
 
// Pre-inspect any other module (there should be at most one) which is loading at top level so that it is self-resolvable
// via fluid.require("%other-module") for whatever it is
 
fluid.module.preInspect();
 
fluid.module.register("infusion", moduleBaseDir, require);
 
// Export the fluid object into the pan-module node.js global object
global.fluid = fluid;
 
 
/** Registering and instrumenting uncaught exception handler:
 * Do this after determining that we are top-level Infusion to avoid FLUID-6225
 */
process.on("uncaughtException", function onUncaughtException(err) {
    fluid.onUncaughtException.fire(err);
});
 
fluid.onUncaughtException = fluid.makeEventFirer({
    name: "Global uncaught exception handler"
});
 
// This registry of priorities will be removed once the implementation of FLUID-5506 is complete
fluid.handlerPriorities = {
    uncaughtException: {
        log: 100, // high priority - do all logging first
        logActivity: "after:log",
        fail: "last"
    }
};
 
fluid.logUncaughtException = function (err) {
    var message = "FATAL ERROR: Uncaught exception: " + err.message;
    fluid.log(fluid.logLevel.FATAL, message);
    console.log(err.stack);
};
 
fluid.onUncaughtException.addListener(fluid.logUncaughtException, "log",
    fluid.handlerPriorities.uncaughtException.log);
 
fluid.onUncaughtException.addListener(function () {fluid.logActivity();}, "logActivity",
    fluid.handlerPriorities.uncaughtException.logActivity);
 
 
// Make sure process exits with error (see FLUID-5920)
fluid.handleUncaughtException = function () {
    process.exit(1);
};
 
fluid.onUncaughtException.addListener(fluid.handleUncaughtException, "fail",
    fluid.handlerPriorities.uncaughtException.fail);
 
 
module.exports = fluid;