<commit_before>Object.defineProperty(exports, "__esModule", { value: true });
const vscode = require("vscode");
const path_1 = require("path");

class LuaConfigurationProvider {
    /**
     * Returns an initial debug configuration based on contextual information, e.g. package.json or folder.
     */
    provideDebugConfigurations(folder, token) {
        return [createLaunchConfig(folder)];
    }
    /**
     * Try to add all missing attributes to the debug configuration being launched.
     */
    resolveDebugConfiguration(folder, config, token) {
        if (!config.type && !config.request && !config.name) {
            config = createLaunchConfig(folder);
        }
        config.type = 'lua';
        config.workspaceFolder = '${workspaceFolder}';
        if (config.request != 'attach') {
            config.request = 'launch';
        }
        if (typeof config.cwd != 'string') {
            config.cwd = '${workspaceFolder}';
        }
        if (typeof config.stopOnEntry != 'boolean') {
            config.stopOnEntry = true;
        }
        if (typeof config.consoleCoding != 'string') {
            config.consoleCoding = 'utf8'
        }
        if (typeof config.sourceCoding != 'string') {
            config.sourceCoding = 'ansi'
        }
        if (config.request == 'launch') {
            if (!config.program && !config.runtimeExecutable) {
                return vscode.window.showInformationMessage('Cannot find a program to debug').then(_ => {
                    return undefined;
                });
            }
            if (typeof config.path != 'string') {
                config.path = '${workspaceRoot}/?.lua';
            }
            if (typeof config.cpath != 'string') {
                config.cpath = '${workspaceRoot}/?.dll';
            }
        }
        else if (config.request == 'attach') {
            if (!config.ip || !config.port) {
                return vscode.window.showInformationMessage('Cannot missing ip or port to debug').then(_ => {
                    return undefined;
                });
            }
        }
        return config
    }
}
exports.LuaConfigurationProvider = LuaConfigurationProvider;

function createLaunchConfig(folder) {
    const config = {
        type: 'lua',
        request: 'launch',
        name: 'Launch'
    };
    let program;
    const editor = vscode.window.activeTextEditor;
    if (editor && editor.document.languageId === 'lua') {
        const wf = vscode.workspace.getWorkspaceFolder(editor.document.uri);
        if (wf === folder) {
            program = vscode.workspace.asRelativePath(editor.document.uri);
            if (!path_1.isAbsolute(program)) {
                program = '${workspaceFolder}/' + program;
            }
        }
    }
    if (program) {
        config['program'] = program;
    }
    else {
        config['program'] = '${file}';
    }
    return config;
}
<commit_msg>指定luaexe之后不再给cpath和path默认值<commit_after>Object.defineProperty(exports, "__esModule", { value: true });
const vscode = require("vscode");
const path_1 = require("path");

class LuaConfigurationProvider {
    /**
     * Returns an initial debug configuration based on contextual information, e.g. package.json or folder.
     */
    provideDebugConfigurations(folder, token) {
        return [createLaunchConfig(folder)];
    }
    /**
     * Try to add all missing attributes to the debug configuration being launched.
     */
    resolveDebugConfiguration(folder, config, token) {
        if (!config.type && !config.request && !config.name) {
            config = createLaunchConfig(folder);
        }
        config.type = 'lua';
        config.workspaceFolder = '${workspaceFolder}';
        if (config.request != 'attach') {
            config.request = 'launch';
        }
        if (typeof config.cwd != 'string') {
            config.cwd = '${workspaceFolder}';
        }
        if (typeof config.stopOnEntry != 'boolean') {
            config.stopOnEntry = true;
        }
        if (typeof config.consoleCoding != 'string') {
            config.consoleCoding = 'utf8'
        }
        if (typeof config.sourceCoding != 'string') {
            config.sourceCoding = 'ansi'
        }
        if (config.request == 'launch') {
            if (!config.program && !config.runtimeExecutable) {
                return vscode.window.showInformationMessage('Cannot find a program to debug').then(_ => {
                    return undefined;
                });
            }
            if (typeof config.luaexe != 'string') {
                if (typeof config.path != 'string') {
                    config.path = '${workspaceRoot}/?.lua';
                }
                if (typeof config.cpath != 'string') {
                    config.cpath = '${workspaceRoot}/?.dll';
                }
            }
        }
        else if (config.request == 'attach') {
            if (!config.ip || !config.port) {
                return vscode.window.showInformationMessage('Cannot missing ip or port to debug').then(_ => {
                    return undefined;
                });
            }
        }
        return config
    }
}
exports.LuaConfigurationProvider = LuaConfigurationProvider;

function createLaunchConfig(folder) {
    const config = {
        type: 'lua',
        request: 'launch',
        name: 'Launch'
    };
    let program;
    const editor = vscode.window.activeTextEditor;
    if (editor && editor.document.languageId === 'lua') {
        const wf = vscode.workspace.getWorkspaceFolder(editor.document.uri);
        if (wf === folder) {
            program = vscode.workspace.asRelativePath(editor.document.uri);
            if (!path_1.isAbsolute(program)) {
                program = '${workspaceFolder}/' + program;
            }
        }
    }
    if (program) {
        config['program'] = program;
    }
    else {
        config['program'] = '${file}';
    }
    return config;
}
<|endoftext|>


<commit_before>var fs = require("fs");
var cx = require("cloneextend");
var spawn = require("child_process").spawn;
var uuid = require("node-uuid");
var logging = require("femto-logger");
var config = require("../config/config");

var services = null;

var TEMPLATE = {
  detail: {
    header: {
      id: "",
      name: null,
      cwd: null,
      cmdline: null,
      running: false,
    },
    output: null
  },
  process: null
};

var list = exports.list = function(callback) {
  load(function(err, items) {
    if(!err) {
      var headers = [];

      for(key in items) {
        headers.push(items[key].detail.header);
      }

      callback(null, headers);
    }
    else {
      callback(err);
    }
  });
};

var detail = exports.detail = function(id, callback) {
  load(function(err, items) {
    if(!err) {
      callback(null, items[id] ? items[id].detail : null);
    }
    else {
      callback(err);
    }
  });
};

var service = exports.service = function(id, callback) {
  load(function(err, items) {
    if(!err) {
      callback(null, items[id]);
    }
    else {
      callback(err);
    }
  });
};

var create = exports.create = function(header, callback) {
  load(function(err, items) {
    if(!err) {
      var service = cx.clone(TEMPLATE);
      service.detail.header = header;
      service.detail.header.id = uuid.v1();
      service.detail.header.running = false;
      services[service.detail.header.id] = service;

      save(callback);
    }
    else {
      callback(err);
    }
  });
};

var update = exports.update = function(id, header, callback) {
  load(function(err, items) {
    if(!err) {
      header.running = items[id].detail.header.running;
      items[id].detail.header = header;
      save(callback);
    }
    else {
      callback(err);
    }
  });
};

var remove = exports.remove = function(id, callback) {
  load(function(err, items) {
    if(!err) {
      if(items[id].detail.header.running) {
        stop(id);
      }

      delete items[id];
      save(callback);
    }
    else {
      callback(err);
    }
  });
};

