<commit_before>// @flow
import * as React from 'react'
import * as c from '@frogpond/colors'
import {
	Platform,
	StyleSheet,
	TextInput,
	View,
	SegmentedControlIOS,
} from 'react-native'
import {Toolbar} from '@frogpond/toolbar'
import {fetch} from '@frogpond/fetch'
import {API} from '@frogpond/api'
import glamorous from 'glamorous-native'
import {iOSUIKit, material} from 'react-native-typography'
import type {NavigationScreenProp} from 'react-navigation'
import {DebugListView} from '../screens/debug'

const styles = StyleSheet.create({
	container: {
		backgroundColor: c.white,
		flex: 1,
	},
	default: {
		height: 44,
		borderBottomWidth: StyleSheet.hairlineWidth,
		borderColor: c.black,
		flex: 1,
		fontSize: 13,
		paddingVertical: 4,
		paddingHorizontal: 8,
	},
	data: {
		padding: 10,
	},
	error: {
		padding: 10,
		color: c.brickRed,
	},
})

const Output = glamorous(TextInput)({
	marginVertical: 3,
	paddingRight: 4,
	...Platform.select({
		ios: iOSUIKit.bodyObject,
		android: material.body1Object,
	}),
})

const Segment = glamorous(SegmentedControlIOS)({})

type Props = {
	navigation: NavigationScreenProp<*>,
}

type State = {
	results: ?string,
	error: ?string,
	selectedIndex: number,
}

export class APITestView extends React.PureComponent<Props, State> {
	static navigationOptions = {
		title: 'API Tester',
	}

	state = {
		results: null,
		error: null,
		selectedIndex: 0,
	}

	fetchData = async (path: string) => {
		try {
			let correctedPath = path.startsWith('/') ? path : `/${path}`
			let responseData: string = await fetch(API(correctedPath), {
				cache: 'no-store',
			}).text()
			this.setState(() => ({results: responseData, error: null}))
		} catch (err) {
			this.setState(() => ({results: null, error: JSON.stringify(err)}))
		}
	}

	render() {
		let {error, results, selectedIndex} = this.state

		let jsonError = error ? (
			<Output
				editable={false}
				// this aligns the text to the top on iOS, and centers it on Android
				multiline={true}
				scrollEnabled={true}
				style={styles.error}
				// use multiline with textAlignVertical="top" for the same behavior in both platforms
				textAlignVertical="top"
				value={error}
			/>
		) : null

		let jsonData = results ? (
			<Output
				editable={false}
				// this aligns the text to the top on iOS, and centers it on Android
				multiline={true}
				scrollEnabled={true}
				style={styles.data}
				// use multiline with textAlignVertical="top" for the same behavior in both platforms
				textAlignVertical="top"
				value={results}
			/>
		) : null

		let showIndex = () => {
			return selectedIndex === 0 ? (
				<>
					{jsonData}
					{jsonError}
				</>
			) : (
				<DebugListView
					navigation={this.props.navigation}
					state={results}
					testing={true}
				/>
			)
		}
		return (
			<View style={styles.container}>
				<Toolbar onPress={() => {}}>
					<TextInput
						autoCapitalize="none"
						autoCorrect={false}
						keyboardType="web-search"
						onEndEditing={e => this.fetchData(e.nativeEvent.text)}
						placeholder="path/to/resource"
						returnKeyType="done"
						style={styles.default}
					/>
				</Toolbar>

				{Platform.OS === 'ios' ? (
					<Segment
						onChange={event => {
							this.setState({
								selectedIndex: event.nativeEvent.selectedSegmentIndex,
							})
						}}
						selectedIndex={selectedIndex}
						values={['Text', 'Parsed']}
					/>
				) : null}

				{showIndex()}
			</View>
		)
	}
}
<commit_msg>Update source/views/settings/screens/api-test.js<commit_after>// @flow
import * as React from 'react'
import * as c from '@frogpond/colors'
import {
	Platform,
	StyleSheet,
	TextInput,
	View,
	SegmentedControlIOS,
} from 'react-native'
import {Toolbar} from '@frogpond/toolbar'
import {fetch} from '@frogpond/fetch'
import {API} from '@frogpond/api'
import glamorous from 'glamorous-native'
import {iOSUIKit, material} from 'react-native-typography'
import type {NavigationScreenProp} from 'react-navigation'
import {DebugListView} from '../screens/debug'

const styles = StyleSheet.create({
	container: {
		backgroundColor: c.white,
		flex: 1,
	},
	default: {
		height: 44,
		borderBottomWidth: StyleSheet.hairlineWidth,
		borderColor: c.black,
		flex: 1,
		fontSize: 13,
		paddingVertical: 4,
		paddingHorizontal: 8,
	},
	data: {
		padding: 10,
	},
	error: {
		padding: 10,
		color: c.brickRed,
	},
})

const Output = glamorous(TextInput)({
	marginVertical: 3,
	paddingRight: 4,
	...Platform.select({
		ios: iOSUIKit.bodyObject,
		android: material.body1Object,
	}),
})

const Segment = glamorous(SegmentedControlIOS)({})

type Props = {
	navigation: NavigationScreenProp<*>,
}

type State = {
	results: ?string,
	error: ?string,
	selectedIndex: number,
}

export class APITestView extends React.PureComponent<Props, State> {
	static navigationOptions = {
		title: 'API Tester',
	}

	state = {
		results: null,
		error: null,
		selectedIndex: 0,
	}

	fetchData = async (path: string) => {
		try {
			let correctedPath = path.startsWith('/') ? path : `/${path}`
			let responseData: string = await fetch(API(correctedPath), {
				cache: 'no-store',
			}).text()
			this.setState(() => ({results: responseData, error: null}))
		} catch (err) {
			this.setState(() => ({results: null, error: JSON.stringify(err)}))
		}
	}

	render() {
		let {error, results, selectedIndex} = this.state

		let jsonError = error ? (
			<Output
				editable={false}
				// this aligns the text to the top on iOS, and centers it on Android
				multiline={true}
				scrollEnabled={true}
				style={styles.error}
				// use multiline with textAlignVertical="top" for the same behavior in both platforms
				textAlignVertical="top"
				value={error}
			/>
		) : null

		let jsonData = results ? (
			<Output
				editable={false}
				// this aligns the text to the top on iOS, and centers it on Android
				multiline={true}
				scrollEnabled={true}
				style={styles.data}
				// use multiline with textAlignVertical="top" for the same behavior in both platforms
				textAlignVertical="top"
				value={results}
			/>
		) : null

		let showIndex = () => {
			return selectedIndex === 0 ? (
				<>
					{jsonData}
					{jsonError}
			error ? (
				<Output
					editable={false}
					// this aligns the text to the top on iOS, and centers it on Android
					multiline={true}
					scrollEnabled={true}
					style={styles.error}
					// use multiline with textAlignVertical="top" for the same behavior in both platforms
					textAlignVertical="top"
					value={error}
				/>
			) : selectedIndex === 0 ? (
				<Output
					editable={false}
					// this aligns the text to the top on iOS, and centers it on Android
					multiline={true}
					scrollEnabled={true}
					style={styles.data}
					// use multiline with textAlignVertical="top" for the same behavior in both platforms
					textAlignVertical="top"
					value={results}
				/>
			) : (
				<DebugListView
					navigation={this.props.navigation}
					state={results}
					testing={true}
				/>
			)
			) : (
				<DebugListView
					navigation={this.props.navigation}
					state={results}
					testing={true}
				/>
			)
		}
		return (
			<View style={styles.container}>
				<Toolbar onPress={() => {}}>
					<TextInput
						autoCapitalize="none"
						autoCorrect={false}
						keyboardType="web-search"
						onEndEditing={e => this.fetchData(e.nativeEvent.text)}
						placeholder="path/to/resource"
						returnKeyType="done"
						style={styles.default}
					/>
				</Toolbar>

				{Platform.OS === 'ios' ? (
					<Segment
						onChange={event => {
							this.setState({
								selectedIndex: event.nativeEvent.selectedSegmentIndex,
							})
						}}
						selectedIndex={selectedIndex}
						values={['Text', 'Parsed']}
					/>
				) : null}

				{showIndex()}
			</View>
		)
	}
}
<|endoftext|>


<commit_before>function fmt(value, className) {
  return {msg: value, className: "jquery-console-message-" + className};
}

function fmtValue(value) { return fmt(value, "value"); }
function fmtType(value) { return fmt(value, "type"); }
function fmtError(value) { return fmt(value, "error"); }

$(function() {
  var console = $('.console');

  var controller = console.console({
    promptLabel: 'λ> ',
    autofocus: true,
    animateScroll: true,
    promptHistory: true,
    welcomeMessage: "Welcome to Dawghaus. Try this: sequence([fd 10, lt 90, fd 20])",

    commandValidate: function(line) {
      return line != "";
    },

    commandHandle: function (line, report) {
      var parts = line.split(" ");

      switch (parts[0]) {
      case ":t":
        var term = parts[1]
        var env = royloader.royEnv(term)
        if (env) {
          return [fmtType(env)];
        } else {
          return [fmtError(term + " is not defined.")];
        }

      case ":c":
        try {
          var code = parts.slice(1).join(" ");
          var compiled = royloader.compileRoy(code)
          return [fmt(compiled.output, "code")];
        } catch(e) {
          return [fmtError(e.toString())];
        }

      default:
        try {
          var evaled = royloader.evalRoy(line);

          if (evaled != undefined) {
            // TODO: hack
            if (typeof evaled.result == "function") {
              evaled.result = evaled.result()
              return ""
            }
            return [fmtValue(JSON.stringify(evaled.result)),
                    fmtType(": " + evaled.type.toString())];
          } else {
            return true;
          }
        } catch(e) {
          return [fmtError(e.toString())];
        }
      }
    }
  });
});
<commit_msg>example command is now circle<commit_after>function fmt(value, className) {
  return {msg: value, className: "jquery-console-message-" + className};
}

function fmtValue(value) { return fmt(value, "value"); }
function fmtType(value) { return fmt(value, "type"); }
function fmtError(value) { return fmt(value, "error"); }

$(function() {
  var console = $('.console');

  var controller = console.console({
    promptLabel: 'λ> ',
    autofocus: true,
    animateScroll: true,
    promptHistory: true,
    welcomeMessage: "Welcome to Dawghaus. Try this: repeat 360 (sequence[fd 1, lt 1])",

    commandValidate: function(line) {
      return line != "";
    },

    commandHandle: function (line, report) {
      var parts = line.split(" ");

      switch (parts[0]) {
      case ":t":
        var term = parts[1]
        var env = royloader.royEnv(term)
        if (env) {
          return [fmtType(env)];
        } else {
          return [fmtError(term + " is not defined.")];
        }

      case ":c":
        try {
          var code = parts.slice(1).join(" ");
          var compiled = royloader.compileRoy(code)
          return [fmt(compiled.output, "code")];
        } catch(e) {
          return [fmtError(e.toString())];
        }

      default:
        try {
          var evaled = royloader.evalRoy(line);

          if (evaled != undefined) {
            // TODO: hack
            if (typeof evaled.result == "function") {
              evaled.result = evaled.result()
              return ""
            }
            return [fmtValue(JSON.stringify(evaled.result)),
                    fmtType(": " + evaled.type.toString())];
          } else {
            return true;
          }
        } catch(e) {
          return [fmtError(e.toString())];
        }
      }
    }
  });
});
<|endoftext|>


<commit_before>var https = require('https');
var LRU = require('lru-cache');
var tls = require('tls');
var sockx = require('sockx');
var util = require('../util');
var config = require('../config');
var http2 = config.enableH2 ? require('http2') : null;

var SUPPORTED_PROTOS = ['h2', 'http/1.1', 'http/1.0'];
var H2_SETTINGS = { enablePush: false , enableConnectProtocol: false };
var clients = {};
var notH2 = new LRU({max: 2560});
var pendingH2 = {};
var pendingList = {};
var TIMEOUT = 36000;

function getKey(options) {
  var proxyOpts = options._proxyOptions;
  var proxyType = '';
  if (proxyOpts) {
    proxyType = [proxyOpts.proxyType, proxyOpts.proxyHost, proxyOpts.proxyPort, proxyOpts.headers.host].join(':');
  }
  return [options.servername, options.host, options.port || '', proxyType].join('/');
}

function getSocksSocket(options, callback) {
  var done;
  var handleCallback = function(err, socket) {
    if (!done) {
      done = true;
      callback(err, socket);
    }
  };
  var proxyOpts = options._proxyOptions;
  var client = sockx.connect({
    localDNS: false,
    proxyHost: proxyOpts.proxyHost,
    proxyPort: proxyOpts.proxyPort,
    auths: config.getAuths(proxyOpts),
    host: options.host,
    port: options.port || 443
  }, function(socket) {
    handleCallback(null, socket);
  });
  client.on('error', handleCallback);
}

function getTunnelSocket(options, callback) {
  var done;
  var handleCallback = function(err, socket) {
    if (!done) {
      done = true;
      callback(err, socket);
    }
  };
  var connReq = config.connect(options._proxyOptions, function(socket) {
    handleCallback(null, socket);
  });
  connReq.on('error', handleCallback);
}

function getProxySocket(options, callback) {
  var handleConnect = function(err, socket) {
    if (err) {
      return callback(err);
    }
    var timer = setTimeout(function() {
      if (timer) {
        timer = null;
        socket.destroy();
      }
    }, config.CONN_TIMEOUT);
    var handleCallback = function(err) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
        callback(err, err ? null : socket);
      }
    };
    socket = tls.connect({
      servername: options.servername,
      socket: socket,
      rejectUnauthorized: false,
      ALPNProtocols: SUPPORTED_PROTOS,
      NPNProtocols: SUPPORTED_PROTOS
    }, handleCallback);
    socket.on('error', handleCallback);
  };
  var proxyOpts = options._proxyOptions;
  proxyOpts.proxyType === 'socks' ?
    getSocksSocket(options, handleConnect) :
      getTunnelSocket(options, handleConnect);
}

function getSocket(options, callback) {
  if (!options) {
    return callback();
  }
  var handleCallback = function(err, socket) {
    if (err) {
      return callback(false, null, err);
    }
    var proto = socket.alpnProtocol || socket.npnProtocol;
    callback(proto === 'h2', socket);
  };
  options._proxyOptions ?
    getProxySocket(options, handleCallback) :
      util.connect({
        servername: options.servername,
        host: options.host,
        port: options.port || 443,
        rejectUnauthorized: false,
        ALPNProtocols: SUPPORTED_PROTOS,
        NPNProtocols: SUPPORTED_PROTOS
      }, handleCallback);
}

function getClient(req, socket, name) {
  var client = http2.connect('https://' + req.headers.host, {
    setttings: H2_SETTINGS,
    rejectUnauthorized: false,
    createConnection: function() {
      return socket;
    }
  });
  clients[name] = client;
  var closed;
  var handleClose = function() {
    if (!closed) {
      closed = true;
      delete clients[name];
      client.close();
      socket.destroy();
    }
  };
  socket.on('error', handleClose);
  socket.on('close', handleClose);
  client.on('error', handleClose);
  return client;
}

function requestH2(client, req, res) {
  if (req.hasError) {
    return;
  }
  var headers = util.formatH2Headers(req.headers);
  delete req.headers.connection;
  delete req.headers['keep-alive'];
  delete req.headers['http2-settings'];
  delete req.headers['proxy-connection'];
  delete req.headers['transfer-encoding'];
  headers[':path'] = req.url;
  headers[':method'] = req.method;
  headers[':authority'] = req.headers.host;
  try {
    var h2Session = client.request(headers);
    h2Session.on('error', util.noop);
    h2Session.on('response', function(h2Headers) {
      var newHeaders = {};
      h2Session.statusCode = h2Headers[':status'];
      h2Session.httpVersion = '1.1';
      h2Session.headers = newHeaders;
      Object.keys(h2Headers).forEach(function(name) {
        if (name[0] !== ':') {
          newHeaders[name] = h2Headers[name];
        }
      });
      res.response(h2Session);
    });
    req.pipe(h2Session);
  } catch (e) {
    client.emit('error', e);
  }
}

exports.getServer = function(options, listener) {
  var createServer;
  if (options.allowHTTP1 && http2) {
    createServer = http2.createSecureServer;
    options.setttings = H2_SETTINGS;
  } else {
    createServer = https.createServer;
  }
  var server = createServer(options);
  if (typeof listener === 'function') {
    server.on('request', listener);
  } else if (listener) {
    Object.keys(listener).forEach(function(name) {
      server.on(name, listener[name]);
    });
  }
  return server;
};

function checkTlsError(err) {
  if (!err) {
    return true;
  }
  var code = err.code;
  if (typeof code !== 'string') {
    return false;
  }
  return code.indexOf('ERR_TLS_') === 0 || code.indexOf('ERR_SSL_') === 0;
}

/**
 * TODO(v2.0): 遗留两种需要处理的H2请求
 * 1. 设置代理后的请求
 * 2. 插件转发回来的请求
 */
exports.request = function(req, res, callback) {
  var options = req.useH2 && req.options;
  if (!options) {
    return callback();
  }
  var key = getKey(options);
  var name = req.sessionId + '\n' + key;
  var client = clients[name];
  if (client) {
    return requestH2(client, req, res);
  }
  var time = notH2.peek(key);
  if (time && (Date.now() - time < TIMEOUT || pendingH2[key])) {
    return callback();
  }
  pendingH2[key] = 1;
  var pendingItem = pendingList[name];
  if (pendingItem) {
    return pendingItem.push([req, res, callback]);
  }
  pendingItem = [[req, res, callback]];
  pendingList[name] = pendingItem;
  getSocket(options, function(isH2, socket, err) {
    client =isH2 && getClient(req, socket, name);
    delete pendingList[name];
    delete pendingH2[key];
    if (client) {
      notH2.del(key);
      pendingItem.forEach(function(list) {
        requestH2(client, list[0], list[1]);
      });
    } else {
      checkTlsError(err) && notH2.set(key, Date.now());
      pendingItem.forEach(function(list) {
        list[2](socket);
        socket = null;
      });
    }
  });
};
<commit_msg>fix: replace url error<commit_after>var https = require('https');
var LRU = require('lru-cache');
var tls = require('tls');
var sockx = require('sockx');
var util = require('../util');
var config = require('../config');
var http2 = config.enableH2 ? require('http2') : null;

var SUPPORTED_PROTOS = ['h2', 'http/1.1', 'http/1.0'];
var H2_SETTINGS = { enablePush: false , enableConnectProtocol: false };
var clients = {};
var notH2 = new LRU({max: 2560});
var pendingH2 = {};
var pendingList = {};
var TIMEOUT = 36000;

function getKey(options) {
  var proxyOpts = options._proxyOptions;
  var proxyType = '';
  if (proxyOpts) {
    proxyType = [proxyOpts.proxyType, proxyOpts.proxyHost, proxyOpts.proxyPort, proxyOpts.headers.host].join(':');
  }
  return [options.servername, options.host, options.port || '', proxyType].join('/');
}

function getSocksSocket(options, callback) {
  var done;
  var handleCallback = function(err, socket) {
    if (!done) {
      done = true;
      callback(err, socket);
    }
  };
  var proxyOpts = options._proxyOptions;
  var client = sockx.connect({
    localDNS: false,
    proxyHost: proxyOpts.proxyHost,
    proxyPort: proxyOpts.proxyPort,
    auths: config.getAuths(proxyOpts),
    host: options.host,
    port: options.port || 443
  }, function(socket) {
    handleCallback(null, socket);
  });
  client.on('error', handleCallback);
}

function getTunnelSocket(options, callback) {
  var done;
  var handleCallback = function(err, socket) {
    if (!done) {
      done = true;
      callback(err, socket);
    }
  };
  var connReq = config.connect(options._proxyOptions, function(socket) {
    handleCallback(null, socket);
  });
  connReq.on('error', handleCallback);
}

function getProxySocket(options, callback) {
  var handleConnect = function(err, socket) {
    if (err) {
      return callback(err);
    }
    var timer = setTimeout(function() {
      if (timer) {
        timer = null;
        socket.destroy();
      }
    }, config.CONN_TIMEOUT);
    var handleCallback = function(err) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
        callback(err, err ? null : socket);
      }
    };
    socket = tls.connect({
      servername: options.servername,
      socket: socket,
      rejectUnauthorized: false,
      ALPNProtocols: SUPPORTED_PROTOS,
      NPNProtocols: SUPPORTED_PROTOS
    }, handleCallback);
    socket.on('error', handleCallback);
  };
  var proxyOpts = options._proxyOptions;
  proxyOpts.proxyType === 'socks' ?
    getSocksSocket(options, handleConnect) :
      getTunnelSocket(options, handleConnect);
}

function getSocket(options, callback) {
  if (!options) {
    return callback();
  }
  var handleCallback = function(err, socket) {
    if (err) {
      return callback(false, null, err);
    }
    var proto = socket.alpnProtocol || socket.npnProtocol;
    callback(proto === 'h2', socket);
  };
  options._proxyOptions ?
    getProxySocket(options, handleCallback) :
      util.connect({
        servername: options.servername,
        host: options.host,
        port: options.port || 443,
        rejectUnauthorized: false,
        ALPNProtocols: SUPPORTED_PROTOS,
        NPNProtocols: SUPPORTED_PROTOS
      }, handleCallback);
}

function getClient(req, socket, name) {
  var client = http2.connect('https://' + req.headers.host, {
    setttings: H2_SETTINGS,
    rejectUnauthorized: false,
    createConnection: function() {
      return socket;
    }
  });
  clients[name] = client;
  var closed;
  var handleClose = function() {
    if (!closed) {
      closed = true;
      delete clients[name];
      client.close();
      socket.destroy();
    }
  };
  socket.on('error', handleClose);
  socket.on('close', handleClose);
  client.on('error', handleClose);
  return client;
}

function requestH2(client, req, res) {
  if (req.hasError) {
    return;
  }
  var headers = util.formatH2Headers(req.headers);
  delete req.headers.connection;
  delete req.headers['keep-alive'];
  delete req.headers['http2-settings'];
  delete req.headers['proxy-connection'];
  delete req.headers['transfer-encoding'];
  var options = req.options;
  headers[':path'] = options.path;
  headers[':method'] = options.method;
  headers[':authority'] = req.headers.host;
  try {
    var h2Session = client.request(headers);
    h2Session.on('error', util.noop);
    h2Session.on('response', function(h2Headers) {
      var newHeaders = {};
      h2Session.statusCode = h2Headers[':status'];
      h2Session.httpVersion = '1.1';
      h2Session.headers = newHeaders;
      Object.keys(h2Headers).forEach(function(name) {
        if (name[0] !== ':') {
          newHeaders[name] = h2Headers[name];
        }
      });
      res.response(h2Session);
    });
    req.pipe(h2Session);
  } catch (e) {
    client.emit('error', e);
  }
}