var start = exports.start = function(id, callback) {
  service(id, function(err, service) {
    if(!err) {
      if(service != null) {
        var split = service.detail.header.cmdline.split(" ");
        var cmd = split[0];
        var args = split.slice(1);

        service.detail.output = "";

        service.process = spawn(cmd, args, {cwd: service.detail.header.cwd});

        service.process.stdout.on("data", function(data) {
          service.detail.output += replaceAll(data.toString(), "\n", "
");
        });

        service.process.stderr.on("data", function(data) {
          service.detail.output += replaceAll(data.toString(), "\n", "
");
        });

        service.process.on("error", function(err) {
          service.detail.output += ("
" + err);
          service.detail.header.running = false;
        });

        service.process.on("exit", function(code) {
          service.detail.output += ("
Process exited with code " + code);
          service.detail.header.running = false;
        });

        service.detail.header.running = true;
        callback(null, service);
      }
      else {
        callback(null, null);
      }
    }
    else {
      callback(err);
    }
  });
}

var stop = exports.stop = function(id, callback) {
  service(id, function(err, service) {
    if(!err) {
      if(service != null) {
        if(service.process) {
          service.process.kill();
        }
        service.detail.header.running = false;
        callback(null, service);
      }
      else {
        callback(null, null);
      }
    }
    else {
      callback(err);
    }
  });
}

function load(callback) {
  if(services === null) {
    fs.readFile(config.datafile, function(err, data) {
      if(!err) {
        services = {};

        var headers = JSON.parse(data);
        for(var i=0; i < headers.length; i++) {
          var service = cx.clone(TEMPLATE);
          service.detail.header = headers[i];
          service.detail.header.running = false;
          services[service.detail.header.id] = service;
        }

        callback(null, services);
      }
      else {
        callback(err);
      }
    });
  }
  else {
    callback(null, services);
  }
}

function save(callback) {
  var headers = [];

  for(id in services) {
    var header = cx.clone(services[id].detail.header);
    delete header.running;
    headers.push(header);
  }

  fs.writeFile(config.datafile, JSON.stringify(headers), callback);
}

function replaceAll(s, find, replace) {
  return s.split(find).join(replace);
}
<commit_msg>Fixed issue when service.json doesnt already exist<commit_after>var fs = require("fs");
var cx = require("cloneextend");
var spawn = require("child_process").spawn;
var uuid = require("node-uuid");
var logging = require("femto-logger");
var config = require("../config/config");

var services = null;

var TEMPLATE = {
  detail: {
    header: {
      id: "",
      name: null,
      cwd: null,
      cmdline: null,
      running: false,
    },
    output: null
  },
  process: null
};

var list = exports.list = function(callback) {
  load(function(err, items) {
    if(!err) {
      var headers = [];

      for(key in items) {
        headers.push(items[key].detail.header);
      }

      callback(null, headers);
    }
    else {
      callback(err);
    }
  });
};

var detail = exports.detail = function(id, callback) {
  load(function(err, items) {
    if(!err) {
      callback(null, items[id] ? items[id].detail : null);
    }
    else {
      callback(err);
    }
  });
};

var service = exports.service = function(id, callback) {
  load(function(err, items) {
    if(!err) {
      callback(null, items[id]);
    }
    else {
      callback(err);
    }
  });
};

var create = exports.create = function(header, callback) {
  load(function(err, items) {
    if(!err) {
      var service = cx.clone(TEMPLATE);
      service.detail.header = header;
      service.detail.header.id = uuid.v1();
      service.detail.header.running = false;
      services[service.detail.header.id] = service;

      save(callback);
    }
    else {
      callback(err);
    }
  });
};

var update = exports.update = function(id, header, callback) {
  load(function(err, items) {
    if(!err) {
      header.running = items[id].detail.header.running;
      items[id].detail.header = header;
      save(callback);
    }
    else {
      callback(err);
    }
  });
};

var remove = exports.remove = function(id, callback) {
  load(function(err, items) {
    if(!err) {
      if(items[id].detail.header.running) {
        stop(id);
      }

      delete items[id];
      save(callback);
    }
    else {
      callback(err);
    }
  });
};

var start = exports.start = function(id, callback) {
  service(id, function(err, service) {
    if(!err) {
      if(service != null) {
        var split = service.detail.header.cmdline.split(" ");
        var cmd = split[0];
        var args = split.slice(1);

        service.detail.output = "";

        service.process = spawn(cmd, args, {cwd: service.detail.header.cwd});

        service.process.stdout.on("data", function(data) {
          service.detail.output += replaceAll(data.toString(), "\n", "
");
        });

        service.process.stderr.on("data", function(data) {
          service.detail.output += replaceAll(data.toString(), "\n", "
");
        });

        service.process.on("error", function(err) {
          service.detail.output += ("
" + err);
          service.detail.header.running = false;
        });

        service.process.on("exit", function(code) {
          service.detail.output += ("
Process exited with code " + code);
          service.detail.header.running = false;
        });

        service.detail.header.running = true;
        callback(null, service);
      }
      else {
        callback(null, null);
      }
    }
    else {
      callback(err);
    }
  });
}

var stop = exports.stop = function(id, callback) {
  service(id, function(err, service) {
    if(!err) {
      if(service != null) {
        if(service.process) {
          service.process.kill();
        }
        service.detail.header.running = false;
        callback(null, service);
      }
      else {
        callback(null, null);
      }
    }
    else {
      callback(err);
    }
  });
}

function load(callback) {
  if(services === null) {
    services = {};
    fs.readFile(config.datafile, function(err, data) {
      if(!err) {

        var headers = JSON.parse(data);
        for(var i=0; i < headers.length; i++) {
          var service = cx.clone(TEMPLATE);
          service.detail.header = headers[i];
          service.detail.header.running = false;
          services[service.detail.header.id] = service;
        }

        callback(null, services);
      }
      else {
        if(err.code !== 'ENOENT') {
          callback(err);
        }
      }
    });
  }
  else {
    callback(null, services);
  }
}

function save(callback) {
  var headers = [];

  for(id in services) {
    var header = cx.clone(services[id].detail.header);
    delete header.running;
    headers.push(header);
  }

  fs.writeFile(config.datafile, JSON.stringify(headers), callback);
}

function replaceAll(s, find, replace) {
  return s.split(find).join(replace);
}
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// for license information please see license.txt

frappe.provide("frappe.form.formatters");

frappe.form.link_formatters = {};

frappe.form.formatters = {
	_right: function(value, options) {
		if(options && (options.inline || options.only_value)) {
			return value;
		} else {
			return "
" + value + "
";
		}
	},
	Data: function(value) {
		return value==null ? "" : value;
	},
	Select: function(value) {
		return __(frappe.form.formatters["Data"](value));
	},
	Float: function(value, docfield, options, doc) {
		// don't allow 0 precision for Floats, hence or'ing with null
		var precision = docfield.precision
			|| cint(frappe.boot.sysdefaults && frappe.boot.sysdefaults.float_precision)
			|| null;
		if (docfield.options && docfield.options.trim()) {
			// options points to a currency field, but expects precision of float!
			docfield.precision = precision;
			return frappe.form.formatters.Currency(value, docfield, options, doc);

		} else {
			// show 1.000000 as 1
			if (!(options || {}).always_show_decimals && !is_null(value)) {
				var temp = cstr(value).split(".");
				if (temp[1]==undefined || cint(temp[1])===0) {
					precision = 0;
				}
			}

			return frappe.form.formatters._right(
				((value==null || value==="")
					? ""
					: format_number(value, null, precision)), options);
		}
	},
	Int: function(value, docfield, options) {
		return frappe.form.formatters._right(value==null ? "" : cint(value), options)
	},
	Percent: function(value, docfield, options) {
		const precision = (
			docfield.precision
			|| cint(
				frappe.boot.sysdefaults
				&& frappe.boot.sysdefaults.float_precision
			)
			|| 2
		);
		return frappe.form.formatters._right(flt(value, precision) + "%", options);
	},
	Rating: function(value) {
		const rating_html =	`${[1, 2, 3, 4, 5].map(i =>
			`<svg class="icon icon-md ${i <= (value || 0) ? "star-click": "" }" data-idx="${i}">
				<use href="#icon-star"></use>
			</svg>`
		).join('')}`;
		return `

			${rating_html}

`;
	},
	Currency: function (value, docfield, options, doc) {
		var currency  = frappe.meta.get_field_currency(docfield, doc);
		var precision = docfield.precision || cint(frappe.boot.sysdefaults.currency_precision) || 2;

		// If you change anything below, it's going to hurt a company in UAE, a bit.
		if (precision > 2) {
			var parts	 = cstr(value).split("."); // should be minimum 2, comes from the DB
			var decimals = parts.length > 1 ? parts[1] : ""; // parts.length == 2 ???

			if ( decimals.length < 3 || decimals.length < precision ) {
				const fraction = frappe.model.get_value(":Currency", currency, "fraction_units") || 100; // if not set, minimum 2.

				if (decimals.length < cstr(fraction).length) {
					precision = cstr(fraction).length - 1;
				}
			}
		}

		value = (value == null || value === "") ? "" : format_currency(value, currency, precision);

		if ( options && options.only_value ) {
			return value;
		} else {
			return frappe.form.formatters._right(value, options);
		}
	},
	Check: function(value) {
		if (value) {
			return `<input type="checkbox" class="disabled-selected">`;
		} else {
			return `<input type="checkbox" class="disabled-deselected">`;
		}
	},
	Link: function(value, docfield, options, doc) {
		var doctype = docfield._options || docfield.options;
		var original_value = value;
		if(value && value.match && value.match(/^['"].*['"]$/)) {
			value.replace(/^.(.*).$/, "$1");
		}

		if(options && (options.for_print || options.only_value)) {
			return value;
		}

		if(frappe.form.link_formatters[doctype]) {
			// don't apply formatters in case of composite (parent field of same type)
			if (doc && doctype !== doc.doctype) {
				value = frappe.form.link_formatters[doctype](value, doc, docfield);
			}
		}

		if(!value) {
			return "";
		}
		if(value[0] == "'" && value[value.length -1] == "'") {
			return value.substring(1, value.length - 1);
		}
		if(docfield && docfield.link_onclick) {
			return repl('%(value)s',
				{onclick: docfield.link_onclick.replace(/"/g, '"'), value:value});
		} else if(docfield && doctype) {
			if (!frappe.model.can_select(doctype) && frappe.model.can_read(doctype)) {
				return `
					${__(options && options.label || value)}`;
			} else {
				return value;
			}
		} else {
			return value;
		}
	},
	Date: function(value) {
		if (!frappe.datetime.str_to_user) {
			return value;
		}
		if (value) {
			value = frappe.datetime.str_to_user(value);
			// handle invalid date
			if (value==="Invalid date") {
				value = null;
			}
		}

		return value || "";
	},
	DateRange: function(value) {
		if($.isArray(value)) {
			return __("{0} to {1}", [frappe.datetime.str_to_user(value[0]), frappe.datetime.str_to_user(value[1])]);
		} else {
			return value || "";
		}
	},
	Datetime: function(value) {
		if(value) {
			var m = moment(frappe.datetime.convert_to_user_tz(value));
			if(frappe.boot.sysdefaults.time_zone) {
				m = m.tz(frappe.boot.sysdefaults.time_zone);
			}
			return m.format(frappe.boot.sysdefaults.date_format.toUpperCase()
				+  ' ' + frappe.boot.sysdefaults.time_format);
		} else {
			return "";
		}
	},
	Text: function(value) {
		if(value) {
			var tags = ["<p", "<div", "<br", "<table"];
			var match = false;

			for(var i=0; i<tags.length; i++) {
				if(value.match(tags[i])) {
					match = true;
					break;
				}
			}

			if(!match) {
				value = frappe.utils.replace_newlines(value);
			}
		}

		return frappe.form.formatters.Data(value);
	},
	Time: function(value) {
		if (value) {
			value = frappe.datetime.str_to_user(value, true);
		}

		return value || "";
	},
	Duration: function(value, docfield) {
		if (value) {
			let duration_options = frappe.utils.get_duration_options(docfield);
			value = frappe.utils.get_formatted_duration(value, duration_options);
		}

		return value || "";
	},
	LikedBy: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= frappe.avatar(v);
		});
		return html;
	},
	Tag: function(value) {
		var html = "";
		$.each((value || "").split(","), function(i, v) {
			if(v) html+= ''+v +'';
		});
		return html;
	},
	Comment: function(value) {
		return value;
	},
	Assign: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v+'';
		});
		return html;
	},
	SmallText: function(value) {
		return frappe.form.formatters.Text(value);
	},
	TextEditor: function(value) {
		let formatted_value = frappe.form.formatters.Text(value);
		// to use ql-editor styles
		try {
			if (!$(formatted_value).find('.ql-editor').length) {
				formatted_value = `<div class="ql-editor read-mode">${formatted_value}</div>`;
			}
		} catch(e) {
			formatted_value = `<div class="ql-editor read-mode">${formatted_value}</div>`;
		}

		return formatted_value;
	},
	Code: function(value) {
		return "
" + (value==null ? "" : $("
").text(value).html()) + "
"
	},
	WorkflowState: function(value) {
		var workflow_state = frappe.get_doc("Workflow State", value);
		if(workflow_state) {
			return repl("\
				 %(value)s", {
					value: value,
					style: workflow_state.style.toLowerCase(),
					icon: workflow_state.icon
				});
		} else {
			return "" + value + "";
		}
	},
	Email: function(value) {
		return $("

").text(value).html();
	},
	FileSize: function(value) {
		if(value > 1048576) {
			value = flt(flt(value) / 1048576, 1) + "M";
		} else if (value > 1024) {
			value = flt(flt(value) / 1024, 1) + "K";
		}
		return value;
	},
	TableMultiSelect: function(rows, df, options) {
		rows = rows || [];
		const meta = frappe.get_meta(df.options);
		const link_field = meta.fields.find(df => df.fieldtype === 'Link');
		const formatted_values = rows.map(row => {
			const value = row[link_field.fieldname];
			return frappe.format(value, link_field, options, row);
		});
		return formatted_values.join(', ');
	}
}

frappe.form.get_formatter = function(fieldtype) {
	if(!fieldtype)
		fieldtype = "Data";
	return frappe.form.formatters[fieldtype.replace(/ /g, "")] || frappe.form.formatters.Data;
}

frappe.format = function(value, df, options, doc) {
	if(!df) df = {"fieldtype":"Data"};
	var fieldtype = df.fieldtype || "Data";

	// format Dynamic Link as a Link
	if(fieldtype==="Dynamic Link") {
		fieldtype = "Link";
		df._options = doc ? doc[df.options] : null;
	}

	var formatter = df.formatter || frappe.form.get_formatter(fieldtype);

	var formatted = formatter(value, df, options, doc);

	if (typeof formatted == "string")
		formatted = frappe.dom.remove_script_and_style(formatted);

	return formatted;
};

frappe.get_format_helper = function(doc) {
	var helper = {
		get_formatted: function(fieldname) {
			var df = frappe.meta.get_docfield(doc.doctype, fieldname);
			if(!df) { console.log("fieldname not found: " + fieldname); }
			return frappe.format(doc[fieldname], df, {inline:1}, doc);
		}
	};
	$.extend(helper, doc);
	return helper;
};

frappe.form.link_formatters['User'] = function(value, doc, docfield) {
	let full_name = doc && (doc.full_name || (docfield && doc[`${docfield.fieldname}_full_name`]));
	return full_name || value;
};
<commit_msg>fix: show link based on READ ignoring select perm (#12521)<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

// for license information please see license.txt

frappe.provide("frappe.form.formatters");

frappe.form.link_formatters = {};

frappe.form.formatters = {
	_right: function(value, options) {
		if(options && (options.inline || options.only_value)) {
			return value;
		} else {
			return "
" + value + "
";
		}
	},
	Data: function(value) {
		return value==null ? "" : value;
	},
	Select: function(value) {
		return __(frappe.form.formatters["Data"](value));
	},
	Float: function(value, docfield, options, doc) {
		// don't allow 0 precision for Floats, hence or'ing with null
		var precision = docfield.precision
			|| cint(frappe.boot.sysdefaults && frappe.boot.sysdefaults.float_precision)
			|| null;
		if (docfield.options && docfield.options.trim()) {
			// options points to a currency field, but expects precision of float!
			docfield.precision = precision;
			return frappe.form.formatters.Currency(value, docfield, options, doc);

		} else {
			// show 1.000000 as 1
			if (!(options || {}).always_show_decimals && !is_null(value)) {
				var temp = cstr(value).split(".");
				if (temp[1]==undefined || cint(temp[1])===0) {
					precision = 0;
				}
			}

			return frappe.form.formatters._right(
				((value==null || value==="")
					? ""
					: format_number(value, null, precision)), options);
		}
	},
	Int: function(value, docfield, options) {
		return frappe.form.formatters._right(value==null ? "" : cint(value), options)
	},
	Percent: function(value, docfield, options) {
		const precision = (
			docfield.precision
			|| cint(
				frappe.boot.sysdefaults
				&& frappe.boot.sysdefaults.float_precision
			)
			|| 2
		);
		return frappe.form.formatters._right(flt(value, precision) + "%", options);
	},
	Rating: function(value) {
		const rating_html =	`${[1, 2, 3, 4, 5].map(i =>
			`<svg class="icon icon-md ${i <= (value || 0) ? "star-click": "" }" data-idx="${i}">
				<use href="#icon-star"></use>
			</svg>`
		).join('')}`;
		return `

			${rating_html}

`;
	},
	Currency: function (value, docfield, options, doc) {
		var currency  = frappe.meta.get_field_currency(docfield, doc);
		var precision = docfield.precision || cint(frappe.boot.sysdefaults.currency_precision) || 2;

		// If you change anything below, it's going to hurt a company in UAE, a bit.
		if (precision > 2) {
			var parts	 = cstr(value).split("."); // should be minimum 2, comes from the DB
			var decimals = parts.length > 1 ? parts[1] : ""; // parts.length == 2 ???

			if ( decimals.length < 3 || decimals.length < precision ) {
				const fraction = frappe.model.get_value(":Currency", currency, "fraction_units") || 100; // if not set, minimum 2.

				if (decimals.length < cstr(fraction).length) {
					precision = cstr(fraction).length - 1;
				}
			}
		}

		value = (value == null || value === "") ? "" : format_currency(value, currency, precision);

		if ( options && options.only_value ) {
			return value;
		} else {
			return frappe.form.formatters._right(value, options);
		}
	},
	Check: function(value) {
		if (value) {
			return `<input type="checkbox" class="disabled-selected">`;
		} else {
			return `<input type="checkbox" class="disabled-deselected">`;
		}
	},
	Link: function(value, docfield, options, doc) {
		var doctype = docfield._options || docfield.options;
		var original_value = value;
		if(value && value.match && value.match(/^['"].*['"]$/)) {
			value.replace(/^.(.*).$/, "$1");
		}

		if(options && (options.for_print || options.only_value)) {
			return value;
		}

		if(frappe.form.link_formatters[doctype]) {
			// don't apply formatters in case of composite (parent field of same type)
			if (doc && doctype !== doc.doctype) {
				value = frappe.form.link_formatters[doctype](value, doc, docfield);
			}
		}

		if(!value) {
			return "";
		}
		if(value[0] == "'" && value[value.length -1] == "'") {
			return value.substring(1, value.length - 1);
		}
		if(docfield && docfield.link_onclick) {
			return repl('%(value)s',
				{onclick: docfield.link_onclick.replace(/"/g, '"'), value:value});
		} else if(docfield && doctype) {
			if (frappe.model.can_read(doctype)) {
				return `
					${__(options && options.label || value)}`;
			} else {
				return value;
			}
		} else {
			return value;
		}
	},
	Date: function(value) {
		if (!frappe.datetime.str_to_user) {
			return value;
		}
		if (value) {
			value = frappe.datetime.str_to_user(value);
			// handle invalid date
			if (value==="Invalid date") {
				value = null;
			}
		}

		return value || "";
	},
	DateRange: function(value) {
		if($.isArray(value)) {
			return __("{0} to {1}", [frappe.datetime.str_to_user(value[0]), frappe.datetime.str_to_user(value[1])]);
		} else {
			return value || "";
		}
	},
	Datetime: function(value) {
		if(value) {
			var m = moment(frappe.datetime.convert_to_user_tz(value));
			if(frappe.boot.sysdefaults.time_zone) {
				m = m.tz(frappe.boot.sysdefaults.time_zone);
			}
			return m.format(frappe.boot.sysdefaults.date_format.toUpperCase()
				+  ' ' + frappe.boot.sysdefaults.time_format);
		} else {
			return "";
		}
	},
	Text: function(value) {
		if(value) {
			var tags = ["<p", "<div", "<br", "<table"];
			var match = false;

			for(var i=0; i<tags.length; i++) {
				if(value.match(tags[i])) {
					match = true;
					break;
				}
			}

			if(!match) {
				value = frappe.utils.replace_newlines(value);
			}
		}

		return frappe.form.formatters.Data(value);
	},
	Time: function(value) {
		if (value) {
			value = frappe.datetime.str_to_user(value, true);
		}

		return value || "";
	},
	Duration: function(value, docfield) {
		if (value) {
			let duration_options = frappe.utils.get_duration_options(docfield);
			value = frappe.utils.get_formatted_duration(value, duration_options);
		}

		return value || "";
	},
	LikedBy: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= frappe.avatar(v);
		});
		return html;
	},
	Tag: function(value) {
		var html = "";
		$.each((value || "").split(","), function(i, v) {
			if(v) html+= ''+v +'';
		});
		return html;
	},
	Comment: function(value) {
		return value;
	},
	Assign: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v+'';
		});
		return html;
	},
	SmallText: function(value) {
		return frappe.form.formatters.Text(value);
	},
	TextEditor: function(value) {
		let formatted_value = frappe.form.formatters.Text(value);
		// to use ql-editor styles
		try {
			if (!$(formatted_value).find('.ql-editor').length) {
				formatted_value = `<div class="ql-editor read-mode">${formatted_value}</div>`;
			}
		} catch(e) {
			formatted_value = `<div class="ql-editor read-mode">${formatted_value}</div>`;
		}

		return formatted_value;
	},
	Code: function(value) {
		return "
" + (value==null ? "" : $("
").text(value).html()) + "
"
	},
	WorkflowState: function(value) {
		var workflow_state = frappe.get_doc("Workflow State", value);
		if(workflow_state) {
			return repl("\
				 %(value)s", {
					value: value,
					style: workflow_state.style.toLowerCase(),
					icon: workflow_state.icon
				});
		} else {
			return "" + value + "";
		}
	},
	Email: function(value) {
		return $("

").text(value).html();
	},
	FileSize: function(value) {
		if(value > 1048576) {
			value = flt(flt(value) / 1048576, 1) + "M";
		} else if (value > 1024) {
			value = flt(flt(value) / 1024, 1) + "K";
		}
		return value;
	},
	TableMultiSelect: function(rows, df, options) {
		rows = rows || [];
		const meta = frappe.get_meta(df.options);
		const link_field = meta.fields.find(df => df.fieldtype === 'Link');
		const formatted_values = rows.map(row => {
			const value = row[link_field.fieldname];
			return frappe.format(value, link_field, options, row);
		});
		return formatted_values.join(', ');
	}
}

frappe.form.get_formatter = function(fieldtype) {
	if(!fieldtype)
		fieldtype = "Data";
	return frappe.form.formatters[fieldtype.replace(/ /g, "")] || frappe.form.formatters.Data;
}

frappe.format = function(value, df, options, doc) {
	if(!df) df = {"fieldtype":"Data"};
	var fieldtype = df.fieldtype || "Data";

	// format Dynamic Link as a Link
	if(fieldtype==="Dynamic Link") {
		fieldtype = "Link";
		df._options = doc ? doc[df.options] : null;
	}

	var formatter = df.formatter || frappe.form.get_formatter(fieldtype);

	var formatted = formatter(value, df, options, doc);

	if (typeof formatted == "string")
		formatted = frappe.dom.remove_script_and_style(formatted);

	return formatted;
};

frappe.get_format_helper = function(doc) {
	var helper = {
		get_formatted: function(fieldname) {
			var df = frappe.meta.get_docfield(doc.doctype, fieldname);
			if(!df) { console.log("fieldname not found: " + fieldname); }
			return frappe.format(doc[fieldname], df, {inline:1}, doc);
		}
	};
	$.extend(helper, doc);
	return helper;
};

frappe.form.link_formatters['User'] = function(value, doc, docfield) {
	let full_name = doc && (doc.full_name || (docfield && doc[`${docfield.fieldname}_full_name`]));
	return full_name || value;
};
<|endoftext|>


<commit_before>'use strict';
var P = require('bluebird');
var flat = require('flat');
var _ = require('lodash');

module.exports = function (model) {
  var fields = [];
  var paths = flat.unflatten(model.schema.paths);

  function objectType(object, getType) {
    var type = { fields: [] };

    Object.keys(object).forEach(function (key) {
      type.fields.push({
        field: key,
        type: getType(key)
      });
    });

    return type;
  }

  function getTypeFromNative(type) {
    if (type instanceof Array) {
      return [getTypeFromNative(type[0])];
    } else if (_.isPlainObject(type)) {
      return objectType(type, function (key) {
        return getTypeFromNative(type[key]);
      });
    } else if (_.isFunction(type) && type.name === 'ObjectId') {
      return 'String';
    }

    switch (type) {
      case String:
        return 'String';
      case Boolean:
        return 'Boolean';
      case Number:
        return 'Number';
      case Date:
        return 'Date';
    }
  }

  function getTypeFromMongoose(opts) {
    if (_.isPlainObject(opts) && !opts.path) {
      // Deal with Object
      return objectType(opts, function (key) {
        return getTypeFromMongoose(opts[key]);
      });
    } else if (opts.instance === 'Array') {
      // Deal with Array
      if (opts.caster.instance) {
        return [getTypeFromMongoose(opts.caster)];
      } else {
        return [objectType(opts.options.type[0], function (key) {
          return getTypeFromNative(opts.options.type[0][key]);
        })];
      }
    } else {
      // Deal with ObjectID
      if (opts.instance === 'ObjectID') { return 'String'; }

      // Deal with primitive type
      return opts.instance || getTypeFromNative(opts.options.type);
    }
  }

  function detectReference(opts) {
    if (opts.options) {
      if (opts.options.ref) {
        return opts.options.ref + '._id' ;
      } else if (_.isArray(opts.options.type) && opts.options.type.length &&
        opts.options.type[0].ref) {
        return opts.options.type[0].ref + '._id';
      }
    }
  }

  function detectRequireFlag(opts) {
   return !!opts.isRequired;
  }

  function getSchema(path) {
    var opts = paths[path];

    var schema = {
      field: path,
      type: getTypeFromMongoose(paths[path]),
      isRequired: !!detectRequireFlag(opts)
    };

    var ref = detectReference(opts);
    if (ref) { schema.ref = ref; }

    if (opts.enumValues && opts.enumValues.length) {
      schema.enumValues = opts.enumValues;
    }

    return schema;
  }

  return P
    .each(Object.keys(paths), function (path) {
      var schema = getSchema(path);
      schema.collectionName = model.collection.name;
      fields.push(schema);
    })
    .then(function () {
      return { name: model.collection.name, fields: fields };
    });
};

<commit_msg>Remove the collectionName from all fields<commit_after>'use strict';
var P = require('bluebird');
var flat = require('flat');
var _ = require('lodash');

module.exports = function (model) {
  var fields = [];
  var paths = flat.unflatten(model.schema.paths);

  function objectType(object, getType) {
    var type = { fields: [] };

    Object.keys(object).forEach(function (key) {
      type.fields.push({
        field: key,
        type: getType(key)
      });
    });

    return type;
  }

  function getTypeFromNative(type) {
    if (type instanceof Array) {
      return [getTypeFromNative(type[0])];
    } else if (_.isPlainObject(type)) {
      return objectType(type, function (key) {
        return getTypeFromNative(type[key]);
      });
    } else if (_.isFunction(type) && type.name === 'ObjectId') {
      return 'String';
    }

    switch (type) {
      case String:
        return 'String';
      case Boolean:
        return 'Boolean';
      case Number:
        return 'Number';
      case Date:
        return 'Date';
    }
  }

  function getTypeFromMongoose(opts) {
    if (_.isPlainObject(opts) && !opts.path) {
      // Deal with Object
      return objectType(opts, function (key) {
        return getTypeFromMongoose(opts[key]);
      });
    } else if (opts.instance === 'Array') {
      // Deal with Array
      if (opts.caster.instance) {
        return [getTypeFromMongoose(opts.caster)];
      } else {
        return [objectType(opts.options.type[0], function (key) {
          return getTypeFromNative(opts.options.type[0][key]);
        })];
      }
    } else {
      // Deal with ObjectID
      if (opts.instance === 'ObjectID') { return 'String'; }

      // Deal with primitive type
      return opts.instance || getTypeFromNative(opts.options.type);
    }
  }

  function detectReference(opts) {
    if (opts.options) {
      if (opts.options.ref) {
        return opts.options.ref + '._id' ;
      } else if (_.isArray(opts.options.type) && opts.options.type.length &&
        opts.options.type[0].ref) {
        return opts.options.type[0].ref + '._id';
      }
    }
  }

  function detectRequireFlag(opts) {
   return !!opts.isRequired;
  }

  function getSchema(path) {
    var opts = paths[path];

    var schema = {
      field: path,
      type: getTypeFromMongoose(paths[path]),
      isRequired: !!detectRequireFlag(opts)
    };

    var ref = detectReference(opts);
    if (ref) { schema.ref = ref; }

    if (opts.enumValues && opts.enumValues.length) {
      schema.enumValues = opts.enumValues;
    }

    return schema;
  }

  return P
    .each(Object.keys(paths), function (path) {
      var schema = getSchema(path);
      fields.push(schema);
    })
    .then(function () {
      return { name: model.collection.name, fields: fields };
    });
};

<|endoftext|>


<commit_before>import React from 'react'
import {goto} from 'app/utils/store'

require('sass/sidebar.sass')

const blogo = require('imgs/logo.svg')
const powered_by_serverboards = require('imgs/logo.svg')

function goto_or_new_tab(ev, path){
  if (ev.button == 0){
    ev.preventDefault()
    goto(path)
  }
}

function Item(props){
  return (
    <a
      className={`ui ${props.selected ? "selected" : ""} item`}
      href={`#${props.goto}`}
      onClick={ (ev) => goto_or_new_tab(ev, props.goto) }
      >
      {props.label}

  )
}

function Sidebar(props){
  const pathname = props.pathname
  return (

           {ev.preventDefault(); props.onToggleSidebar()}}>

URL header

        {props.sections.project.map( s => (
          <Item key={s.id} label={s.label} selected={s.goto == pathname} goto={s.goto}/>
        ))}

        {props.sections.global.map( s => (
          <Item key={s.id} label={s.label} selected={s.goto == pathname} goto={s.goto}/>
        ))}

        <a
           className={`ui ${props.section == 'profile' ? "selected" : ""} item`}
           href="#_" style={{padding: "0 0 0 16px"}}
           onClick={(ev) => {ev.preventDefault(); goto("/user/profile")}}>

              {props.user.name}

        {props.sections.settings.map( s => (
          <Item key={s.id} label={s.label} selected={s.goto == pathname} goto={s.goto}/>
        ))}

  )
}

export default Sidebar
<commit_msg>Fix when loading and no user data yet<commit_after>import React from 'react'
import {goto} from 'app/utils/store'

require('sass/sidebar.sass')

const blogo = require('imgs/logo.svg')
const powered_by_serverboards = require('imgs/logo.svg')

function goto_or_new_tab(ev, path){
  if (ev.button == 0){
    ev.preventDefault()
    goto(path)
  }
}

function Item(props){
  return (
    <a
      className={`ui ${props.selected ? "selected" : ""} item`}
      href={`#${props.goto}`}
      onClick={ (ev) => goto_or_new_tab(ev, props.goto) }
      >
      {props.label}

  )
}

function Sidebar(props){
  const pathname = props.pathname
  return (

           {ev.preventDefault(); props.onToggleSidebar()}}>

URL header

        {props.sections.project.map( s => (
          <Item key={s.id} label={s.label} selected={s.goto == pathname} goto={s.goto}/>
        ))}

        {props.sections.global.map( s => (
          <Item key={s.id} label={s.label} selected={s.goto == pathname} goto={s.goto}/>
        ))}

        <a
           className={`ui ${props.section == 'profile' ? "selected" : ""} item`}
           href="#_" style={{padding: "0 0 0 16px"}}
           onClick={(ev) => {ev.preventDefault(); goto("/user/profile")}}>

              {props.user && props.user.name}

        {props.sections.settings.map( s => (
          <Item key={s.id} label={s.label} selected={s.goto == pathname} goto={s.goto}/>
        ))}

  )
}

export default Sidebar
<|endoftext|>


<commit_before>/**
 * Example: inputPlaceholder( document.getElementById('my_input_element') )
 * @param {Element} input
 * @param {String} color
 * @return {Element} input
 */
function inputPlaceholder (input, color) {

  if (!input) return null;

  /**
   * Webkit browsers already implemented placeholder attribute.
   * This function useless for them.
   */
  if (input.placeholder && 'placeholder' in document.createElement(input.tagName)) return input;

  var placeholder_color = color || '#AAA';
  var default_color = input.style.color;
  var placeholder = input.getAttribute('placeholder');

  if (input.value === '' || input.value == placeholder) {
    input.value = placeholder;
    input.style.color = placeholder_color;
  }

  var add_event = /*@cc_on'attachEvent'||@*/'addEventListener';

  input[add_event](/*@cc_on'on'+@*/'focus', function(){
    input.style.color = default_color;
    if (input.value == placeholder) {
      input.value = '';
    }
  }, false);

  input[add_event](/*@cc_on'on'+@*/'blur', function(){
    if (input.value === '') {
      input.value = placeholder;
      input.style.color = placeholder_color;
    } else {
      input.style.color = default_color;
    }
  }, false);

  input.form && input.form[add_event](/*@cc_on'on'+@*/'submit', function(){
    if (input.value == placeholder) {
      input.value = '';
    }
  }, false);

  return input;
}
<commit_msg>Firefox 3.7 supports placeholder. No need for placeholder_color variable.<commit_after>/**
 * Example: inputPlaceholder( document.getElementById('my_input_element') )
 * @param {Element} input
 * @param {String} color
 * @return {Element} input
 */
function inputPlaceholder (input, color) {

  if (!input) return null;

  // Do nothing if placeholder supported by browser (Webkit, Firefox 3.7)
  if (input.placeholder && 'placeholder' in document.createElement(input.tagName)) return input;

  color = color || '#AAA';
  var default_color = input.style.color;
  var placeholder = input.getAttribute('placeholder');

  if (input.value === '' || input.value == placeholder) {
    input.value = placeholder;
    input.style.color = color;
  }

  var add_event = /*@cc_on'attachEvent'||@*/'addEventListener';

  input[add_event](/*@cc_on'on'+@*/'focus', function(){
    input.style.color = default_color;
    if (input.value == placeholder) {
      input.value = '';
    }
  }, false);

  input[add_event](/*@cc_on'on'+@*/'blur', function(){
    if (input.value === '') {
      input.value = placeholder;
      input.style.color = color;
    } else {
      input.style.color = default_color;
    }
  }, false);

  input.form && input.form[add_event](/*@cc_on'on'+@*/'submit', function(){
    if (input.value == placeholder) {
      input.value = '';
    }
  }, false);

  return input;
}
<|endoftext|>


<commit_before>var config = require('./config');
var zlib = require('zlib');
var compute = require('./compute');
var computePlayerMatchData = compute.computePlayerMatchData;
var aggregator = require('./aggregator');
var async = require('async');
var constants = require('./constants');
var utility = require('./utility');
var serialize = utility.serialize;
var filter = require('./filter');
var util = require('util');
var reduceAggregable = utility.reduceAggregable;
var enabled = config.ENABLE_PLAYER_CACHE;
var cEnabled = config.ENABLE_CASSANDRA_PLAYER_CACHE;
var redis;
var cassandra;
if (enabled)
{
    redis = require('./redis');
    if (cEnabled)
    {
        cassandra = require('./cassandra');
    }
}

function readCache(account_id, options, cb)
{
    if (enabled)
    {
        if (cEnabled)
        {
            console.time('readcache');
            //TODO currently aggregator does live significance check.  Persist it to store so we can project fewer fields?
            var proj = ['account_id', 'match_id', 'player_slot', 'version', 'start_time', 'duration', 'game_mode', 'lobby_type', 'radiant_win'];
            var table = ['hero_id', 'player_win', 'game_mode', 'skill', 'duration', 'kills', 'deaths', 'assists', 'last_hits', 'gold_per_min', 'parse_status'];
            var query = util.format('SELECT %s FROM player_caches WHERE account_id = ?', Object.keys(options.js_agg).concat(proj).concat(table).join(','));
            var aggData = aggregator([], options.js_agg);
            return cassandra.stream(query, [account_id],
            {
                prepare: true,
                autoPage: true,
            }).on('readable', function()
            {
                //readable is emitted as soon a row is received and parsed
                var m;
                while (m = this.read())
                {
                    m.keys().forEach(function(key)
                    {
                        try
                        {
                            m[key] = JSON.parse(m[key]);
                        }
                        catch (e)
                        {
                            console.error(e, m[key]);
                        }
                    });
                    if (filter([m], options.js_select).length)
                    {
                        aggData = aggregator([m], options.js_agg, aggData);
                    }
                }
            }).on('end', function()
            {
                //stream ended, there aren't any more rows
                console.timeEnd('readcache');
                return cb(null,
                {
                    aggData: aggData
                });
            }).on('error', function(err)
            {
                //Something went wrong: err is a response error from Cassandra
                console.error(err);
                console.timeEnd('readcache');
                return cb(err);
            });
        }
        else
        {
            //console.time('readcache');
            redis.get(new Buffer("player:" + account_id), function(err, result)
            {
                var cache = result ? JSON.parse(zlib.inflateSync(result)) : null;
                //console.timeEnd('readcache');
                //console.log(result ? result.length : 0, JSON.stringify(cache).length);
                return cb(err, cache);
            });
        }
    }
    else
    {
        return cb();
    }
}

function writeCache(account_id, cache, cb)
{
    if (enabled)
    {
        if (cEnabled)
        {
            //console.time("writecache");
            //console.log("saving player cache to cassandra %s", account_id);
            var arr = cache.raw.map(function(m)
            {
                var agg = reduceAggregable(m);
                return serialize(agg);
            });
            //upsert matches into store
            return async.each(arr, function(m, cb)
            {
                var query = 'INSERT INTO player_caches JSON ?';
                cassandra.execute(query, [JSON.stringify(m)],
                {
                    prepare: true
                }, cb);
            }, function(err)
            {
                //console.timeEnd("writecache");
                return cb(err);
            });
        }
        else
        {
            console.time("writecache");
            console.log("saving player cache to redis %s", account_id);
            redis.ttl("player:" + account_id, function(err, ttl)
            {
                if (err)
                {
                    return cb(err);
                }
                cache = {
                    aggData: cache.aggData
                };
                redis.setex(new Buffer("player:" + account_id), Number(ttl) > 0 ? Number(ttl) : 24 * 60 * 60 * config.UNTRACK_DAYS, zlib.deflateSync(JSON.stringify(cache)), function(err)
                {
                    console.timeEnd("writecache");
                    cb(err);
                });
            });
        }
    }
    else
    {
        return cb();
    }
}

function updateCache(match, cb)
{
    if (enabled)
    {
        var players = match.players;
        if (match.pgroup && players)
        {
            players.forEach(function(p)
            {
                //add account id to each player so we know what caches to update
                p.account_id = match.pgroup[p.player_slot].account_id;
                //add hero_id to each player so we update records with hero played
                p.hero_id = match.pgroup[p.player_slot].hero_id;
            });
        }
        async.eachSeries(players, function(player_match, cb)
        {
            if (player_match.account_id && player_match.account_id !== constants.anonymous_account_id)
            {
                //join player with match to form player_match
                for (var key in match)
                {
                    player_match[key] = match[key];
                }
                computePlayerMatchData(player_match);
                if (cEnabled)
                {
                    writeCache(player_match.account_id,
                    {
                        raw: [player_match]
                    }, cb);
                }
                else
                {
                    readCache(player_match.account_id,
                    {}, function(err, cache)
                    {
                        if (err)
                        {
                            return cb(err);
                        }
                        //if player cache doesn't exist, skip
                        if (cache)
                        {
                            cache.aggData = aggregator([player_match], null, cache.aggData);
                            writeCache(player_match.account_id, cache, cb);
                        }
                        else
                        {
                            return cb();
                        }
                    });
                }
            }
            else
            {
                return cb();
            }
        }, cb);
    }
    else
    {
        return cb();
    }
}

function countPlayerCaches(cb)
{
    if (enabled)
    {
        redis.keys("player:*", function(err, result)
        {
            cb(err, result.length);
        });
    }
    else
    {
        return cb(null, 0);
    }
}
module.exports = {
    readCache: readCache,
    writeCache: writeCache,
    updateCache: updateCache,
    countPlayerCaches: countPlayerCaches,
};<commit_msg>throw cassandra errors<commit_after>var config = require('./config');
var zlib = require('zlib');
var compute = require('./compute');
var computePlayerMatchData = compute.computePlayerMatchData;
var aggregator = require('./aggregator');
var async = require('async');
var constants = require('./constants');
var utility = require('./utility');
var serialize = utility.serialize;
var filter = require('./filter');
var util = require('util');
var reduceAggregable = utility.reduceAggregable;
var enabled = config.ENABLE_PLAYER_CACHE;
var cEnabled = config.ENABLE_CASSANDRA_PLAYER_CACHE;
var redis;
var cassandra;
if (enabled)
{
    redis = require('./redis');
    if (cEnabled)
    {
        cassandra = require('./cassandra');
    }
}

function readCache(account_id, options, cb)
{
    if (enabled)
    {
        if (cEnabled)
        {
            console.time('readcache');
            //TODO currently aggregator does live significance check.  Persist it to store so we can project fewer fields?
            var proj = ['account_id', 'match_id', 'player_slot', 'version', 'start_time', 'duration', 'game_mode', 'lobby_type', 'radiant_win'];
            var table = ['hero_id', 'player_win', 'game_mode', 'skill', 'duration', 'kills', 'deaths', 'assists', 'last_hits', 'gold_per_min', 'parse_status'];
            var query = util.format('SELECT %s FROM player_caches WHERE account_id = ?', Object.keys(options.js_agg).concat(proj).concat(table).join(','));
            var aggData = aggregator([], options.js_agg);
            return cassandra.stream(query, [account_id],
            {
                prepare: true,
                autoPage: true,
            }).on('readable', function()
            {
                //readable is emitted as soon a row is received and parsed
                var m;
                while (m = this.read())
                {
                    m.keys().forEach(function(key)
                    {
                        try
                        {
                            m[key] = JSON.parse(m[key]);
                        }
                        catch (e)
                        {
                            console.error(e, m[key]);
                        }
                    });
                    if (filter([m], options.js_select).length)
                    {
                        aggData = aggregator([m], options.js_agg, aggData);
                    }
                }
            }).on('end', function()
            {
                //stream ended, there aren't any more rows
                console.timeEnd('readcache');
                return cb(null,
                {
                    aggData: aggData
                });
            }).on('error', function(err)
            {
                //Something went wrong: err is a response error from Cassandra
                throw err;
            });
        }
        else
        {
            //console.time('readcache');
            redis.get(new Buffer("player:" + account_id), function(err, result)
            {
                var cache = result ? JSON.parse(zlib.inflateSync(result)) : null;
                //console.timeEnd('readcache');
                //console.log(result ? result.length : 0, JSON.stringify(cache).length);
                return cb(err, cache);
            });
        }
    }
    else
    {
        return cb();
    }
}

function writeCache(account_id, cache, cb)
{
    if (enabled)
    {
        if (cEnabled)
        {
            //console.time("writecache");
            //console.log("saving player cache to cassandra %s", account_id);
            var arr = cache.raw.map(function(m)
            {
                var agg = reduceAggregable(m);
                return serialize(agg);
            });
            //upsert matches into store
            return async.each(arr, function(m, cb)
            {
                var query = 'INSERT INTO player_caches JSON ?';
                cassandra.execute(query, [JSON.stringify(m)],
                {
                    prepare: true
                }, cb);
            }, function(err)
            {
                //console.timeEnd("writecache");
                return cb(err);
            });
        }
        else
        {
            console.time("writecache");
            console.log("saving player cache to redis %s", account_id);
            redis.ttl("player:" + account_id, function(err, ttl)
            {
                if (err)
                {
                    return cb(err);
                }
                cache = {
                    aggData: cache.aggData
                };
                redis.setex(new Buffer("player:" + account_id), Number(ttl) > 0 ? Number(ttl) : 24 * 60 * 60 * config.UNTRACK_DAYS, zlib.deflateSync(JSON.stringify(cache)), function(err)
                {
                    console.timeEnd("writecache");
                    cb(err);
                });
            });
        }
    }
    else
    {
        return cb();
    }
}

function updateCache(match, cb)
{
    if (enabled)
    {
        var players = match.players;
        if (match.pgroup && players)
        {
            players.forEach(function(p)
            {
                //add account id to each player so we know what caches to update
                p.account_id = match.pgroup[p.player_slot].account_id;
                //add hero_id to each player so we update records with hero played
                p.hero_id = match.pgroup[p.player_slot].hero_id;
            });
        }
        async.eachSeries(players, function(player_match, cb)
        {
            if (player_match.account_id && player_match.account_id !== constants.anonymous_account_id)
            {
                //join player with match to form player_match
                for (var key in match)
                {
                    player_match[key] = match[key];
                }
                computePlayerMatchData(player_match);
                if (cEnabled)
                {
                    writeCache(player_match.account_id,
                    {
                        raw: [player_match]
                    }, cb);
                }
                else
                {
                    readCache(player_match.account_id,
                    {}, function(err, cache)
                    {
                        if (err)
                        {
                            return cb(err);
                        }
                        //if player cache doesn't exist, skip
                        if (cache)
                        {
                            cache.aggData = aggregator([player_match], null, cache.aggData);
                            writeCache(player_match.account_id, cache, cb);
                        }
                        else
                        {
                            return cb();
                        }
                    });
                }
            }
            else
            {
                return cb();
            }
        }, cb);
    }
    else
    {
        return cb();
    }
}

function countPlayerCaches(cb)
{
    if (enabled)
    {
        redis.keys("player:*", function(err, result)
        {
            cb(err, result.length);
        });
    }
    else
    {
        return cb(null, 0);
    }
}
module.exports = {
    readCache: readCache,
    writeCache: writeCache,
    updateCache: updateCache,
    countPlayerCaches: countPlayerCaches,
};<|endoftext|>


<commit_before>var ocargo = ocargo || {};

function createUi() {
    return new ocargo.SimpleUi();
}

function createDefaultLevel(nodeData, destination, decor, ui, maxFuel) {
	var nodes = createNodes(nodeData);
    var destinationIndex = findByCoordinate(destination, nodes);
    var dest = destinationIndex > -1 ? nodes[destinationIndex] : nodes[nodes.length - 1];
    var map = new ocargo.Map(nodes, decor, dest, ui);
    var van = new ocargo.Van(nodes[0], nodes[0].connectedNodes[0], maxFuel, ui);
    return new ocargo.Level(map, van, ui);
}

function createNodes(nodeData){
	var nodes = [];

    var i;
	// Create nodes with coords
	for(i = 0; i < nodeData.length; i++){
		 var coordinate = new ocargo.Coordinate(nodeData[i]['coordinate'][0], nodeData[i]['coordinate'][1]);
         nodes.push(new ocargo.Node(coordinate));
	}

	// Link nodes (must be done in second loop so that linked nodes have definitely been created)
	for(i = 0; i < nodeData.length; i++){
		var node = nodes[i];
        var connectedNodes = nodeData[i]['connectedNodes'];
        for(var j = 0; j < connectedNodes.length; j++){
            node.addConnectedNode(nodes[connectedNodes[j]]);
    	}
	}

	return nodes;
}

function findByCoordinate(coordinate, nodes) {
    for (var i = 0; i < nodes.length; i++) {
        var coord = nodes[i].coordinate;
        if(coord.x === coordinate[0] && coord.y === coordinate[1]) {
            return i;
        }
    }
    return -1;
}

function initialiseDefault() {
    'use strict';

    var title = "Level " + LEVEL_ID;
    startPopup(title, "", LESSON);

    ocargo.ui = createUi();
    ocargo.level = createDefaultLevel(PATH, DESTINATION, DECOR, ocargo.ui, MAX_FUEL);
    ocargo.level.levelId = JSON.parse(LEVEL_ID);
    ocargo.level.blockLimit = JSON.parse(BLOCK_LIMIT);
    enableDirectControl();
    if (ocargo.level.blockLimit)
        ocargo.level.blockLimit++;
    if ($.cookie("muted") === "true") {
        $('#mute').text("Unmute");
        ocargo.sound.mute();
    }
}

function enableDirectControl() {
    document.getElementById('moveForward').disabled = false;
    document.getElementById('turnLeft').disabled = false;
    document.getElementById('turnRight').disabled = false;
    document.getElementById('play').disabled = false;
    document.getElementById('controls').style.visibility='visible';
}

function disableDirectControl() {
    document.getElementById('controls').style.visibility='hidden';
    document.getElementById('moveForward').disabled = true;
    document.getElementById('turnLeft').disabled = true;
    document.getElementById('turnRight').disabled = true;
    document.getElementById('play').disabled = true;
}

function clearVanData() {
    var nodes = ocargo.level.map.nodes;
    ocargo.level.van = new ocargo.Van(nodes[0], nodes[1], ocargo.level.van.maxFuel, ocargo.ui);
    ocargo.ui.setVanToFront();
}

function trackDevelopment() {
    $('#moveForward').click(function() {
        ocargo.blocklyControl.addBlockToEndOfProgram('move_forwards');
        moveForward(function(){});
    });

    $('#turnLeft').click(function() {
        ocargo.blocklyControl.addBlockToEndOfProgram('turn_left');
        moveLeft(function(){});
    });

    $('#turnRight').click(function() {
        ocargo.blocklyControl.addBlockToEndOfProgram('turn_right');
        moveRight(function(){});
    });

    $('#play').click(function() {
        if (ocargo.blocklyControl.incorrect)
            ocargo.blocklyControl.incorrect.setColour(ocargo.blocklyControl.incorrectColour);
        disableDirectControl();
        var program = ocargo.blocklyControl.populateProgram();
        program.instructionHandler = new InstructionHandler(ocargo.level);
        clearVanData();
        ocargo.level.play(program);
        ocargo.level.correct = 0;
    });

    $('#clearIncorrect').click(function() {
        ocargo.blocklyControl.removeWrong();
        enableDirectControl();
    });

    $('#clear').click(function() {
        ocargo.blocklyControl.reset();
        enableDirectControl();
        clearVanData();
    });

    $('#slideBlockly').click(function() {
        var c = $('#programmingConsole');
        if (c.is(':visible')) {
            $('#paper').animate({width: '100%'});
            $('#sliderControls').animate({left: '0%'});
        } else {
            $('#paper').animate({width: '50%'});
            $('#sliderControls').animate({left: '50%'});
        }
        c.animate({width: 'toggle'});
    });
}

$(function() {
    initialiseDefault();
    trackDevelopment();

});

$('#mute').click(function() {
    var $this = $(this);
    if (ocargo.sound.volume === 0) {
        $this.text('Mute');
        ocargo.sound.unmute();
    } else {
        $this.text('Unmute');
        ocargo.sound.mute();
    }
});
<commit_msg>Preventing users from multiple clicks and, hence, van not moving enough.<commit_after>var ocargo = ocargo || {};

function createUi() {
    return new ocargo.SimpleUi();
}

function createDefaultLevel(nodeData, destination, decor, ui, maxFuel) {
	var nodes = createNodes(nodeData);
    var destinationIndex = findByCoordinate(destination, nodes);
    var dest = destinationIndex > -1 ? nodes[destinationIndex] : nodes[nodes.length - 1];
    var map = new ocargo.Map(nodes, decor, dest, ui);
    var van = new ocargo.Van(nodes[0], nodes[0].connectedNodes[0], maxFuel, ui);
    return new ocargo.Level(map, van, ui);
}

function createNodes(nodeData){
	var nodes = [];

    var i;
	// Create nodes with coords
	for(i = 0; i < nodeData.length; i++){
		 var coordinate = new ocargo.Coordinate(nodeData[i]['coordinate'][0], nodeData[i]['coordinate'][1]);
         nodes.push(new ocargo.Node(coordinate));
	}

	// Link nodes (must be done in second loop so that linked nodes have definitely been created)
	for(i = 0; i < nodeData.length; i++){
		var node = nodes[i];
        var connectedNodes = nodeData[i]['connectedNodes'];
        for(var j = 0; j < connectedNodes.length; j++){
            node.addConnectedNode(nodes[connectedNodes[j]]);
    	}
	}

	return nodes;
}

function findByCoordinate(coordinate, nodes) {
    for (var i = 0; i < nodes.length; i++) {
        var coord = nodes[i].coordinate;
        if(coord.x === coordinate[0] && coord.y === coordinate[1]) {
            return i;
        }
    }
    return -1;
}

function initialiseDefault() {
    'use strict';

    var title = "Level " + LEVEL_ID;
    startPopup(title, "", LESSON);

    ocargo.ui = createUi();
    ocargo.level = createDefaultLevel(PATH, DESTINATION, DECOR, ocargo.ui, MAX_FUEL);
    ocargo.level.levelId = JSON.parse(LEVEL_ID);
    ocargo.level.blockLimit = JSON.parse(BLOCK_LIMIT);
    enableDirectControl();
    if (ocargo.level.blockLimit)
        ocargo.level.blockLimit++;
    if ($.cookie("muted") === "true") {
        $('#mute').text("Unmute");
        ocargo.sound.mute();
    }
}

function enableDirectControl() {
    document.getElementById('moveForward').disabled = false;
    document.getElementById('turnLeft').disabled = false;
    document.getElementById('turnRight').disabled = false;
    document.getElementById('play').disabled = false;
    document.getElementById('controls').style.visibility='visible';
}

function disableDirectControl() {
    document.getElementById('controls').style.visibility='hidden';
    document.getElementById('moveForward').disabled = true;
    document.getElementById('turnLeft').disabled = true;
    document.getElementById('turnRight').disabled = true;
    document.getElementById('play').disabled = true;
}

function clearVanData() {
    var nodes = ocargo.level.map.nodes;
    ocargo.level.van = new ocargo.Van(nodes[0], nodes[1], ocargo.level.van.maxFuel, ocargo.ui);
    ocargo.ui.setVanToFront();
}

function trackDevelopment() {

    $('#moveForward').click(function() {
        disableDirectControl();
        ocargo.blocklyControl.addBlockToEndOfProgram('move_forwards');
        moveForward(enableDirectControl);
    });

    $('#turnLeft').click(function() {
        disableDirectControl();
        ocargo.blocklyControl.addBlockToEndOfProgram('turn_left');
        moveLeft(enableDirectControl);
    });

    $('#turnRight').click(function() {
        disableDirectControl();
        ocargo.blocklyControl.addBlockToEndOfProgram('turn_right');
        moveRight(enableDirectControl);
    });

    $('#play').click(function() {
        if (ocargo.blocklyControl.incorrect)
            ocargo.blocklyControl.incorrect.setColour(ocargo.blocklyControl.incorrectColour);
        disableDirectControl();
        var program = ocargo.blocklyControl.populateProgram();

        program.instructionHandler = new InstructionHandler(ocargo.level);
        clearVanData();
        ocargo.level.play(program);
        ocargo.level.correct = 0;
    });

    $('#clearIncorrect').click(function() {
        ocargo.blocklyControl.removeWrong();
        enableDirectControl();
    });

    $('#clear').click(function() {
        ocargo.blocklyControl.reset();
        enableDirectControl();
        clearVanData();
    });

    $('#slideBlockly').click(function() {
        var c = $('#programmingConsole');
        if (c.is(':visible')) {
            $('#paper').animate({width: '100%'});
            $('#sliderControls').animate({left: '0%'});
        } else {
            $('#paper').animate({width: '50%'});
            $('#sliderControls').animate({left: '50%'});
        }
        c.animate({width: 'toggle'});
    });
}

$(function() {
    initialiseDefault();
    trackDevelopment();

});

$('#mute').click(function() {
    var $this = $(this);
    if (ocargo.sound.volume === 0) {
        $this.text('Mute');
        ocargo.sound.unmute();
    } else {
        $this.text('Unmute');
        ocargo.sound.mute();
    }
});
<|endoftext|>


<commit_before>//Connection url
//mongodb://USERNAME:PASSWORD@DBHOST:DBPORT/DBNAME?authSource=DATABASEADMIN

//Import dependencies
var MongoClient = require('mongodb').MongoClient;

//Database
var db = null;

//Connect to database
exports.Connect = function(opt, callback)
{
	//Check the database status
	if(db){ return callback(); }

	//Create the url
	var url = 'mongodb://' + opt.user + ':' + opt.pass + '@' + opt.host + ':' + opt.port + '/' + opt.db + '?authSource=' + opt.auth;

	//Else, connect to database
	MongoClient.connect(url, function(err, datab){

		//Check for error
		if(err)
		{
			//Show error in console
			console.error(err);

			//Return with error
			return callback(err);
		}

		//Save the database connection
		db = datab;

		//Do the callback
		callback();

	});

};

//Get the database
exports.Get = function(){ return db; };

//Close the connection
exports.Close = function(callback){

	//Close the connection to the database
	db.close(function(err, result){

		//Destroy the database
		db = null;

		//Do the callback
		callback(err);

	});

};
<commit_msg>Remove unused<commit_after><|endoftext|>


<commit_before>/* globals JSON */
import path from 'path';
import { MultiFileCachingCompiler } from 'meteor/caching-compiler';
import { Meteor } from 'meteor/meteor';
import { Babel } from 'meteor/babel-compiler';

import recursiveUnwrapped from 'recursive-readdir';
import ScssProcessor from './scss-processor';
import LessProcessor from './less-processor';
import StylusProcessor from './stylus-processor';
import CssModulesProcessor from './css-modules-processor';
import IncludedFile from './included-file';
import pluginOptionsWrapper, { reloadOptions } from './options';
import getOutputPath from './get-output-path';
import profile from './helpers/profile';
import ImportPathHelpers from './helpers/import-path-helpers';
import { stripIndent, stripIndents } from 'common-tags';

let pluginOptions = pluginOptionsWrapper.options;
const recursive = Meteor.wrapAsync(recursiveUnwrapped);

class FileMap extends Map {
  constructor(compiler) {
    super();
    this.compiler = compiler;
  }

  get(key) {
    const file = super.get(key);
    if (!file) { return; }
    this.compiler._prepInputFile(file);
    this.compiler.isRoot(file);
    return file;
  }
}

export default class CssModulesBuildPlugin extends MultiFileCachingCompiler {
  constructor() {
    super({
      compilerName: 'mss',
      defaultCacheSize: 1024 * 1024 * 10
    });
    this.profilingResults = {
      processFilesForTarget: null,
      _transpileScssToCss: null,
      _transpileCssModulesToCss: null
    };

    this.preprocessors = null;
    this.cssModulesProcessor = null;
    this.filesByName = null;
    this.optionsHash = null;

    this.reloadOptions = reloadOptions;
  }

  processFilesForTarget(files) {
    pluginOptions = this.reloadOptions();
    if (!pluginOptions.cache.enableCache) {
      this._cache.reset();
    }
    this.optionsHash = pluginOptions.hash;
    const start = profile();

    this.filesByName = new FileMap(this);
    files.forEach((inputFile) => {
      const importPath = this.getAbsoluteImportPath(inputFile);
      this.filesByName.set(importPath, inputFile);
    });

    files = removeFilesFromExcludedFolders(files);
    files = addFilesFromIncludedFolders(files);

    this._setupPreprocessors();
    this.cssModulesProcessor = new CssModulesProcessor(pluginOptions);

    super.processFilesForTarget(files);

    this.profilingResults.processFilesForTarget = profile(start, 'processFilesForTarget');

    function removeFilesFromExcludedFolders(files) {
      if (!pluginOptions.ignorePaths.length) {
        return files;
      }

      const testRegex = (file, regex) => regex.test(file.getPathInPackage());
      const testFile = file => testRegex.bind(this, file);
      const shouldKeepFile = file => pluginOptions.includePaths.some(testFile(file)) || !pluginOptions.ignorePaths.some(testFile(file));

      return files.filter(shouldKeepFile);
    }

    function addFilesFromIncludedFolders(files) {
      pluginOptions.explicitIncludes.map(folderPath => {
        const includedFiles = recursive(folderPath, [onlyAllowExtensionsHandledByPlugin]);
        files = files.concat(includedFiles.map(filePath => new IncludedFile(filePath.replace(/\\/g, '/'), files[0])));

        function onlyAllowExtensionsHandledByPlugin(file, stats) {
          let extension = path.extname(file);
          if (extension) {
            extension = extension.substring(1);
          }
          return !stats.isDirectory() && pluginOptions.extensions.indexOf(extension) === -1;
        }
      });
      return files;
    }
  }

  _prepInputFiles(files) {
    files.forEach(file => {
      file.referencedImportPaths = [];

      file.contents = file.getContentsAsString() || '';
      if (pluginOptions.globalVariablesText) {
        file.contents = `${pluginOptions.globalVariablesText}\n\n${file.contents}`;
      }
      file.rawContents = file.contents;
    });
  }

  _setupPreprocessors() {
    this.preprocessors = [];
    if (pluginOptions.enableSassCompilation) {
      this.preprocessors.push(new ScssProcessor(pluginOptions));
    }
    if (pluginOptions.enableStylusCompilation) {
      this.preprocessors.push(new StylusProcessor(pluginOptions));
    }
    if (pluginOptions.enableLessCompilation) {
      this.preprocessors.push(new LessProcessor(pluginOptions));
    }
  }

  isRoot(inputFile) {
    if ('isRoot' in inputFile) {
      return inputFile.isRoot;
    }

    let isRoot = null;
    for (let i = 0; i < this.preprocessors.length; i++) {
      const preprocessor = this.preprocessors[i];
      if (preprocessor.shouldProcess(inputFile)) {
        if (preprocessor.isRoot(inputFile)) {
          inputFile.preprocessor = preprocessor;
          inputFile.isRoot = true;
          return true;
        }
        isRoot = false;
      }
    }
    inputFile.isRoot = isRoot === null ? true : isRoot;
    /* If no preprocessors handle this file, it's automatically considered a root file. */
    return inputFile.isRoot;
  }

  compileOneFile(inputFile) {
    const filesByName = this.filesByName;

    this._prepInputFile(inputFile);
    this._preprocessFile(inputFile, filesByName);
    if (inputFile.transpileCssModules !== false) {
      this._transpileCssModulesToCss(inputFile, filesByName).await();
    }

    const compileResult = this._generateOutput(inputFile);
    return { compileResult, referencedImportPaths: inputFile.referencedImportPaths };
  }

  compileFromSource(source, backingInputFile, { transpileCssModules = true} = {}) {
    pluginOptions = this.reloadOptions();
    if (!pluginOptions.cache.enableCache) {
      this._cache.reset();
    }
    this.optionsHash = pluginOptions.hash;
    this._setupPreprocessors();
    this.cssModulesProcessor = new CssModulesProcessor(pluginOptions);

    this._updateFilesByName(new Map());
    const inputFile = this._createIncludedFile(backingInputFile.getPathInPackage(), backingInputFile, source);

    inputFile.transpileCssModules = transpileCssModules;
    return this.compileOneFile(inputFile, this.filesByName);
  }

  _createIncludedFile(importPath, rootFile, contents) {
    const file = new IncludedFile(importPath, rootFile);
    this.getAbsoluteImportPath(file);
    file.contents = contents;
    file.prepInputFile();
    this.filesByName.set(importPath, file);

    return file;
  }

  _generateOutput(inputFile) {
    const filePath = inputFile.getPathInPackage();
    const checkIfLazy = (filePath) => {
      let splitPath = filePath.split('/');
      return splitPath.indexOf('imports') >= 0 || splitPath.indexOf('node_modules') >= 0;
    };
    const isLazy = checkIfLazy(filePath);

    const compileResult = { isLazy, filePath, imports: inputFile.imports, absoluteImports: inputFile.absoluteImports };
    compileResult.stylesheet = inputFile.contents;

    compileResult.importsCode = inputFile.imports
      ? tryBabelCompile(inputFile.imports.map(importPath => `import '${importPath}';`).join('\n'))
      : '';

    const shouldAddStylesheet = inputFile.getArch().indexOf('web') === 0;
    compileResult.stylesheetCode = (isLazy && shouldAddStylesheet && inputFile.contents)
      ? tryBabelCompile(stripIndent`
         import modules from 'meteor/modules';
				 modules.addStyles(${JSON.stringify(inputFile.contents)});`)
      : '';

    compileResult.tokens = inputFile.tokens;
    compileResult.tokensCode = inputFile.tokens
      ? tryBabelCompile(stripIndent`
         const styles = ${JSON.stringify(inputFile.tokens)};
         export { styles as default, styles };`)
      : '';

    return compileResult;

    function tryBabelCompile(code) {
      try {
        return Babel.compile(code).code;
      } catch (err) {
        console.error(`\n/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);
        console.error(`Processing Step: Babel compilation`);
        console.error(`Unable to compile ${filePath}\n${err}`);
        console.error('Source: \n// <start of file>\n', code.replace(/^\s+/gm, ''));
        console.error(`// <end of file>`);
        console.error(`\n/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);
        throw err;
      }
    }
  }

  _prepInputFile(file) {
    if (file.isPrepped) {
      return;
    }

    file.referencedImportPaths = [];

    file.contents = file.getContentsAsString() || '';
    if (pluginOptions.globalVariablesText) {
      file.contents = `${pluginOptions.globalVariablesText}\n\n${file.contents}`;
    }
    file.rawContents = file.contents;

    file.isPrepped = true;
  }

  _preprocessFile(inputFile, filesByName) {
    if (inputFile.preprocessor) {
      inputFile.preprocessor.process(inputFile, filesByName);
    }
  }

  async _transpileCssModulesToCss(file, filesByName) {
    const startedAt = profile();

    await this.cssModulesProcessor.process(file, filesByName);

    this.profilingResults._transpileCssModulesToCss = (this.profilingResults._transpileCssModulesToCss || 0) + startedAt;
  }

  addCompileResult(file, result) {
    const isWebArchitecture = file.getArch().indexOf('web') === 0;
    const shouldAddStylesheet = isWebArchitecture && !result.isLazy;
    if (result.stylesheet && shouldAddStylesheet) {
      file.addStylesheet({
        data: result.stylesheet,
        path: getOutputPath(result.filePath, pluginOptions.outputCssFilePath) + '.css',
        sourcePath: getOutputPath(result.filePath, pluginOptions.outputCssFilePath) + '.css',
        sourceMap: JSON.stringify(result.sourceMap),
        lazy: false
      });
    }

    const js = (result.importsCode || result.stylesheetCode || result.tokensCode)
      ? stripIndents`
					${result.importsCode}
					${isWebArchitecture ? result.stylesheetCode : ''}
					${result.tokensCode}`
      : '';

    if (js) {
      file.addJavaScript({
        data: js,
        path: getOutputPath(result.filePath, pluginOptions.outputJsFilePath) + '.js',
        sourcePath: getOutputPath(result.filePath, pluginOptions.outputJsFilePath),
        lazy: result.isLazy,
        bare: false,
      });
    }
  }

  compileResultSize(compileResult) {
    return JSON.stringify(compileResult).length;
  }

  getCacheKey(inputFile) {
    return `${this.optionsHash}...${inputFile.getSourceHash()}`;
  }

  getAbsoluteImportPath(inputFile) {
    const importPath = ImportPathHelpers.getImportPathInPackage(inputFile);
    inputFile.importPath = importPath;
    return importPath;
  }

};

<commit_msg>fix compileFromSource<commit_after>/* globals JSON */
import path from 'path';
import { MultiFileCachingCompiler } from 'meteor/caching-compiler';
import { Meteor } from 'meteor/meteor';
import { Babel } from 'meteor/babel-compiler';

import recursiveUnwrapped from 'recursive-readdir';
import ScssProcessor from './scss-processor';
import LessProcessor from './less-processor';
import StylusProcessor from './stylus-processor';
import CssModulesProcessor from './css-modules-processor';
import IncludedFile from './included-file';
import pluginOptionsWrapper, { reloadOptions } from './options';
import getOutputPath from './get-output-path';
import profile from './helpers/profile';
import ImportPathHelpers from './helpers/import-path-helpers';
import { stripIndent, stripIndents } from 'common-tags';

let pluginOptions = pluginOptionsWrapper.options;
const recursive = Meteor.wrapAsync(recursiveUnwrapped);

class FileMap extends Map {
  constructor(compiler) {
    super();
    this.compiler = compiler;
  }

  get(key) {
    const file = super.get(key);
    if (!file) { return; }
    this.compiler._prepInputFile(file);
    this.compiler.isRoot(file);
    return file;
  }
}

export default class CssModulesBuildPlugin extends MultiFileCachingCompiler {
  constructor() {
    super({
      compilerName: 'mss',
      defaultCacheSize: 1024 * 1024 * 10
    });
    this.profilingResults = {
      processFilesForTarget: null,
      _transpileScssToCss: null,
      _transpileCssModulesToCss: null
    };

    this.preprocessors = null;
    this.cssModulesProcessor = null;
    this.filesByName = null;
    this.optionsHash = null;

    this.reloadOptions = reloadOptions;
  }

  processFilesForTarget(files) {
    pluginOptions = this.reloadOptions();
    if (!pluginOptions.cache.enableCache) {
      this._cache.reset();
    }
    this.optionsHash = pluginOptions.hash;
    const start = profile();

    this.filesByName = new FileMap(this);
    files.forEach((inputFile) => {
      const importPath = this.getAbsoluteImportPath(inputFile);
      this.filesByName.set(importPath, inputFile);
    });

    files = removeFilesFromExcludedFolders(files);
    files = addFilesFromIncludedFolders(files);

    this._setupPreprocessors();
    this.cssModulesProcessor = new CssModulesProcessor(pluginOptions);

    super.processFilesForTarget(files);

    this.profilingResults.processFilesForTarget = profile(start, 'processFilesForTarget');

    function removeFilesFromExcludedFolders(files) {
      if (!pluginOptions.ignorePaths.length) {
        return files;
      }

      const testRegex = (file, regex) => regex.test(file.getPathInPackage());
      const testFile = file => testRegex.bind(this, file);
      const shouldKeepFile = file => pluginOptions.includePaths.some(testFile(file)) || !pluginOptions.ignorePaths.some(testFile(file));

      return files.filter(shouldKeepFile);
    }

    function addFilesFromIncludedFolders(files) {
      pluginOptions.explicitIncludes.map(folderPath => {
        const includedFiles = recursive(folderPath, [onlyAllowExtensionsHandledByPlugin]);
        files = files.concat(includedFiles.map(filePath => new IncludedFile(filePath.replace(/\\/g, '/'), files[0])));

        function onlyAllowExtensionsHandledByPlugin(file, stats) {
          let extension = path.extname(file);
          if (extension) {
            extension = extension.substring(1);
          }
          return !stats.isDirectory() && pluginOptions.extensions.indexOf(extension) === -1;
        }
      });
      return files;
    }
  }

  _prepInputFiles(files) {
    files.forEach(file => {
      file.referencedImportPaths = [];

      file.contents = file.getContentsAsString() || '';
      if (pluginOptions.globalVariablesText) {
        file.contents = `${pluginOptions.globalVariablesText}\n\n${file.contents}`;
      }
      file.rawContents = file.contents;
    });
  }

  _setupPreprocessors() {
    this.preprocessors = [];
    if (pluginOptions.enableSassCompilation) {
      this.preprocessors.push(new ScssProcessor(pluginOptions));
    }
    if (pluginOptions.enableStylusCompilation) {
      this.preprocessors.push(new StylusProcessor(pluginOptions));
    }
    if (pluginOptions.enableLessCompilation) {
      this.preprocessors.push(new LessProcessor(pluginOptions));
    }
  }

  isRoot(inputFile) {
    if ('isRoot' in inputFile) {
      return inputFile.isRoot;
    }

    let isRoot = null;
    for (let i = 0; i < this.preprocessors.length; i++) {
      const preprocessor = this.preprocessors[i];
      if (preprocessor.shouldProcess(inputFile)) {
        if (preprocessor.isRoot(inputFile)) {
          inputFile.preprocessor = preprocessor;
          inputFile.isRoot = true;
          return true;
        }
        isRoot = false;
      }
    }
    inputFile.isRoot = isRoot === null ? true : isRoot;
    /* If no preprocessors handle this file, it's automatically considered a root file. */
    return inputFile.isRoot;
  }

  compileOneFile(inputFile) {
    const filesByName = this.filesByName;

    this._prepInputFile(inputFile);
    this._preprocessFile(inputFile, filesByName);
    if (inputFile.transpileCssModules !== false) {
      this._transpileCssModulesToCss(inputFile, filesByName).await();
    }

    const compileResult = this._generateOutput(inputFile);
    return { compileResult, referencedImportPaths: inputFile.referencedImportPaths };
  }

  compileFromSource(source, backingInputFile, { transpileCssModules = true} = {}) {
    pluginOptions = this.reloadOptions();
    if (!pluginOptions.cache.enableCache) {
      this._cache.reset();
    }
    this.optionsHash = pluginOptions.hash;
    this._setupPreprocessors();
    this.cssModulesProcessor = new CssModulesProcessor(pluginOptions);

    this.filesByName = new FileMap(this);
    const inputFile = this._createIncludedFile(backingInputFile.getPathInPackage(), backingInputFile, source);

    inputFile.transpileCssModules = transpileCssModules;
    return this.compileOneFile(inputFile, this.filesByName);
  }

  _createIncludedFile(importPath, rootFile, contents) {
    const file = new IncludedFile(importPath, rootFile);
    this.getAbsoluteImportPath(file);
    file.contents = contents;
    file.prepInputFile();
    this.filesByName.set(importPath, file);

    return file;
  }

  _generateOutput(inputFile) {
    const filePath = inputFile.getPathInPackage();
    const checkIfLazy = (filePath) => {
      let splitPath = filePath.split('/');
      return splitPath.indexOf('imports') >= 0 || splitPath.indexOf('node_modules') >= 0;
    };
    const isLazy = checkIfLazy(filePath);

    const compileResult = { isLazy, filePath, imports: inputFile.imports, absoluteImports: inputFile.absoluteImports };
    compileResult.stylesheet = inputFile.contents;

    compileResult.importsCode = inputFile.imports
      ? tryBabelCompile(inputFile.imports.map(importPath => `import '${importPath}';`).join('\n'))
      : '';

    const shouldAddStylesheet = inputFile.getArch().indexOf('web') === 0;
    compileResult.stylesheetCode = (isLazy && shouldAddStylesheet && inputFile.contents)
      ? tryBabelCompile(stripIndent`
         import modules from 'meteor/modules';
				 modules.addStyles(${JSON.stringify(inputFile.contents)});`)
      : '';

    compileResult.tokens = inputFile.tokens;
    compileResult.tokensCode = inputFile.tokens
      ? tryBabelCompile(stripIndent`
         const styles = ${JSON.stringify(inputFile.tokens)};
         export { styles as default, styles };`)
      : '';

    return compileResult;

    function tryBabelCompile(code) {
      try {
        return Babel.compile(code).code;
      } catch (err) {
        console.error(`\n/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);
        console.error(`Processing Step: Babel compilation`);
        console.error(`Unable to compile ${filePath}\n${err}`);
        console.error('Source: \n// <start of file>\n', code.replace(/^\s+/gm, ''));
        console.error(`// <end of file>`);
        console.error(`\n/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);
        throw err;
      }
    }
  }

  _prepInputFile(file) {
    if (file.isPrepped) {
      return;
    }

    file.referencedImportPaths = [];

    file.contents = file.getContentsAsString() || '';
    if (pluginOptions.globalVariablesText) {
      file.contents = `${pluginOptions.globalVariablesText}\n\n${file.contents}`;
    }
    file.rawContents = file.contents;

    file.isPrepped = true;
  }

  _preprocessFile(inputFile, filesByName) {
    if (inputFile.preprocessor) {
      inputFile.preprocessor.process(inputFile, filesByName);
    }
  }

  async _transpileCssModulesToCss(file, filesByName) {
    const startedAt = profile();

    await this.cssModulesProcessor.process(file, filesByName);

    this.profilingResults._transpileCssModulesToCss = (this.profilingResults._transpileCssModulesToCss || 0) + startedAt;
  }

  addCompileResult(file, result) {
    const isWebArchitecture = file.getArch().indexOf('web') === 0;
    const shouldAddStylesheet = isWebArchitecture && !result.isLazy;
    if (result.stylesheet && shouldAddStylesheet) {
      file.addStylesheet({
        data: result.stylesheet,
        path: getOutputPath(result.filePath, pluginOptions.outputCssFilePath) + '.css',
        sourcePath: getOutputPath(result.filePath, pluginOptions.outputCssFilePath) + '.css',
        sourceMap: JSON.stringify(result.sourceMap),
        lazy: false
      });
    }

    const js = (result.importsCode || result.stylesheetCode || result.tokensCode)
      ? stripIndents`
					${result.importsCode}
					${isWebArchitecture ? result.stylesheetCode : ''}
					${result.tokensCode}`
      : '';

    if (js) {
      file.addJavaScript({
        data: js,
        path: getOutputPath(result.filePath, pluginOptions.outputJsFilePath) + '.js',
        sourcePath: getOutputPath(result.filePath, pluginOptions.outputJsFilePath),
        lazy: result.isLazy,
        bare: false,
      });
    }
  }

  compileResultSize(compileResult) {
    return JSON.stringify(compileResult).length;
  }

  getCacheKey(inputFile) {
    return `${this.optionsHash}...${inputFile.getSourceHash()}`;
  }

  getAbsoluteImportPath(inputFile) {
    const importPath = ImportPathHelpers.getImportPathInPackage(inputFile);
    inputFile.importPath = importPath;
    return importPath;
  }

};

<|endoftext|>