exports.getServer = function(options, listener) {
  var createServer;
  if (options.allowHTTP1 && http2) {
    createServer = http2.createSecureServer;
    options.setttings = H2_SETTINGS;
  } else {
    createServer = https.createServer;
  }
  var server = createServer(options);
  if (typeof listener === 'function') {
    server.on('request', listener);
  } else if (listener) {
    Object.keys(listener).forEach(function(name) {
      server.on(name, listener[name]);
    });
  }
  return server;
};

function checkTlsError(err) {
  if (!err) {
    return true;
  }
  var code = err.code;
  if (typeof code !== 'string') {
    return false;
  }
  return code.indexOf('ERR_TLS_') === 0 || code.indexOf('ERR_SSL_') === 0;
}

/**
 * TODO(v2.0): 遗留两种需要处理的H2请求
 * 1. 设置代理后的请求
 * 2. 插件转发回来的请求
 */
exports.request = function(req, res, callback) {
  var options = req.useH2 && req.options;
  if (!options) {
    return callback();
  }
  var key = getKey(options);
  var name = req.sessionId + '\n' + key;
  var client = clients[name];
  if (client) {
    return requestH2(client, req, res);
  }
  var time = notH2.peek(key);
  if (time && (Date.now() - time < TIMEOUT || pendingH2[key])) {
    return callback();
  }
  pendingH2[key] = 1;
  var pendingItem = pendingList[name];
  if (pendingItem) {
    return pendingItem.push([req, res, callback]);
  }
  pendingItem = [[req, res, callback]];
  pendingList[name] = pendingItem;
  getSocket(options, function(isH2, socket, err) {
    client =isH2 && getClient(req, socket, name);
    delete pendingList[name];
    delete pendingH2[key];
    if (client) {
      notH2.del(key);
      pendingItem.forEach(function(list) {
        requestH2(client, list[0], list[1]);
      });
    } else {
      checkTlsError(err) && notH2.set(key, Date.now());
      pendingItem.forEach(function(list) {
        list[2](socket);
        socket = null;
      });
    }
  });
};
<|endoftext|>


<commit_before>/**
 * @author Jordi Torres
 */

define( [
    'osg/Vec3',
    'osg/Matrix',
    'osgUtil/TriangleIntersector'
], function ( Vec3, Matrix, TriangleIntersector ) {

    'use strict';

    var LineSegmentIntersector = function () {
        this._start = Vec3.create();
        this._end = Vec3.create();
        this._iStart = Vec3.create();
        this._iEnd = Vec3.create();
        this._intersections = [];
    };

    LineSegmentIntersector.prototype = {
        set: function ( start, end ) {
            Vec3.copy( start, this._start );
            Vec3.copy( end, this._end );
        },
        setStart: function ( start ) {
            Vec3.copy( start, this._start );
        },
        setEnd: function ( end ) {
            Vec3.copy( end, this._end );
        },
        reset: function () {
            // Clear the intersections vector
            this._intersections.length = 0;
        },
        enter: function ( node ) {
            // Not working if culling disabled ??
            return !node.isCullingActive() || this.intersects( node.getBound() );
        },
        // Optimized Intersection Segment/Sphere
        // From Real-Time Rendering, by Tomas Akenine-Möller, Eric Haines, and Naty Hoffman. Pages 738-741
        intersects: ( function () {
            var l = Vec3.create();
            return function ( bsphere ) {
                if ( !bsphere.valid() ) return false;
                Vec3.sub( bsphere.center(), this._iStart, l );
                var s = Vec3.dot( l, this._iEnd );
                var l2 = Vec3.length2( l );
                if ( s < 0.0 && l2 > bsphere.radius2() ) return false;
                var m2 = l2 - ( s * s );
                if ( m2 > bsphere.radius2() ) return false;
                return true;
            };
        } )(),

        intersect: function ( iv, node ) {
            var kdtree = node.getShape();
            if ( kdtree ) {
                // Use KDTREES
                return kdtree.intersectRay( this._iStart, this._iEnd, this._intersections, iv.nodePath );
            } else {
                // Use the TriangleIntersector
                var ti = new TriangleIntersector();
                ti.setNodePath( iv.nodePath );
                ti.set( this._iStart, this._iEnd );
                ti.apply( node );
                var l = ti._intersections.length;
                if ( l > 0 ) {
                    // Intersection/s exists
                    for ( var i = 0; i < l; i++ ) {
                        this._intersections.push( ti._intersections[ i ] );
                    }
                    return true;
                }
                // No intersection found
                return false;
            }
            return false;
        },
        getIntersections: function () {
            return this._intersections;
        },
        setCurrentTransformation: function ( matrix ) {
            Matrix.inverse( matrix, matrix );
            Matrix.transformVec3( matrix, this._start, this._iStart );
            Matrix.transformVec3( matrix, this._end, this._iEnd );
        }
    };

    return LineSegmentIntersector;
} );
<commit_msg>Reordered comparations to o do intersection test even faster, credits to Stephane Ginier<commit_after>/**
 * @author Jordi Torres
 */

define( [
    'osg/Vec3',
    'osg/Matrix',
    'osgUtil/TriangleIntersector'
], function ( Vec3, Matrix, TriangleIntersector ) {

    'use strict';

    var LineSegmentIntersector = function () {
        this._start = Vec3.create();
        this._end = Vec3.create();
        this._iStart = Vec3.create();
        this._iEnd = Vec3.create();
        this._intersections = [];
    };

    LineSegmentIntersector.prototype = {
        set: function ( start, end ) {
            Vec3.copy( start, this._start );
            Vec3.copy( end, this._end );
        },
        setStart: function ( start ) {
            Vec3.copy( start, this._start );
        },
        setEnd: function ( end ) {
            Vec3.copy( end, this._end );
        },
        reset: function () {
            // Clear the intersections vector
            this._intersections.length = 0;
        },
        enter: function ( node ) {
            // Not working if culling disabled ??
            return !node.isCullingActive() || this.intersects( node.getBound() );
        },
        // Optimized Intersection Segment/Sphere
        // From Real-Time Rendering, by Tomas Akenine-Möller, Eric Haines, and Naty Hoffman. Pages 738-741
        intersects: ( function () {
            var l = Vec3.create();
            return function ( bsphere ) {
                if ( !bsphere.valid() ) return false;
                Vec3.sub( bsphere.center(), this._iStart, l );
                var l2 = Vec3.length2( l );
                if ( l2 < bsphere.radius2() ) return true;
                var s = Vec3.dot( l, this._iEnd );
                if ( s < 0 ) return false;
                var m2 = l2 - ( s * s );
                if ( m2 > bsphere.radius2() ) return false;
                return true;
            };
        } )(),

        intersect: function ( iv, node ) {
            var kdtree = node.getShape();
            if ( kdtree ) {
                // Use KDTREES
                return kdtree.intersectRay( this._iStart, this._iEnd, this._intersections, iv.nodePath );
            } else {
                // Use the TriangleIntersector
                var ti = new TriangleIntersector();
                ti.setNodePath( iv.nodePath );
                ti.set( this._iStart, this._iEnd );
                ti.apply( node );
                var l = ti._intersections.length;
                if ( l > 0 ) {
                    // Intersection/s exists
                    for ( var i = 0; i < l; i++ ) {
                        this._intersections.push( ti._intersections[ i ] );
                    }
                    return true;
                }
                // No intersection found
                return false;
            }
            return false;
        },
        getIntersections: function () {
            return this._intersections;
        },
        setCurrentTransformation: function ( matrix ) {
            Matrix.inverse( matrix, matrix );
            Matrix.transformVec3( matrix, this._start, this._iStart );
            Matrix.transformVec3( matrix, this._end, this._iEnd );
        }
    };

    return LineSegmentIntersector;
} );
<|endoftext|>


<commit_before>var testacular = require('testacular');

/*global module:false*/
module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-recess');
  grunt.loadNpmTasks('grunt-coffee');

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/**\n' + ' * <%= pkg.description %>\n' + ' * @version v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * @link <%= pkg.homepage %>\n' + ' * @license MIT License, http://www.opensource.org/licenses/MIT\n' + ' */'
    },
    coffee: {
      build: {
        src: ['common/*.coffee', 'modules/**/*.coffee'],
        extension: ".coffee.js"
      }
    },
    concat: {
      basic: {
        src: ['<banner:meta.banner>', 'common/*.js', 'modules/*/*/*.js'],
        dest: 'build/<%= pkg.name %>.js'
      },
      ieshiv: {
        src: ['<banner:meta.banner>', 'common/ieshiv/*.js'],
        dest: 'build/<%= pkg.name %>-ieshiv.js'
      }
    },
    min: {
      basic: {
        src: ['<banner:meta.banner>', '<config:concat.basic.dest>'],
        dest: 'build/<%= pkg.name %>.min.js'
      },
      ieshiv: {
        src: ['<banner:meta.banner>', '<config:concat.ieshiv.dest>'],
        dest: 'build/<%= pkg.name %>-ieshiv.min.js'
      }
    },
    recess: {
      basic: {
        src: 'common/**/*.less',
        dest: 'build/<%= pkg.name %>.css',
        options: {
          compile: true
        }
      },
      min: {
        src: '<config:recess.basic.dest>',
        dest: 'build/<%= pkg.name %>.min.css',
        options: {
          compress: true
        }
      }
    },
    test: {
      files: ['modules/**/test/*.js', 'templates/**/test/*.js']
    },
    lint: {
      files: ['grunt.js', 'common/**/*.js', 'modules/**/*.js']
    },
    watch: {
      files: ['modules/**/*.coffee', 'modules/**/*.js', 'common/**/*.js', 'templates/**/*.js'],
      tasks: 'coffee test'
    }
  });

  // Default task.
  grunt.registerTask('default', 'coffee concat min recess:basic recess:min test');

  grunt.registerTask('server', 'start testacular server', function() {
    //Mark the task as async but never call done, so the server stays up
    var done = this.async();
    testacular.server.start('test/test-config.js');
  });

  grunt.registerTask('test', 'run tests (make sure server task is run first)', function() {
    var done = this.async();
    grunt.utils.spawn({
      cmd: process.platform === 'win32' ? 'testacular-run.cmd' : 'testacular-run',
      args: ['test/test-config.js']
    }, function(error, result, code) {
      if (error) {
        grunt.warn("Make sure the testacular server is online: run `grunt server`.\n"+
          "Also make sure you have a browser open to http://localhost:8080/.\n"+
          error.stdout+error.stderr);
        //the testacular runner somehow modifies the files if it errors(??).
        //this causes grunt's watch task to re-fire itself constantly,
        //unless we wait for a sec
        setTimeout(done, 1000);
      } else {
        grunt.log.write(result.stdout);
        done();
      }
    });
  });
};<commit_msg>Start of grunt custom-builder<commit_after>var testacular = require('testacular');

/*global module:false*/
module.exports = function(grunt) {

  var modules = {};
  grunt.file.recurse('modules', function(abspath, rootdir, subdir, filename) {
    //If numbers / is 1, we know it's first in depth. eg filters/inflector, not filters/inflector/test
    if (subdir.split('/').length == 2) {
      modules[subdir] = grunt.file.expand(rootdir+'/'+subdir+'/*.js');
    }
  });

  grunt.loadNpmTasks('grunt-recess');
  grunt.loadNpmTasks('grunt-coffee');

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/**\n' + ' * <%= pkg.description %>\n' + ' * @version v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * @link <%= pkg.homepage %>\n' + ' * @license MIT License, http://www.opensource.org/licenses/MIT\n' + ' */'
    },
    coffee: {
      build: {
        src: ['common/*.coffee', 'modules/**/*.coffee'],
        extension: ".coffee.js"
      }
    },
    concat: {
      basic: {
        src: ['<banner:meta.banner>', 'common/*.js', 'modules/*/*/*.js'],
        dest: 'build/<%= pkg.name %>.js'
      },
      ieshiv: {
        src: ['<banner:meta.banner>', 'common/ieshiv/*.js'],
        dest: 'build/<%= pkg.name %>-ieshiv.js'
      }
    },
    min: {
      basic: {
        src: ['<banner:meta.banner>', '<config:concat.basic.dest>'],
        dest: 'build/<%= pkg.name %>.min.js'
      },
      ieshiv: {
        src: ['<banner:meta.banner>', '<config:concat.ieshiv.dest>'],
        dest: 'build/<%= pkg.name %>-ieshiv.min.js'
      }
    },
    recess: {
      basic: {
        src: 'common/**/*.less',
        dest: 'build/<%= pkg.name %>.css',
        options: {
          compile: true
        }
      },
      min: {
        src: '<config:recess.basic.dest>',
        dest: 'build/<%= pkg.name %>.min.css',
        options: {
          compress: true
        }
      }
    },
    test: {
      files: ['modules/**/test/*.js', 'templates/**/test/*.js']
    },
    lint: {
      files: ['grunt.js', 'common/**/*.js', 'modules/**/*.js']
    },
    watch: {
      files: ['modules/**/*.coffee', 'modules/**/*.js', 'common/**/*.js', 'templates/**/*.js'],
      tasks: 'coffee concat:basic test'
    }
  });

  // Default task.
  grunt.registerTask('default', 'coffee concat min recess:basic recess:min test');

  grunt.registerTask('server', 'start testacular server', function() {
    //Mark the task as async but never call done, so the server stays up
    var done = this.async();
    testacular.server.start('test/test-config.js');
  });

  grunt.registerTask('test', 'run tests (make sure server task is run first)', function() {
    var done = this.async();
    grunt.utils.spawn({
      cmd: process.platform === 'win32' ? 'testacular-run.cmd' : 'testacular-run',
      args: ['test/test-config.js']
    }, function(error, result, code) {
      if (error) {
        grunt.warn("Make sure the testacular server is online: run `grunt server`.\n"+
          "Also make sure you have a browser open to http://localhost:8080/.\n"+
          error.stdout+error.stderr);
        //the testacular runner somehow modifies the files if it errors(??).
        //this causes grunt's watch task to re-fire itself constantly,
        //unless we wait for a sec
        setTimeout(done, 1000);
      } else {
        grunt.log.write(result.stdout);
        done();
      }
    });
  });

  grunt.registerTask('build', 'Build a custom angular-ui.js', function() {
    var files = ['common/module.js'];

    this.args.forEach(function(moduleName) {
      if (modules[moduleName])
        files = files.concat(modules[moduleName]);
    });
    grunt.file.write('build/custom/angular-ui.js', grunt.helper('concat', files));
  });
};
<|endoftext|>


<commit_before>/*jshint node: true */
module.exports = function( grunt ) {

var
	// files
	coreFiles = [
		"jquery.ui.core.js",
		"jquery.ui.widget.js",
		"jquery.ui.mouse.js",
		"jquery.ui.draggable.js",
		"jquery.ui.droppable.js",
		"jquery.ui.resizable.js",
		"jquery.ui.selectable.js",
		"jquery.ui.sortable.js",
		"jquery.ui.effect.js"
	],

	uiFiles = coreFiles.map(function( file ) {
		return "ui/" + file;
	}).concat( grunt.file.expandFiles( "ui/*.js" ).filter(function( file ) {
		return coreFiles.indexOf( file.substring(3) ) === -1;
	})),

	allI18nFiles = grunt.file.expandFiles( "ui/i18n/*.js" ),

	cssFiles = [
		"core",
		"accordion",
		"autocomplete",
		"button",
		"datepicker",
		"dialog",
		"menu",
		"progressbar",
		"resizable",
		"selectable",
		"slider",
		"spinner",
		"tabs",
		"tooltip",
		"theme"
	].map(function( component ) {
		return "themes/base/jquery.ui." + component + ".css";
	}),

	// minified files
	minify = {
		"dist/jquery-ui.min.js": [ "<banner:meta.bannerAll>", "dist/jquery-ui.js" ],
		"dist/i18n/jquery-ui-i18n.min.js": [ "<banner:meta.bannerI18n>", "dist/i18n/jquery-ui-i18n.js" ]
	},

	minifyCSS = {
		"dist/jquery-ui.min.css": "dist/jquery-ui.css"
	},

	compareFiles = {
		all: [
			"dist/jquery-ui.js",
			"dist/jquery-ui.min.js"
		]
	};

function mapMinFile( file ) {
	return "dist/" + file.replace( /\.js$/, ".min.js" ).replace( /ui\//, "minified/" );
}

uiFiles.concat( allI18nFiles ).forEach(function( file ) {
	minify[ mapMinFile( file ) ] = [ "<banner>", file ];
});

cssFiles.forEach(function( file ) {
	minifyCSS[ "dist/" + file.replace( /\.css$/, ".min.css" ).replace( /themes\/base\//, "themes/base/minified/" ) ] = [ "<banner>", "<strip_all_banners:" + file + ">" ];
});

uiFiles.forEach(function( file ) {
	compareFiles[ file ] = [ file,  mapMinFile( file ) ];
});

// grunt plugins
grunt.loadNpmTasks( "grunt-css" );
grunt.loadNpmTasks( "grunt-html" );
grunt.loadNpmTasks( "grunt-compare-size" );
grunt.loadNpmTasks( "grunt-junit" );
grunt.loadNpmTasks( "grunt-git-authors" );
// local testswarm and build tasks
grunt.loadTasks( "build/tasks" );

grunt.registerHelper( "strip_all_banners", function( filepath ) {
	return grunt.file.read( filepath ).replace( /^\s*\/\*[\s\S]*?\*\/\s*/g, "" );
});

function stripBanner( files ) {
	return files.map(function( file ) {
		return "<strip_all_banners:" + file + ">";
	});
}

function stripDirectory( file ) {
	// TODO: we're receiving the directive, so we need to strip the trailing >
	// we should be receving a clean path without the directive
	return file.replace( /.+\/(.+?)>?$/, "$1" );
}
// allow access from banner template
global.stripDirectory = stripDirectory;

function createBanner( files ) {
	// strip folders
	var fileNames = files && files.map( stripDirectory );
	return "/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - " +
		"<%= grunt.template.today('isoDate') %>\n" +
		"<%= pkg.homepage ? '* ' + pkg.homepage + '\n' : '' %>" +
		"* Includes: " + (files ? fileNames.join(", ") : "<%= stripDirectory(grunt.task.current.file.src[1]) %>") + "\n" +
		"* Copyright <%= grunt.template.today('yyyy') %> <%= pkg.author.name %>;" +
		" Licensed <%= _.pluck(pkg.licenses, 'type').join(', ') %> */";
}

grunt.initConfig({
	pkg: "<json:package.json>",
	files: {
		dist: "<%= pkg.name %>-<%= pkg.version %>",
		cdn: "<%= pkg.name %>-<%= pkg.version %>-cdn",
		themes: "<%= pkg.name %>-themes-<%= pkg.version %>"
	},
	meta: {
		banner: createBanner(),
		bannerAll: createBanner( uiFiles ),
		bannerI18n: createBanner( allI18nFiles ),
		bannerCSS: createBanner( cssFiles )
	},
	compare_size: compareFiles,
	concat: {
		ui: {
			src: [ "<banner:meta.bannerAll>", stripBanner( uiFiles ) ],
			dest: "dist/jquery-ui.js"
		},
		i18n: {
			src: [ "<banner:meta.bannerI18n>", allI18nFiles ],
			dest: "dist/i18n/jquery-ui-i18n.js"
		},
		css: {
			src: [ "<banner:meta.bannerCSS>", stripBanner( cssFiles ) ],
			dest: "dist/jquery-ui.css"
		}
	},
	min: minify,
	cssmin: minifyCSS,
	htmllint: {
		// ignore files that contain invalid html, used only for ajax content testing
		all: grunt.file.expand( [ "demos/**/*.html", "tests/**/*.html" ] ).filter(function( file ) {
			return !/(?:ajax\/content\d\.html|tabs\/data\/test\.html|tests\/unit\/core\/core\.html)/.test( file );
		})
	},
	copy: {
		dist: {
			src: [
				"AUTHORS.txt",
				"jquery-*.js",
				"MIT-LICENSE.txt",
				"README.md",
				"grunt.js",
				"package.json",
				"*.jquery.json",
				"ui/**/*",
				"ui/.jshintrc",
				"demos/**/*",
				"themes/**/*",
				"external/**/*",
				"tests/**/*"
			],
			renames: {
				"dist/jquery-ui.js": "ui/jquery-ui.js",
				"dist/jquery-ui.min.js": "ui/minified/jquery-ui.min.js",
				"dist/i18n/jquery-ui-i18n.js": "ui/i18n/jquery-ui-i18n.js",
				"dist/i18n/jquery-ui-i18n.min.js": "ui/minified/i18n/jquery-ui-i18n.min.js",
				"dist/jquery-ui.css": "themes/base/jquery-ui.css",
				"dist/jquery-ui.min.css": "themes/base/minified/jquery-ui.min.css"
			},
			dest: "dist/<%= files.dist %>"
		},
		dist_min: {
			src: "dist/minified/**/*",
			strip: /^dist/,
			dest: "dist/<%= files.dist %>/ui"
		},
		dist_css_min: {
			src: "dist/themes/base/minified/*.css",
			strip: /^dist/,
			dest: "dist/<%= files.dist %>"
		},
		dist_units_images: {
			src: "themes/base/images/*",
			strip: /^themes\/base\//,
			dest: "dist/"
		},
		dist_min_images: {
			src: "themes/base/images/*",
			strip: /^themes\/base\//,
			dest: "dist/<%= files.dist %>/themes/base/minified"
		},
		cdn: {
			src: [
				"AUTHORS.txt",
				"MIT-LICENSE.txt",
				"ui/*.js",
				"package.json"
			],
			renames: {
				"dist/jquery-ui.js": "jquery-ui.js",
				"dist/jquery-ui.min.js": "jquery-ui.min.js",
				"dist/i18n/jquery-ui-i18n.js": "i18n/jquery-ui-i18n.js",
				"dist/i18n/jquery-ui-i18n.min.js": "i18n/jquery-ui-i18n.min.js",
				"dist/jquery-ui.css": "themes/base/jquery-ui.css",
				"dist/jquery-ui.min.css": "themes/base/minified/jquery-ui.min.css"
			},
			dest: "dist/<%= files.cdn %>"
		},
		cdn_i18n: {
			src: "ui/i18n/jquery.ui.datepicker-*.js",
			strip: "ui/",
			dest: "dist/<%= files.cdn %>"
		},
		cdn_i18n_min: {
			src: "dist/minified/i18n/jquery.ui.datepicker-*.js",
			strip: "dist/minified",
			dest: "dist/<%= files.cdn %>"
		},
		cdn_min: {
			src: "dist/minified/*.js",
			strip: /^dist\/minified/,
			dest: "dist/<%= files.cdn %>/ui"
		},
		cdn_min_images: {
			src: "themes/base/images/*",
			strip: /^themes\/base\//,
			dest: "dist/<%= files.cdn %>/themes/base/minified"
		},
		cdn_themes: {
			src: "dist/<%= files.themes %>/themes/**/*",
			strip: "dist/<%= files.themes %>",
			dest: "dist/<%= files.cdn %>"
		},
		themes: {
			src: [
				"AUTHORS.txt",
				"MIT-LICENSE.txt",
				"package.json"
			],
			dest: "dist/<%= files.themes %>"
		}
	},
	zip: {
		dist: {
			src: "<%= files.dist %>",
			dest: "<%= files.dist %>.zip"
		},
		cdn: {
			src: "<%= files.cdn %>",
			dest: "<%= files.cdn %>.zip"
		},
		themes: {
			src: "<%= files.themes %>",
			dest: "<%= files.themes %>.zip"
		}
	},
	md5: {
		dist: {
			src: "dist/<%= files.dist %>",
			dest: "dist/<%= files.dist %>/MANIFEST"
		},
		cdn: {
			src: "dist/<%= files.cdn %>",
			dest: "dist/<%= files.cdn %>/MANIFEST"
		},
		themes: {
			src: "dist/<%= files.themes %>",
			dest: "dist/<%= files.themes %>/MANIFEST"
		}
	},
	qunit: {
		files: grunt.file.expandFiles( "tests/unit/**/*.html" ).filter(function( file ) {
			// disabling everything that doesn't (quite) work with PhantomJS for now
			// TODO except for all|index|test, try to include more as we go
			return !( /(all|all-active|index|test|draggable|droppable|selectable|resizable|sortable|dialog|slider|datepicker|tabs|tabs_deprecated)\.html$/ ).test( file );
		})
	},
	lint: {
		ui: grunt.file.expandFiles( "ui/*.js" ).filter(function( file ) {
			// TODO remove items from this list once rewritten
			return !( /(mouse|datepicker|draggable|droppable|resizable|selectable|sortable)\.js$/ ).test( file );
		}),
		grunt: [ "grunt.js", "build/**/*.js" ],
		tests: "tests/unit/**/*.js"
	},
	csslint: {
		// nothing: []
		// TODO figure out what to check for, then fix and enable
		base_theme: {
			src: grunt.file.expandFiles( "themes/base/*.css" ).filter(function( file ) {
				// TODO remove items from this list once rewritten
				return !( /(button|datepicker|core|dialog|theme)\.css$/ ).test( file );
			}),
			// TODO consider reenabling some of these rules
			rules: {
				"import": false,
				"important": false,
				"outline-none": false,
				// especially this one
				"overqualified-elements": false
			}
		}
	},
	jshint: (function() {
		function parserc( path ) {
			var rc = grunt.file.readJSON( (path || "") + ".jshintrc" ),
				settings = {
					options: rc,
					globals: {}
				};

			(rc.predef || []).forEach(function( prop ) {
				settings.globals[ prop ] = true;
			});
			delete rc.predef;

			return settings;
		}

		return {
			// TODO: use "faux strict mode" https://github.com/jshint/jshint/issues/504
			// TODO: limit `smarttabs` to multi-line comments https://github.com/jshint/jshint/issues/503
			options: parserc(),
			ui: parserc( "ui/" ),
			// TODO: `evil: true` is only for document.write() https://github.com/jshint/jshint/issues/519
			// TODO: don't create so many globals in tests
			tests: parserc( "tests/" )
		};
	})()
});

grunt.registerTask( "default", "lint csslint htmllint qunit" );
grunt.registerTask( "sizer", "concat:ui min:dist/jquery-ui.min.js compare_size:all" );
grunt.registerTask( "sizer_all", "concat:ui min compare_size" );
grunt.registerTask( "build", "concat min cssmin copy:dist_units_images" );
grunt.registerTask( "release", "clean build copy:dist copy:dist_min copy:dist_min_images copy:dist_css_min md5:dist zip:dist" );
grunt.registerTask( "release_themes", "release generate_themes copy:themes md5:themes zip:themes" );
grunt.registerTask( "release_cdn", "release_themes copy:cdn copy:cdn_min copy:cdn_i18n copy:cdn_i18n_min copy:cdn_min_images copy:cdn_themes md5:cdn zip:cdn" );

};
<commit_msg>Grunt: Removed tooltip tests from qunit task.<commit_after>/*jshint node: true */
module.exports = function( grunt ) {

var
	// files
	coreFiles = [
		"jquery.ui.core.js",
		"jquery.ui.widget.js",
		"jquery.ui.mouse.js",
		"jquery.ui.draggable.js",
		"jquery.ui.droppable.js",
		"jquery.ui.resizable.js",
		"jquery.ui.selectable.js",
		"jquery.ui.sortable.js",
		"jquery.ui.effect.js"
	],

	uiFiles = coreFiles.map(function( file ) {
		return "ui/" + file;
	}).concat( grunt.file.expandFiles( "ui/*.js" ).filter(function( file ) {
		return coreFiles.indexOf( file.substring(3) ) === -1;
	})),

	allI18nFiles = grunt.file.expandFiles( "ui/i18n/*.js" ),

	cssFiles = [
		"core",
		"accordion",
		"autocomplete",
		"button",
		"datepicker",
		"dialog",
		"menu",
		"progressbar",
		"resizable",
		"selectable",
		"slider",
		"spinner",
		"tabs",
		"tooltip",
		"theme"
	].map(function( component ) {
		return "themes/base/jquery.ui." + component + ".css";
	}),

	// minified files
	minify = {
		"dist/jquery-ui.min.js": [ "<banner:meta.bannerAll>", "dist/jquery-ui.js" ],
		"dist/i18n/jquery-ui-i18n.min.js": [ "<banner:meta.bannerI18n>", "dist/i18n/jquery-ui-i18n.js" ]
	},

	minifyCSS = {
		"dist/jquery-ui.min.css": "dist/jquery-ui.css"
	},

	compareFiles = {
		all: [
			"dist/jquery-ui.js",
			"dist/jquery-ui.min.js"
		]
	};

function mapMinFile( file ) {
	return "dist/" + file.replace( /\.js$/, ".min.js" ).replace( /ui\//, "minified/" );
}

uiFiles.concat( allI18nFiles ).forEach(function( file ) {
	minify[ mapMinFile( file ) ] = [ "<banner>", file ];
});

cssFiles.forEach(function( file ) {
	minifyCSS[ "dist/" + file.replace( /\.css$/, ".min.css" ).replace( /themes\/base\//, "themes/base/minified/" ) ] = [ "<banner>", "<strip_all_banners:" + file + ">" ];
});

uiFiles.forEach(function( file ) {
	compareFiles[ file ] = [ file,  mapMinFile( file ) ];
});

// grunt plugins
grunt.loadNpmTasks( "grunt-css" );
grunt.loadNpmTasks( "grunt-html" );
grunt.loadNpmTasks( "grunt-compare-size" );
grunt.loadNpmTasks( "grunt-junit" );
grunt.loadNpmTasks( "grunt-git-authors" );
// local testswarm and build tasks
grunt.loadTasks( "build/tasks" );

grunt.registerHelper( "strip_all_banners", function( filepath ) {
	return grunt.file.read( filepath ).replace( /^\s*\/\*[\s\S]*?\*\/\s*/g, "" );
});

function stripBanner( files ) {
	return files.map(function( file ) {
		return "<strip_all_banners:" + file + ">";
	});
}

function stripDirectory( file ) {
	// TODO: we're receiving the directive, so we need to strip the trailing >
	// we should be receving a clean path without the directive
	return file.replace( /.+\/(.+?)>?$/, "$1" );
}
// allow access from banner template
global.stripDirectory = stripDirectory;

function createBanner( files ) {
	// strip folders
	var fileNames = files && files.map( stripDirectory );
	return "/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - " +
		"<%= grunt.template.today('isoDate') %>\n" +
		"<%= pkg.homepage ? '* ' + pkg.homepage + '\n' : '' %>" +
		"* Includes: " + (files ? fileNames.join(", ") : "<%= stripDirectory(grunt.task.current.file.src[1]) %>") + "\n" +
		"* Copyright <%= grunt.template.today('yyyy') %> <%= pkg.author.name %>;" +
		" Licensed <%= _.pluck(pkg.licenses, 'type').join(', ') %> */";
}

grunt.initConfig({
	pkg: "<json:package.json>",
	files: {
		dist: "<%= pkg.name %>-<%= pkg.version %>",
		cdn: "<%= pkg.name %>-<%= pkg.version %>-cdn",
		themes: "<%= pkg.name %>-themes-<%= pkg.version %>"
	},
	meta: {
		banner: createBanner(),
		bannerAll: createBanner( uiFiles ),
		bannerI18n: createBanner( allI18nFiles ),
		bannerCSS: createBanner( cssFiles )
	},
	compare_size: compareFiles,
	concat: {
		ui: {
			src: [ "<banner:meta.bannerAll>", stripBanner( uiFiles ) ],
			dest: "dist/jquery-ui.js"
		},
		i18n: {
			src: [ "<banner:meta.bannerI18n>", allI18nFiles ],
			dest: "dist/i18n/jquery-ui-i18n.js"
		},
		css: {
			src: [ "<banner:meta.bannerCSS>", stripBanner( cssFiles ) ],
			dest: "dist/jquery-ui.css"
		}
	},
	min: minify,
	cssmin: minifyCSS,
	htmllint: {
		// ignore files that contain invalid html, used only for ajax content testing
		all: grunt.file.expand( [ "demos/**/*.html", "tests/**/*.html" ] ).filter(function( file ) {
			return !/(?:ajax\/content\d\.html|tabs\/data\/test\.html|tests\/unit\/core\/core\.html)/.test( file );
		})
	},
	copy: {
		dist: {
			src: [
				"AUTHORS.txt",
				"jquery-*.js",
				"MIT-LICENSE.txt",
				"README.md",
				"grunt.js",
				"package.json",
				"*.jquery.json",
				"ui/**/*",
				"ui/.jshintrc",
				"demos/**/*",
				"themes/**/*",
				"external/**/*",
				"tests/**/*"
			],
			renames: {
				"dist/jquery-ui.js": "ui/jquery-ui.js",
				"dist/jquery-ui.min.js": "ui/minified/jquery-ui.min.js",
				"dist/i18n/jquery-ui-i18n.js": "ui/i18n/jquery-ui-i18n.js",
				"dist/i18n/jquery-ui-i18n.min.js": "ui/minified/i18n/jquery-ui-i18n.min.js",
				"dist/jquery-ui.css": "themes/base/jquery-ui.css",
				"dist/jquery-ui.min.css": "themes/base/minified/jquery-ui.min.css"
			},
			dest: "dist/<%= files.dist %>"
		},
		dist_min: {
			src: "dist/minified/**/*",
			strip: /^dist/,
			dest: "dist/<%= files.dist %>/ui"
		},
		dist_css_min: {
			src: "dist/themes/base/minified/*.css",
			strip: /^dist/,
			dest: "dist/<%= files.dist %>"
		},
		dist_units_images: {
			src: "themes/base/images/*",
			strip: /^themes\/base\//,
			dest: "dist/"
		},
		dist_min_images: {
			src: "themes/base/images/*",
			strip: /^themes\/base\//,
			dest: "dist/<%= files.dist %>/themes/base/minified"
		},
		cdn: {
			src: [
				"AUTHORS.txt",
				"MIT-LICENSE.txt",
				"ui/*.js",
				"package.json"
			],
			renames: {
				"dist/jquery-ui.js": "jquery-ui.js",
				"dist/jquery-ui.min.js": "jquery-ui.min.js",
				"dist/i18n/jquery-ui-i18n.js": "i18n/jquery-ui-i18n.js",
				"dist/i18n/jquery-ui-i18n.min.js": "i18n/jquery-ui-i18n.min.js",
				"dist/jquery-ui.css": "themes/base/jquery-ui.css",
				"dist/jquery-ui.min.css": "themes/base/minified/jquery-ui.min.css"
			},
			dest: "dist/<%= files.cdn %>"
		},
		cdn_i18n: {
			src: "ui/i18n/jquery.ui.datepicker-*.js",
			strip: "ui/",
			dest: "dist/<%= files.cdn %>"
		},
		cdn_i18n_min: {
			src: "dist/minified/i18n/jquery.ui.datepicker-*.js",
			strip: "dist/minified",
			dest: "dist/<%= files.cdn %>"
		},
		cdn_min: {
			src: "dist/minified/*.js",
			strip: /^dist\/minified/,
			dest: "dist/<%= files.cdn %>/ui"
		},
		cdn_min_images: {
			src: "themes/base/images/*",
			strip: /^themes\/base\//,
			dest: "dist/<%= files.cdn %>/themes/base/minified"
		},
		cdn_themes: {
			src: "dist/<%= files.themes %>/themes/**/*",
			strip: "dist/<%= files.themes %>",
			dest: "dist/<%= files.cdn %>"
		},
		themes: {
			src: [
				"AUTHORS.txt",
				"MIT-LICENSE.txt",
				"package.json"
			],
			dest: "dist/<%= files.themes %>"
		}
	},
	zip: {
		dist: {
			src: "<%= files.dist %>",
			dest: "<%= files.dist %>.zip"
		},
		cdn: {
			src: "<%= files.cdn %>",
			dest: "<%= files.cdn %>.zip"
		},
		themes: {
			src: "<%= files.themes %>",
			dest: "<%= files.themes %>.zip"
		}
	},
	md5: {
		dist: {
			src: "dist/<%= files.dist %>",
			dest: "dist/<%= files.dist %>/MANIFEST"
		},
		cdn: {
			src: "dist/<%= files.cdn %>",
			dest: "dist/<%= files.cdn %>/MANIFEST"
		},
		themes: {
			src: "dist/<%= files.themes %>",
			dest: "dist/<%= files.themes %>/MANIFEST"
		}
	},
	qunit: {
		files: grunt.file.expandFiles( "tests/unit/**/*.html" ).filter(function( file ) {
			// disabling everything that doesn't (quite) work with PhantomJS for now
			// TODO except for all|index|test, try to include more as we go
			return !( /(all|all-active|index|test|draggable|droppable|selectable|resizable|sortable|dialog|slider|datepicker|tabs|tabs_deprecated|tooltip)\.html$/ ).test( file );
		})
	},
	lint: {
		ui: grunt.file.expandFiles( "ui/*.js" ).filter(function( file ) {
			// TODO remove items from this list once rewritten
			return !( /(mouse|datepicker|draggable|droppable|resizable|selectable|sortable)\.js$/ ).test( file );
		}),
		grunt: [ "grunt.js", "build/**/*.js" ],
		tests: "tests/unit/**/*.js"
	},
	csslint: {
		// nothing: []
		// TODO figure out what to check for, then fix and enable
		base_theme: {
			src: grunt.file.expandFiles( "themes/base/*.css" ).filter(function( file ) {
				// TODO remove items from this list once rewritten
				return !( /(button|datepicker|core|dialog|theme)\.css$/ ).test( file );
			}),
			// TODO consider reenabling some of these rules
			rules: {
				"import": false,
				"important": false,
				"outline-none": false,
				// especially this one
				"overqualified-elements": false
			}
		}
	},
	jshint: (function() {
		function parserc( path ) {
			var rc = grunt.file.readJSON( (path || "") + ".jshintrc" ),
				settings = {
					options: rc,
					globals: {}
				};

			(rc.predef || []).forEach(function( prop ) {
				settings.globals[ prop ] = true;
			});
			delete rc.predef;

			return settings;
		}

		return {
			// TODO: use "faux strict mode" https://github.com/jshint/jshint/issues/504
			// TODO: limit `smarttabs` to multi-line comments https://github.com/jshint/jshint/issues/503
			options: parserc(),
			ui: parserc( "ui/" ),
			// TODO: `evil: true` is only for document.write() https://github.com/jshint/jshint/issues/519
			// TODO: don't create so many globals in tests
			tests: parserc( "tests/" )
		};
	})()
});

grunt.registerTask( "default", "lint csslint htmllint qunit" );
grunt.registerTask( "sizer", "concat:ui min:dist/jquery-ui.min.js compare_size:all" );
grunt.registerTask( "sizer_all", "concat:ui min compare_size" );
grunt.registerTask( "build", "concat min cssmin copy:dist_units_images" );
grunt.registerTask( "release", "clean build copy:dist copy:dist_min copy:dist_min_images copy:dist_css_min md5:dist zip:dist" );
grunt.registerTask( "release_themes", "release generate_themes copy:themes md5:themes zip:themes" );
grunt.registerTask( "release_cdn", "release_themes copy:cdn copy:cdn_min copy:cdn_i18n copy:cdn_i18n_min copy:cdn_min_images copy:cdn_themes md5:cdn zip:cdn" );

};
<|endoftext|>


<commit_before>// Friendly interval
// Initialize once, then start, stop & restart with single calls

'use strict';

var ee    = require('event-emitter')
  , ntick = require('./next-tick');

var o = ee({
	init: function (i, start) {
		this.f = this.emit.bind(this, 'tick');
		this.i = i;
		if (start) {
			ntick(this.start.bind(this));
		}
		return this;
	},
	start: function () {
		if (!this.t) {
			this.t = setInterval(this.f, this.i);
			this.running = true;
			this.emit('start');
		}
	},
	stop: function () {
		if (this.t) {
			clearInterval(this.t);
			this.t = null;
			this.running = false;
			this.emit('stop');
		}
	},
	restart: function () {
		this.stop();
		this.start();
	}
});

module.exports = function (i, start) {
	return Object.create(o).init(i, start);
};
<commit_msg>Automatic start now immediate<commit_after>// Friendly interval
// Initialize once, then start, stop & restart with single calls

'use strict';

var ee    = require('event-emitter')
  , ntick = require('./next-tick');

var o = ee({
	init: function (i, start) {
		this.f = this.emit.bind(this, 'tick');
		this.i = i;
		this.start.bind(this);
		return this;
	},
	start: function () {
		if (!this.t) {
			this.t = setInterval(this.f, this.i);
			this.running = true;
			this.emit('start');
		}
	},
	stop: function () {
		if (this.t) {
			clearInterval(this.t);
			this.t = null;
			this.running = false;
			this.emit('stop');
		}
	},
	restart: function () {
		this.stop();
		this.start();
	}
});

module.exports = function (i, start) {
	return Object.create(o).init(i, start);
};
<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {

  'use strict';

  // Project configuration.
  grunt.initConfig({
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'specs/**/*.js']
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint jasmine'
    },
    dojo: {
      frozen: {
        dojo: 'deps/dojo/dojo.js',
        profile: 'frozen.profile.js',
        'package': './',
        dojoConfig: 'dojoConfig.js',
        cwd: './'
      }
    },
    jsdoc: {
      dist: {
        src: ['src/**/*.js'],
        dest: 'doc'
      }
    },
    jasmine: {
      src: 'src/**/*.js',
      specs: 'specs/**/*Spec.js',
      amd: true,
      helpers: [
        'dojoConfig.js',
        'deps/dojo/dojo.js'
      ],
      timeout: 10000,
      phatomjs: {
        'ignore-ssl-errors': true
      }
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        undef: true,
        boss: true,
        es5: true,
        strict: true,
        trailing: true,
        loopfunc: true,
        // Enviroments
        browser: true,
        devel: true
      },
      globals: {
        define: true,
        require: true,
        Box2D: true,
        expect: true,
        describe: true,
        it: true
      }
    }
  });

  grunt.loadNpmTasks('grunt-dojo');

  grunt.loadNpmTasks('grunt-jsdoc-plugin');

  grunt.loadNpmTasks('grunt-jasmine-runner');

  // Default task.
  grunt.registerTask('default', 'lint test');

};
<commit_msg>remove test from default grunt task, replace with jasmine<commit_after>/*global module:false*/
module.exports = function(grunt) {

  'use strict';

  // Project configuration.
  grunt.initConfig({
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'specs/**/*.js']
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'lint jasmine'
    },
    dojo: {
      frozen: {
        dojo: 'deps/dojo/dojo.js',
        profile: 'frozen.profile.js',
        'package': './',
        dojoConfig: 'dojoConfig.js',
        cwd: './'
      }
    },
    jsdoc: {
      dist: {
        src: ['src/**/*.js'],
        dest: 'doc'
      }
    },
    jasmine: {
      src: 'src/**/*.js',
      specs: 'specs/**/*Spec.js',
      amd: true,
      helpers: [
        'dojoConfig.js',
        'deps/dojo/dojo.js'
      ],
      timeout: 10000,
      phatomjs: {
        'ignore-ssl-errors': true
      }
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        undef: true,
        boss: true,
        es5: true,
        strict: true,
        trailing: true,
        loopfunc: true,
        // Enviroments
        browser: true,
        devel: true
      },
      globals: {
        define: true,
        require: true,
        Box2D: true,
        expect: true,
        describe: true,
        it: true
      }
    }
  });

  grunt.loadNpmTasks('grunt-dojo');

  grunt.loadNpmTasks('grunt-jsdoc-plugin');

  grunt.loadNpmTasks('grunt-jasmine-runner');

  // Default task.
  grunt.registerTask('default', 'lint jasmine');

};
<|endoftext|>


<commit_before>module.exports = interval;

// NOTE: just a stub for now, implimentation coming soon

// take an object that specifies a number of hours and return milliseconds
function interval(obj) {
  var days = obj.days || 0;
  var hours = obj.hours || 0;
  var minutes = obj.minutes || 0;
  var seconds = obj.seconds || 0;
  var milliseconds = obj.milliseconds || 0;

  hours += days * 24;
  minutes += hours * 60;
  seconds += minutes * 60;
  milliseconds += seconds * 1000;

  return milliseconds;
}

var properties = ['days', 'hours', 'minutes', 'seconds', 'milliseconds'];

interval.stringify = function (obj) {
  var result = [];

  properties.forEach(function (property) {
    if (obj[property]) {
      result.push(obj[property].toString() + ' ' + property);
    }
  });

  return result.join(', ');
}

interval.parse = function (s) {
  throw new Error('not implimented');
}
<commit_msg>[style] add semicolons after function literals<commit_after>module.exports = interval;

// NOTE: just a stub for now, implimentation coming soon

// take an object that specifies a number of hours and return milliseconds
function interval(obj) {
  var days = obj.days || 0;
  var hours = obj.hours || 0;
  var minutes = obj.minutes || 0;
  var seconds = obj.seconds || 0;
  var milliseconds = obj.milliseconds || 0;

  hours += days * 24;
  minutes += hours * 60;
  seconds += minutes * 60;
  milliseconds += seconds * 1000;

  return milliseconds;
}

var properties = ['days', 'hours', 'minutes', 'seconds', 'milliseconds'];

interval.stringify = function (obj) {
  var result = [];

  properties.forEach(function (property) {
    if (obj[property]) {
      result.push(obj[property].toString() + ' ' + property);
    }
  });

  return result.join(', ');
};

interval.parse = function (s) {
  throw new Error('not implimented');
};
<|endoftext|>


<commit_before>var _ = require('underscore');
var fs = require('fs');

// Haha, this is so tricky. so we have a template for index.html to stick
// in the hashed JS and style files -- that template also contains
// templates used in the app. in order to avoid evaluating those
// templates, we change the regexes so we can effectively nest templates
_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
_.templateSettings.escape = /\{\{\{(.*?)\}\}\}/g;
_.templateSettings.evaluate = /\{\{-(.*?)\}\}/g;

// precompile for speed
var indexFile = fs.readFileSync('src/template.index.html').toString();
var indexTemplate = _.template(indexFile);

/*global module:false*/
module.exports = function(grunt) {
  // eventually have sound...?
  grunt.registerTask('compliment', 'Stay motivated!', function() {
    var defaults = ['Awesome!!'];

    var compliments = grunt.config('compliment.compliments') || defaults;
    var index = Math.floor(Math.random() * compliments.length);

    grunt.log.writeln(compliments[index]);
  });

  grunt.registerTask('buildIndex', 'stick in hashed resources', function() {
    grunt.log.writeln('Building index...');

    // first find the one in here that we want
    var buildFiles = fs.readdirSync('build');

    var hashedMinFile;
    if (buildFiles.length == 2) {
      grunt.log.writeln('Assuming debug mode wanted');
      hashedMinFile = 'bundle.js';
    }
    var jsRegex = /bundle\.min\.\w+\.js/;
    _.each(buildFiles, function(jsFile) {
      if (jsRegex.test(jsFile)) {
        if (hashedMinFile) {
          throw new Error('more than one hashed file: ' + jsFile + hashedMinFile);
        }
        hashedMinFile = jsFile;
      }
    });
    if (!hashedMinFile) { throw new Error('no hashed min file found!'); }

    grunt.log.writeln('Found hashed js file: ' + hashedMinFile);

    var styleRegex = /main\.\w+\.css/;
    var hashedStyleFile;
    _.each(buildFiles, function(styleFile) {
      if (styleRegex.test(styleFile)) {
        if (hashedStyleFile) {
          throw new Error('more than one hashed style: ' + styleFile + hashedStyleFile);
        }
        hashedStyleFile = styleFile;
      }
    });
    if (!hashedStyleFile) { throw new Error('no style found'); }

    grunt.log.writeln('Found hashed style file: ' + hashedStyleFile);

    // output these filenames to our index template
    var outputIndex = indexTemplate({
      jsFile: hashedMinFile,
      styleFile: hashedStyleFile
    });
    fs.writeFileSync('index.html', outputIndex);
  });

  grunt.initConfig({
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'spec/*.js']
    },
    compliment: {
      compliments: [
        "Wow peter great work!",
        "Such a professional dev environment",
        "Can't stop the TRAIN",
        "git raging"
      ]
    },
    hash: {
      src: ['build/bundle.min.js', 'src/style/main.css'],
      dest: 'build/'
    },
    jasmine_node: {
      specNameMatcher: 'spec', // load only specs containing specNameMatcher
      projectRoot: '.',
      forceExit: true,
      verbose: true
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'watching'
    },
    min: {
      dist: {
        src: ['build/bundle.js'],
        dest: 'build/bundle.min.js'
      }
    },
    rm: {
      build: 'build/*'
    },
    shell: {
      gitAdd: {
        command: 'git add build/'
      }
    },
    jshint: {
      options: {
        curly: true,
        // sometimes triple equality is just redundant and unnecessary
        eqeqeq: false,
        // i know my regular expressions
        regexp: false,
        // i think it's super weird to not use new on a constructor
        nonew: false,
        // these latedefs are just annoying -- no pollution of global scope
        latedef: false,
        // use this in mocks
        forin: false,
        ///////////////////////////////
        // All others are true
        //////////////////////////////
        immed: true,
        newcap: true,
        noarg: true,
        bitwise: true,
        sub: true,
        undef: true,
        unused: false,
        trailing: true,
        devel: true,
        jquery: true,
        nonstandard: true,
        boss: true,
        eqnull: true,
        browser: true,
        debug: true
      },
      globals: {
        Raphael: true,
        require: true,
        console: true,
        describe: true,
        expect: true,
        it: true,
        exports: true,
        process: true
      }
    },
    browserify: {
      'build/bundle.js': {
        entries: ['src/**/*.js', 'src/js/**/*.js']
        //prepend: ['<banner:meta.banner>'],
      }
    }
  });

  // all my npm helpers
  grunt.loadNpmTasks('grunt-jslint');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-jasmine-node');
  grunt.loadNpmTasks('grunt-hash');
  grunt.loadNpmTasks('grunt-rm');
  grunt.loadNpmTasks('grunt-shell');

  grunt.registerTask('build', 'rm browserify min hash buildIndex shell');
  grunt.registerTask('fastBuild', 'rm browserify hash buildIndex shell');

  grunt.registerTask('default', 'lint jasmine_node build compliment');

  grunt.registerTask('watching', 'fastBuild lint');
  grunt.registerTask('test', 'jasmine_node');
};

<commit_msg>sweet lintStrings working<commit_after>var _ = require('underscore');
var fs = require('fs');

// Haha, this is so tricky. so we have a template for index.html to stick
// in the hashed JS and style files -- that template also contains
// templates used in the app. in order to avoid evaluating those
// templates, we change the regexes so we can effectively nest templates
_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
_.templateSettings.escape = /\{\{\{(.*?)\}\}\}/g;
_.templateSettings.evaluate = /\{\{-(.*?)\}\}/g;

// precompile for speed
var indexFile = fs.readFileSync('src/template.index.html').toString();
var indexTemplate = _.template(indexFile);

/*global module:false*/
module.exports = function(grunt) {
  // eventually have sound...?
  grunt.registerTask('compliment', 'Stay motivated!', function() {
    var defaults = ['Awesome!!'];

    var compliments = grunt.config('compliment.compliments') || defaults;
    var index = Math.floor(Math.random() * compliments.length);

    grunt.log.writeln(compliments[index]);
  });

  grunt.registerTask('lintStrings', 'Find if an INTL string doesnt exist', function() {
    var child_process = require('child_process');
    var output = child_process.exec('node src/js/intl/checkStrings', function(err, output) {
      grunt.log.writeln(output);
    });
  });

  grunt.registerTask('buildIndex', 'stick in hashed resources', function() {
    grunt.log.writeln('Building index...');

    // first find the one in here that we want
    var buildFiles = fs.readdirSync('build');

    var hashedMinFile;
    if (buildFiles.length == 2) {
      grunt.log.writeln('Assuming debug mode wanted');
      hashedMinFile = 'bundle.js';
    }
    var jsRegex = /bundle\.min\.\w+\.js/;
    _.each(buildFiles, function(jsFile) {
      if (jsRegex.test(jsFile)) {
        if (hashedMinFile) {
          throw new Error('more than one hashed file: ' + jsFile + hashedMinFile);
        }
        hashedMinFile = jsFile;
      }
    });
    if (!hashedMinFile) { throw new Error('no hashed min file found!'); }

    grunt.log.writeln('Found hashed js file: ' + hashedMinFile);

    var styleRegex = /main\.\w+\.css/;
    var hashedStyleFile;
    _.each(buildFiles, function(styleFile) {
      if (styleRegex.test(styleFile)) {
        if (hashedStyleFile) {
          throw new Error('more than one hashed style: ' + styleFile + hashedStyleFile);
        }
        hashedStyleFile = styleFile;
      }
    });
    if (!hashedStyleFile) { throw new Error('no style found'); }

    grunt.log.writeln('Found hashed style file: ' + hashedStyleFile);

    // output these filenames to our index template
    var outputIndex = indexTemplate({
      jsFile: hashedMinFile,
      styleFile: hashedStyleFile
    });
    fs.writeFileSync('index.html', outputIndex);
  });

  grunt.initConfig({
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'spec/*.js']
    },
    compliment: {
      compliments: [
        "Wow peter great work!",
        "Such a professional dev environment",
        "Can't stop the TRAIN",
        "git raging"
      ]
    },
    hash: {
      src: ['build/bundle.min.js', 'src/style/main.css'],
      dest: 'build/'
    },
    jasmine_node: {
      specNameMatcher: 'spec', // load only specs containing specNameMatcher
      projectRoot: '.',
      forceExit: true,
      verbose: true
    },
    watch: {
      files: '<config:lint.files>',
      tasks: 'watching'
    },
    min: {
      dist: {
        src: ['build/bundle.js'],
        dest: 'build/bundle.min.js'
      }
    },
    rm: {
      build: 'build/*'
    },
    shell: {
      gitAdd: {
        command: 'git add build/'
      }
    },
    jshint: {
      options: {
        curly: true,
        // sometimes triple equality is just redundant and unnecessary
        eqeqeq: false,
        // i know my regular expressions
        regexp: false,
        // i think it's super weird to not use new on a constructor
        nonew: false,
        // these latedefs are just annoying -- no pollution of global scope
        latedef: false,
        // use this in mocks
        forin: false,
        ///////////////////////////////
        // All others are true
        //////////////////////////////
        immed: true,
        newcap: true,
        noarg: true,
        bitwise: true,
        sub: true,
        undef: true,
        unused: false,
        trailing: true,
        devel: true,
        jquery: true,
        nonstandard: true,
        boss: true,
        eqnull: true,
        browser: true,
        debug: true
      },
      globals: {
        Raphael: true,
        require: true,
        console: true,
        describe: true,
        expect: true,
        it: true,
        exports: true,
        process: true
      }
    },
    browserify: {
      'build/bundle.js': {
        entries: ['src/**/*.js', 'src/js/**/*.js']
        //prepend: ['<banner:meta.banner>'],
      }
    }
  });

  // all my npm helpers
  grunt.loadNpmTasks('grunt-jslint');
  grunt.loadNpmTasks('grunt-browserify');
  grunt.loadNpmTasks('grunt-jasmine-node');
  grunt.loadNpmTasks('grunt-hash');
  grunt.loadNpmTasks('grunt-rm');
  grunt.loadNpmTasks('grunt-shell');

  grunt.registerTask('build', 'rm browserify min hash buildIndex shell');
  grunt.registerTask('fastBuild', 'rm browserify hash buildIndex shell');

  grunt.registerTask('default', 'lint lintStrings jasmine_node build compliment');

  grunt.registerTask('watching', 'fastBuild lint lintStrings');
  grunt.registerTask('test', 'jasmine_node');
};

<|endoftext|>


<commit_before>"use strict";

var child_process = require('child_process'),
    exec = child_process.exec,
    spawn = child_process.spawn,
    path = require("path");

module.exports = function(grunt) {

    grunt.initConfig({
        lint: {
            files: ["grunt.js", "lib/server/**/*.js"]
        },
        jshint: {
            options: {
                curly: true,
                eqeqeq: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                sub: true,
                undef: true,
                eqnull: true,
                node : true,
                es5 : true,
                globalstrict : true
            }
        },
        simplemocha: {
            all: {
                src: ["test/server/**/*.test.js", "test/shared/**/*.test.js", "test/core/**/*.test.js"],
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'spec'
                }
            },
            nyan: {
                src: ["test/server/**/*.test.js", "test/shared/**/*.test.js", "test/core/**/*.test.js"],
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'nyan'
                }
            },
            shared : {
                src: 'test/shared/**/*.test.js',
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'spec'
                }
            },
            server : {
                src: 'test/server/**/*.test.js',
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'spec'
                }
            },
            core : {
                src: 'test/core/**/*.test.js',
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'spec'
                }
            },
            jenkins: {
                src: ["test/server/**/*.test.js", "test/shared/**/*.test.js", "test/core/**/*.test.js"],
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'xunit-file'
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-simple-mocha');

    grunt.registerTask("enable-testing-mode", "sets env to testing to keep the console quiet", function() {
        var env = process.env;
        env.mode = "testing"; //logger be quiet!
    });

    grunt.registerTask("freshNpmInstall","deletes the node_modules folder and does npm install afterwards", function() {

        var done = this.async();

        var rmNodeModulesProcess = exec("rm -r -f " + __dirname + "/node_modules  ",
            function (error, stdout, stderr) {

                if (error !== null) {
                    done(error);
                    return;
                }

                var npmInstall = spawn("npm", ["install"]);

                //awesome pipeing!
                npmInstall.stdout.pipe(process.stdout);
                npmInstall.stderr.pipe(process.stderr);

                npmInstall.on('exit', function (code) {
                    if(code === 0) {
                        done(null);
                    }
                    else {
                        done(new Error("NPM Install error!"));
                    }
                });
            });
    });

    grunt.registerTask("test-client", "tests with nof5", function() {

        var done = this.async(),
            nof5Command = 'cd ' + path.resolve(__dirname, "./test/client") + " ; nof5";

        var nof5Process = exec(nof5Command,
            function (error, stdout, stderr) {
                if (error !== null) {
                    console.log('exec error: ' + error);
                }
            });

        //give nof5 some time to initialize
        setTimeout(function() {
            var openBrowserCmd = "open http://localhost:11234";
            var openBrowserProcess = exec(openBrowserCmd, function(error){
                if (error !== null) {
                    console.log('exec error: ' + error);
                }
            });
        }, 1000);
    });

    //mocha server tests
    grunt.registerTask("test-server", "enable-testing-mode simplemocha:server");
    grunt.registerTask("test-core", "enable-testing-mode simplemocha:core");
    grunt.registerTask("test-shared", "enable-testing-mode simplemocha:shared");

    grunt.registerTask('test-all', "enable-testing-mode simplemocha:all");

    grunt.registerTask("test-jenkins", "enable-testing-mode simplemocha:jenkins");

};<commit_msg>- made test starters for client tests<commit_after>"use strict";

var child_process = require('child_process'),
    exec = child_process.exec,
    spawn = child_process.spawn,
    path = require("path");

module.exports = function(grunt) {

    grunt.initConfig({
        lint: {
            files: ["grunt.js", "lib/server/**/*.js"]
        },
        jshint: {
            options: {
                curly: true,
                eqeqeq: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                sub: true,
                undef: true,
                eqnull: true,
                node : true,
                es5 : true,
                globalstrict : true
            }
        },
        simplemocha: {
            all: {
                src: ["test/server/**/*.test.js", "test/shared/**/*.test.js", "test/core/**/*.test.js"],
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'spec'
                }
            },
            nyan: {
                src: ["test/server/**/*.test.js", "test/shared/**/*.test.js", "test/core/**/*.test.js"],
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'nyan'
                }
            },
            shared : {
                src: 'test/shared/**/*.test.js',
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'spec'
                }
            },
            server : {
                src: 'test/server/**/*.test.js',
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'spec'
                }
            },
            core : {
                src: 'test/core/**/*.test.js',
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'spec'
                }
            },
            jenkins: {
                src: ["test/server/**/*.test.js", "test/shared/**/*.test.js", "test/core/**/*.test.js"],
                options: {
                    globals: ['should'],
                    timeout: 3000,
                    ignoreLeaks: false,
                    ui: 'bdd',
                    reporter: 'xunit-file'
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-simple-mocha');

    grunt.registerTask("enable-testing-mode", "sets env to testing to keep the console quiet", function() {
        var env = process.env;
        env.mode = "testing"; //logger be quiet!
    });

    grunt.registerHelper('nof5Test', function(testPath, callback) {

        var nof5Command = 'cd ' + testPath + " ; nof5";

        var nof5Process = exec(nof5Command,
            function (error, stdout, stderr) {
                if (error !== null) {
                    console.log('exec error: ' + error);
                }
            });

        nof5Process.stdout.pipe(process.stdout);
        nof5Process.stderr.pipe(process.stderr);

        //give nof5 some time to initialize
        setTimeout(function() {
            var openBrowserCmd = "open http://localhost:11234";
            var openBrowserProcess = exec(openBrowserCmd, function(error){
                if (error !== null) {
                    console.log('exec error: ' + error);
                }
                callback(error);
            });
        }, 1000);
    });

    grunt.registerTask("freshNpmInstall","deletes the node_modules folder and does npm install afterwards", function() {

        var done = this.async();

        var rmNodeModulesProcess = exec("rm -r -f " + __dirname + "/node_modules  ",
            function (error, stdout, stderr) {

                if (error !== null) {
                    done(error);
                    return;
                }

                var npmInstall = spawn("npm", ["install"]);

                //awesome pipeing!
                npmInstall.stdout.pipe(process.stdout);
                npmInstall.stderr.pipe(process.stderr);

                npmInstall.on('exit', function (code) {
                    if(code === 0) {
                        done(null);
                    }
                    else {
                        done(new Error("NPM Install error!"));
                    }
                });
            });
    });

    grunt.registerTask("test-client", "tests with nof5", function() {

        var done = this.async();

        grunt.helper("nof5Test", path.resolve(__dirname, "./test/client"), function() {
            //do nothing, kill it manually
        });
    });

    grunt.registerTask("test-shared-browser", "tests with nof5", function() {

        var done = this.async();

        grunt.helper("nof5Test", path.resolve(__dirname, "./test/shared"), function() {
            //do nothing, kill it manually
        });
    });

    //mocha server tests
    grunt.registerTask("test-server", "enable-testing-mode simplemocha:server");
    grunt.registerTask("test-core", "enable-testing-mode simplemocha:core");
    grunt.registerTask("test-shared", "enable-testing-mode simplemocha:shared");

    grunt.registerTask('test-all', "enable-testing-mode simplemocha:all");

    grunt.registerTask("test-jenkins", "enable-testing-mode simplemocha:jenkins");

};<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function (grunt) {
	"use strict";
	grunt.loadNpmTasks('grunt-jslint');
	grunt.loadNpmTasks('grunt-contrib');
	grunt.loadNpmTasks('grunt-compass');

	// Project configuration.
	grunt.initConfig({
		pkg: '<json:package.json>',
		meta: {
			banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
				'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
				'<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
				'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
				' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
		},
		jslint: {
			files: ['grunt.js', 'public/javascripts/spec/**/*.js', 'public/javascripts/*.js', 'test/**/*.js', 'app/**/*.js', 'app.js']
		},
		mincss: {
			compress: {
				files: {
					'public/stylesheets/style.min.css': ['public/stylesheets/reset.css', 'public/stylesheets/bootstrap.css', 'public/stylesheets/style.css']
				}
			}
		},
		concat: {
			dist: {
				src: ['public/javascripts/semtag.js', 'public/javascripts/sw-semtag.js'],
				dest: 'public/javascripts/dist/<%= pkg.name %>.js'
			}
		},
		min: {
			dist: {
				src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
				dest: 'public/javascripts/dist/<%= pkg.name %>.min.js'
			}
		},
		watch: {
			files: ['public/javascripts/*.js', 'public/stylesheets/scss/*', 'grunt.js', 'app/**/*.js', 'app.js'],
			tasks: ['default']
		},
		jslint_directives: { // example directives
			browser: true,
			unparam: true,
			node: true,
			predef: [ // array of pre-defined globals
				'jQuery'
			]
		},
		jslint_options: {
			junit: 'logs/junit.xml', // write the output to a JUnit XML
			log: 'logs/lint.log',
			errorsOnly: true // only display errors
		},
		uglify: {},
		compass: {
			dev: {
				src: 'public/stylesheets/scss/',
				dest: 'public/stylesheets/',
				linecomments: true
			}
		}
	});

	// Default task.
	grunt.registerTask('default', 'jslint concat min compass:dev mincss');

};
<commit_msg>Added bootstrap to the js concat lint<commit_after>/*global module:false*/
module.exports = function (grunt) {
	"use strict";
	grunt.loadNpmTasks('grunt-jslint');
	grunt.loadNpmTasks('grunt-contrib');
	grunt.loadNpmTasks('grunt-compass');

	// Project configuration.
	grunt.initConfig({
		pkg: '<json:package.json>',
		meta: {
			banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
				'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
				'<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
				'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
				' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
		},
		jslint: {
			files: ['grunt.js', 'public/javascripts/spec/**/*.js', 'public/javascripts/*.js', 'test/**/*.js', 'app/**/*.js', 'app.js']
		},
		mincss: {
			compress: {
				files: {
					'public/stylesheets/style.min.css': ['public/stylesheets/reset.css', 'public/stylesheets/bootstrap.css', 'public/stylesheets/style.css']
				}
			}
		},
		concat: {
			dist: {
				src: ['public/javascripts/lib/bootstrap.js', 'public/javascripts/semtag.js', 'public/javascripts/sw-semtag.js'],
				dest: 'public/javascripts/dist/<%= pkg.name %>.js'
			}
		},
		min: {
			dist: {
				src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
				dest: 'public/javascripts/dist/<%= pkg.name %>.min.js'
			}
		},
		watch: {
			files: ['public/javascripts/*.js', 'public/stylesheets/scss/*', 'grunt.js', 'app/**/*.js', 'app.js'],
			tasks: ['default']
		},
		jslint_directives: { // example directives
			browser: true,
			unparam: true,
			node: true,
			predef: [ // array of pre-defined globals
				'jQuery'
			]
		},
		jslint_options: {
			junit: 'logs/junit.xml', // write the output to a JUnit XML
			log: 'logs/lint.log',
			errorsOnly: true // only display errors
		},
		uglify: {},
		compass: {
			dev: {
				src: 'public/stylesheets/scss/',
				dest: 'public/stylesheets/',
				linecomments: true
			}
		}
	});

	// Default task.
	grunt.registerTask('default', 'jslint concat min compass:dev mincss');

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  grunt.initConfig({
    qunit: ['./test/index.html'],
    lint: ['supermodel.js', './test/*.js'],
    jshint: {
      options: {
        eqnull: true,
        undef: true
      },
      globals: {
        // QUnit
        ok: true,
        test: true,
        module: true,
        deepEqual: true,
        strictEqual: true,

        // Dependencies
        _: true,
        jQuery: true,
        Backbone: true,
        Supermodel: true
      }
    }
  });

};
<commit_msg>Add `raises` to linter globals.<commit_after>module.exports = function(grunt) {

  grunt.initConfig({
    qunit: ['./test/index.html'],
    lint: ['supermodel.js', './test/*.js'],
    jshint: {
      options: {
        eqnull: true,
        undef: true
      },
      globals: {
        // QUnit
        ok: true,
        test: true,
        module: true,
        raises: true,
        deepEqual: true,
        strictEqual: true,

        // Dependencies
        _: true,
        jQuery: true,
        Backbone: true,
        Supermodel: true
      }
    }
  });

};
<|endoftext|>