<commit_before>/**
 * JavaScript Behaviors Library
 *
 * @copyright 2014 Stephen Riesenberg, All Rights Reserved
 * @author Dan Yoder
 * @author Stephen Riesenberg
 * @version 0.7
 * @license MIT
 * @link http://code.google.com/p/cruiser/wiki/Behaviors
 * @link https://github.com/sjohnr/behaviors.js
 */
var Behaviors = {
	/**
	 * Load and process Behaviors Stylesheets.
	 */
	load: function() {
		$A(document.getElementsByTagName("link"))
			.select(Behaviors.Stylesheet.test)
			.pluck("href")
			.map(Behaviors.process);
	},
	/**
	 * Load an individual Behaviors Stylesheet file by URL.
	 */
	process: function(href) {
		Behaviors.Stylesheet.load(href);
	}
};

Behaviors.Stylesheet = {
	/**
	 * Determine if the given <link> element is a Behaviors Stylesheet.
	 *
	 * @param link A <link> element to test
	 */
	test: function(link) {
		return link.rel == "behaviors";
	},
	/**
	 * Load the contents of a Behaviors Styleseheet via Ajax
	 * and process the result.
	 *
	 * @param url The URL to load
	 */
	load: function(url) {
		new Ajax.Request(url, { method: "get", onSuccess: Behaviors.Stylesheet.process });
	},
	/**
	 * Process an Ajax response as a Behaviors Stylesheet.
	 *
	 * @param t The Ajax response object
	 */
	process: function(t) {
		var rules = Behaviors.Stylesheet.parse(t.responseText);
		$H(rules).each(function(r) {
			var elements = $$(r.key);
			var attributes = r.value;
			elements.each(function(e) {
				if (!e.binding) {
					e.binding = e;
				}
				$H(attributes).each(function(a) {
					var fn = Behaviors.Attributes[a.key.camelize()];
					try {
						fn ? fn(e, a.value, a.key) : null;
					} catch (ex) {
						if (window.console) {
							console.log(ex);
							console.log("@ " + r.key + " { " + a.key + ": " + a.value + "; }");
						}
					};
				});
			});
		});
	},
	/**
	 * Parse a Behaviors Stylesheet.
	 *
	 * @param s The contents of the stylesheet file
	 */
	parse: function(s) {
		return Behaviors.Stylesheet._parse(s).first();
	}
};

Behaviors.Translator = {
	/**
	 * Translate style attributes an associative array.
	 *
	 * @param attrs The attributes parse tree
	 */
	style: function(attrs) {
		return attrs.inject({}, function(h, a) {
			h[a[0]] = a[1];

			return h;
		});
	},
	/**
	 * Translate rules to an associative array.
	 *
	 * @param rx The rules parse tree
	 */
	rules: function(rx) {
		return rx.inject({}, function(h, r) {
			if (r) {
				h[r[0]] = r[1];
			}

			return h;
		});
	}
};

Behaviors.Grammar = {};
(function() {
	var g = Behaviors.Grammar, s = Behaviors.Stylesheet, t = Behaviors.Translator, o = Parsing.Operators;

	// basic tokens
	g.lbrace = o.token("{");
	g.rbrace = o.token("}");
	g.lparen = o.token(/\(/);
	g.rparen = o.token(/\)/);
	g.colon = o.token(":");
	g.semicolon = o.token(";");
	// comments
	g.inlineComment = o.token(/\x2F\x2F[^\n]*\n/);
	g.multilineComment = o.token(/\x2F\x2A(.|\n)*?\x2A\x2F/);
	g.comments = o.ignore(o.any(g.inlineComment, g.multilineComment));
	// attributes
	g.attrName = o.token(/[\w\-\d]+/);
	g.attrValue = o.token(/[^;\}]+/);
	g.attr = o.pair(g.attrName, g.attrValue, g.colon);
	g.attrList = o.list(g.attr, g.semicolon, true);
	g.style = o.process(o.between(g.lbrace, g.attrList, g.rbrace), t.style);
	// style rules
	g.selector = o.token(/[^\{]+/);
	g.rule = o.any(g.comments, o.each(g.selector, g.style));
	g.rules = o.process(o.many(g.rule), t.rules);
	// parser
	s._parse = g.rules;
})();

Behaviors.Bindings = {};
(function() {
	/**
	 * Set the binding property of an object
	 *
	 * @param o The object or element to bind to
	 * @param t The target object or element being bound
	 */
	function bind(o, t) {
		o.binding = ((t instanceof Element) && t.binding) ? t.binding : t;
	}

	Object.extend(Behaviors.Bindings, {
		"new":      function(e, x) { bind(e, eval("new "+x+"(e)")); },
		"object":   function(e, x) { bind(e, eval(x)); },
		"select":   function(e, x) { bind(e, $$(x)[0]); },
		"up":       function(e, x) { bind(e, e.up(x)); },
		"down":     function(e, x) { bind(e, e.down(x)); },
		"previous": function(e, x) { bind(e, e.previous(x)); },
		"next":     function(e, x) { bind(e, e.next(x)); }
	});
})();

Behaviors.Relative = {};
Behaviors.Attributes = {};
(function() {
	/**
	 * Adds relative attribute functions: minimum, maximum, equal.
	 *
	 * @param c The comparator function
	 * @param a The attribute name
	 * @param e1 The first element (the element to act upon)
	 * @param s The selector to evaluate as an element to compare to
	 */
	function apply(c, a, e1, s) {
		var e2 = $$(s)[0]; if (!e2) return;
		if (c(parseInt(e1.getStyle(a)), parseInt(e2.getStyle(a)))) {
			e1.style[a] = e2.getStyle(a) ;
		}
	}

	/**
	 * Adds an event handler to the element: blur, change, click, etc.
	 *
	 * @param h The handler
	 * @param e The element
	 * @param v The function name to invoke
	 */
	function observe(h, e, v) {
		e.observe(h, e.binding[v].bind(e.binding));
	}

	/**
	 * Adds relative attributes: height, width ...
	 *
	 * @param a The attribute name
	 * @param e The element
	 * @param v The function spec, e.g. "minimum( div.sidebar )"
	 */
	function relative(a, e, v) {
		var f = parseFunction(v);
		if (!f) {
			return;
		}
		var fname = f[1]; var s = f[2];
		var fn = Behaviors.Relative[fname];
		if (fn) {
			fn(a, e, s);
		}
	}

	function parseFunction(s) {
		return s.match(/(\w+)\s*\(\s*([^\)]+)\s*\)/);
	}

	//
	// Comparator functions
	//
	Object.extend(Behaviors.Relative, $H({
		"minimum": function(a, b) { return a < b; },
		"maximum": function(a, b) { return a > b; },
		"equal":   function(a, b) { return a == b; }
	}).inject({}, function(r, h) {
		return r[h.key] = apply.curry(h.value);
	}));

	//
	// Core attribute functions
	//
	Object.extend(Behaviors.Attributes, {
		/**
		 * Adds a binding to an element.
		 *
		 * @param e The element
		 * @param v The function spec, e.g. "new( TabControl )"
		 */
		binding: function(e, v) {
			var f = parseFunction(v);
			if (!f) {
				return;
			}
			var fname = f[1], x = f[2];
			var fn = Behaviors.Bindings[fname];
			if (fn) {
				fn(e, x);
			}
		},
		/**
		 * Adds a callback when the element is loaded.
		 *
		 * @param e The element
		 * @param v The function, e.g. "addMenuItem"
		 */
		load: function(e, v) {
			if (e.binding[v]) {
				e.binding[v](e);
			}
		},
		/**
		 * Give an element focus.
		 *
		 * @param e The element
		 * @param v Dummy argument, "true" or "yes"
		 */
		hasFocus: function(e, v) {
			v = v.toLowerCase();
			if (v == "true" || v == "yes") {
				e.focus();
			}
		}
	});

	//
	// Meta functions for observing events
	//
	$w("blur change click dblclick contextmenu focus keydown keypress keyup mousedown mousemove mouseout mouseover mouseup resize").each(function(s) {
		Behaviors.Attributes[s] = observe.curry(s);
	});

	//
	// Meta functions for maintaining relative size
	//
	$w("height width").each(function(s) {
		Behaviors.Attributes[s] = relative.curry(s);
	});
})();

document.observe("dom:loaded", Behaviors.load);<commit_msg>Renamed Parsing to Parser<commit_after>/**
 * JavaScript Behaviors Library
 *
 * @copyright 2014 Stephen Riesenberg, All Rights Reserved
 * @author Dan Yoder
 * @author Stephen Riesenberg
 * @version 0.7
 * @license MIT
 * @link http://code.google.com/p/cruiser/wiki/Behaviors
 * @link https://github.com/sjohnr/behaviors.js
 */
var Behaviors = {
	/**
	 * Load and process Behaviors Stylesheets.
	 */
	load: function() {
		$A(document.getElementsByTagName("link"))
			.select(Behaviors.Stylesheet.test)
			.pluck("href")
			.map(Behaviors.process);
	},
	/**
	 * Load an individual Behaviors Stylesheet file by URL.
	 */
	process: function(href) {
		Behaviors.Stylesheet.load(href);
	}
};

Behaviors.Stylesheet = {
	/**
	 * Determine if the given <link> element is a Behaviors Stylesheet.
	 *
	 * @param link A <link> element to test
	 */
	test: function(link) {
		return link.rel == "behaviors";
	},
	/**
	 * Load the contents of a Behaviors Styleseheet via Ajax
	 * and process the result.
	 *
	 * @param url The URL to load
	 */
	load: function(url) {
		new Ajax.Request(url, { method: "get", onSuccess: Behaviors.Stylesheet.process });
	},
	/**
	 * Process an Ajax response as a Behaviors Stylesheet.
	 *
	 * @param t The Ajax response object
	 */
	process: function(t) {
		var rules = Behaviors.Stylesheet.parse(t.responseText);
		$H(rules).each(function(r) {
			var elements = $$(r.key);
			var attributes = r.value;
			elements.each(function(e) {
				if (!e.binding) {
					e.binding = e;
				}
				$H(attributes).each(function(a) {
					var fn = Behaviors.Attributes[a.key.camelize()];
					try {
						fn ? fn(e, a.value, a.key) : null;
					} catch (ex) {
						if (window.console) {
							console.log(ex);
							console.log("@ " + r.key + " { " + a.key + ": " + a.value + "; }");
						}
					};
				});
			});
		});
	},
	/**
	 * Parse a Behaviors Stylesheet.
	 *
	 * @param s The contents of the stylesheet file
	 */
	parse: function(s) {
		return Behaviors.Stylesheet._parse(s).first();
	}
};

Behaviors.Translator = {
	/**
	 * Translate style attributes an associative array.
	 *
	 * @param attrs The attributes parse tree
	 */
	style: function(attrs) {
		return attrs.inject({}, function(h, a) {
			h[a[0]] = a[1];

			return h;
		});
	},
	/**
	 * Translate rules to an associative array.
	 *
	 * @param rx The rules parse tree
	 */
	rules: function(rx) {
		return rx.inject({}, function(h, r) {
			if (r) {
				h[r[0]] = r[1];
			}

			return h;
		});
	},
	/**
	 * Merge lists of rules together after ignoring comments.
	 *
	 * @param rx The rules lists to merge
	 */
	parse: function(rx) {
		return rx.inject($H({}), function(h, r) {
			h.merge(r);

			return h;
		});
	}
};

Behaviors.Grammar = {};
(function() {
	var g = Behaviors.Grammar, s = Behaviors.Stylesheet, t = Behaviors.Translator, o = Parser.Operators;

	// basic tokens
	g.lbrace = o.token("{");
	g.rbrace = o.token("}");
	g.lparen = o.token(/\(/);
	g.rparen = o.token(/\)/);
	g.colon = o.token(":");
	g.semicolon = o.token(";");
	// comments
	g.inlineComment = o.token(/\x2F\x2F[^\n]*\n/);
	g.multilineComment = o.token(/\x2F\x2A(.|\n)*?\x2A\x2F/);
	g.comments = o.ignore(o.any(g.inlineComment, g.multilineComment));
	// attributes
	g.attrName = o.token(/[\w\-\d]+/);
	g.attrValue = o.token(/[^;\}]+/);
	g.attr = o.pair(g.attrName, g.attrValue, g.colon);
	g.attrList = o.list(g.attr, g.semicolon, true);
	g.style = o.process(o.between(g.lbrace, g.attrList, g.rbrace), t.style);
	// style rules
	g.selector = o.token(/[^\{]+/);
	g.rule = o.each(g.selector, g.style);
	g.rules = o.process(o.many(g.rule), t.rules);
	// parser
	s._parse = o.process(many(any(g.comments, g.rules)), t.parse);
})();

Behaviors.Bindings = {};
(function() {
	/**
	 * Set the binding property of an object
	 *
	 * @param o The object or element to bind to
	 * @param t The target object or element being bound
	 */
	function bind(o, t) {
		o.binding = ((t instanceof Element) && t.binding) ? t.binding : t;
	}

	Object.extend(Behaviors.Bindings, {
		"new":      function(e, x) { bind(e, eval("new "+x+"(e)")); },
		"object":   function(e, x) { bind(e, eval(x)); },
		"select":   function(e, x) { bind(e, $$(x)[0]); },
		"up":       function(e, x) { bind(e, e.up(x)); },
		"down":     function(e, x) { bind(e, e.down(x)); },
		"previous": function(e, x) { bind(e, e.previous(x)); },
		"next":     function(e, x) { bind(e, e.next(x)); }
	});
})();

Behaviors.Relative = {};
Behaviors.Attributes = {};
(function() {
	/**
	 * Adds relative attribute functions: minimum, maximum, equal.
	 *
	 * @param c The comparator function
	 * @param a The attribute name
	 * @param e1 The first element (the element to act upon)
	 * @param s The selector to evaluate as an element to compare to
	 */
	function apply(c, a, e1, s) {
		var e2 = $$(s)[0]; if (!e2) return;
		if (c(parseInt(e1.getStyle(a)), parseInt(e2.getStyle(a)))) {
			e1.style[a] = e2.getStyle(a) ;
		}
	}

	/**
	 * Adds an event handler to the element: blur, change, click, etc.
	 *
	 * @param h The handler
	 * @param e The element
	 * @param v The function name to invoke
	 */
	function observe(h, e, v) {
		e.observe(h, e.binding[v].bind(e.binding));
	}

	/**
	 * Adds relative attributes: height, width ...
	 *
	 * @param a The attribute name
	 * @param e The element
	 * @param v The function spec, e.g. "minimum( div.sidebar )"
	 */
	function relative(a, e, v) {
		var f = parseFunction(v);
		if (!f) {
			return;
		}
		var fname = f[1]; var s = f[2];
		var fn = Behaviors.Relative[fname];
		if (fn) {
			fn(a, e, s);
		}
	}

	function parseFunction(s) {
		return s.match(/(\w+)\s*\(\s*([^\)]+)\s*\)/);
	}

	//
	// Comparator functions
	//
	Object.extend(Behaviors.Relative, $H({
		"minimum": function(a, b) { return a < b; },
		"maximum": function(a, b) { return a > b; },
		"equal":   function(a, b) { return a == b; }
	}).inject({}, function(r, h) {
		return r[h.key] = apply.curry(h.value);
	}));

	//
	// Core attribute functions
	//
	Object.extend(Behaviors.Attributes, {
		/**
		 * Adds a binding to an element.
		 *
		 * @param e The element
		 * @param v The function spec, e.g. "new( TabControl )"
		 */
		binding: function(e, v) {
			var f = parseFunction(v);
			if (!f) {
				return;
			}
			var fname = f[1], x = f[2];
			var fn = Behaviors.Bindings[fname];
			if (fn) {
				fn(e, x);
			}
		},
		/**
		 * Adds a callback when the element is loaded.
		 *
		 * @param e The element
		 * @param v The function, e.g. "addMenuItem"
		 */
		load: function(e, v) {
			if (e.binding[v]) {
				e.binding[v](e);
			}
		},
		/**
		 * Give an element focus.
		 *
		 * @param e The element
		 * @param v Dummy argument, "true" or "yes"
		 */
		hasFocus: function(e, v) {
			v = v.toLowerCase();
			if (v == "true" || v == "yes") {
				e.focus();
			}
		}
	});

	//
	// Meta functions for observing events
	//
	$w("blur change click dblclick contextmenu focus keydown keypress keyup mousedown mousemove mouseout mouseover mouseup resize").each(function(s) {
		Behaviors.Attributes[s] = observe.curry(s);
	});

	//
	// Meta functions for maintaining relative size
	//
	$w("height width").each(function(s) {
		Behaviors.Attributes[s] = relative.curry(s);
	});
})();

document.observe("dom:loaded", Behaviors.load);<|endoftext|>


<commit_before>require('es6-promise/auto')
require('whatwg-fetch')
const Uppy = require('@uppy/core')
const Dashboard = require('@uppy/dashboard')
const Webcam = require('@uppy/webcam')
const Transloadit = require('@uppy/transloadit')
const Instagram = require('@uppy/instagram')
const Facebook = require('@uppy/facebook')
const { createHmac } = require('crypto')
const COMPANION = require('../env')

function sha1 (key, text) {
  return createHmac('sha1', key)
    .update(text)
    .digest('hex')
}

function initUppy (opts = {}) {
  if (window.uppy) {
    window.uppy.close()
  }

  const uppy = new Uppy({
    debug: true,
    autoProceed: false,
    restrictions: {
      maxFileSize: 1024 * 1024 * 1024,
      maxNumberOfFiles: 2,
      minNumberOfFiles: 1,
      allowedFileTypes: ['image/*']
    },
    locale: {
      strings: {
        youCanOnlyUploadFileTypes: 'You can only upload images'
      }
    }
  })

  function getExpiration (future) {
    return new Date(Date.now() + future)
      .toISOString()
      .replace('T', ' ')
      .replace(/\.\d+Z$/, '+00:00')
  }

  function getAssemblyOptions () {
    const hasSecret = opts.secret != null
    let params = {
      auth: {
        key: window.TRANSLOADIT_API_KEY,
        expires: hasSecret ? getExpiration(5 * 60 * 1000) : undefined
      },
      // It's more secure to use a template_id and enable
      // Signature Authentication
      steps: {
        resize: {
          robot: '/image/resize',
          width: 250,
          height: 250,
          resize_strategy: 'fit',
          text: [
            {
              text: `© ${(new Date).getFullYear()} Transloadit.com`,
              size: 12,
              font: 'Ubuntu',
              color: '#eeeeee',
              valign: 'bottom',
              align: 'right',
              x_offset: 16,
              y_offset: -10
            }
          ]
        }
      }
    }

    let signature
    if (opts.secret) {
      params = JSON.stringify(params)
      signature = sha1(opts.secret, params)
    }

    return { params, signature }
  }

  uppy
    .use(Transloadit, {
      getAssemblyOptions,
      waitForEncoding: true
    })
    .use(Dashboard, {
      inline: true,
      maxHeight: 400,
      target: '#uppy-dashboard-container',
      note: 'Images only, 1–2 files, up to 1 MB'
    })
    .use(Instagram, {
      target: Dashboard,
      companionUrl: 'https://api2.transloadit.com/companion',
      companionAllowedHosts: Transloadit.COMPANION_PATTERN
    })
    .use(Facebook, {
      target: Dashboard,
      companionUrl: COMPANION
    })
    .use(Webcam, { target: Dashboard, modes: ['picture'] })

  uppy
    .on('transloadit:result', (stepName, result) => {
      const file = uppy.getFile(result.localId)
      var resultContainer = document.createElement('div')
      resultContainer.innerHTML = `

Name: ${file.name}

          View

      `
      document
        .getElementById('uppy-transloadit-result')
        .appendChild(resultContainer)
    })
}

window.initUppy = initUppy
<commit_msg>website: enable Zoom on transloadit example (#2474)<commit_after>require('es6-promise/auto')
require('whatwg-fetch')
const Uppy = require('@uppy/core')
const Dashboard = require('@uppy/dashboard')
const Webcam = require('@uppy/webcam')
const Transloadit = require('@uppy/transloadit')
const Instagram = require('@uppy/instagram')
const Facebook = require('@uppy/facebook')
const Zoom = require('@uppy/zoom')
const { createHmac } = require('crypto')
const COMPANION = require('../env')

function sha1 (key, text) {
  return createHmac('sha1', key)
    .update(text)
    .digest('hex')
}

function initUppy (opts = {}) {
  if (window.uppy) {
    window.uppy.close()
  }

  const zoomMode = document.location.hash === '#enable-zoom'
  const allowedFileTypes = zoomMode ? ['video/*'] : ['image/*']
  const uppy = new Uppy({
    debug: true,
    autoProceed: false,
    restrictions: {
      maxFileSize: 1024 * 1024 * 1024,
      maxNumberOfFiles: 2,
      minNumberOfFiles: 1,
      allowedFileTypes
    },
    locale: {
      strings: {
        youCanOnlyUploadFileTypes: 'You can only upload images'
      }
    }
  })

  function getExpiration (future) {
    return new Date(Date.now() + future)
      .toISOString()
      .replace('T', ' ')
      .replace(/\.\d+Z$/, '+00:00')
  }

  function getAssemblyOptions () {
    const hasSecret = opts.secret != null
    let params = {
      auth: {
        key: window.TRANSLOADIT_API_KEY,
        expires: hasSecret ? getExpiration(5 * 60 * 1000) : undefined
      },
      // It's more secure to use a template_id and enable
      // Signature Authentication
      steps: {
        resize: {
          robot: '/image/resize',
          width: 250,
          height: 250,
          resize_strategy: 'fit',
          text: [
            {
              text: `© ${(new Date).getFullYear()} Transloadit.com`,
              size: 12,
              font: 'Ubuntu',
              color: '#eeeeee',
              valign: 'bottom',
              align: 'right',
              x_offset: 16,
              y_offset: -10
            }
          ]
        }
      }
    }

    if (zoomMode) {
      params.steps = {
        resized: {
          use: ':original',
          robot: '/video/encode',
          result: true,
          ffmpeg_stack: 'v3.3.3',
          preset: 'ipad-high',
          resize_strategy: 'fillcrop'
        },
        watermarked: {
          use: 'resized',
          robot: '/video/encode',
          result: true,
          ffmpeg_stack: 'v3.3.3',
          preset: 'ipad-high',
          watermark_opacity: 0.7,
          watermark_position: 'top-right',
          watermark_size: '25%',
          watermark_url: 'https://demos.transloadit.com/inputs/transloadit-padded.png',
          watermark_x_offset: -10,
          watermark_y_offset: 10
        }
      }
    }

    let signature
    if (opts.secret) {
      params = JSON.stringify(params)
      signature = sha1(opts.secret, params)
    }

    return { params, signature }
  }

  uppy
    .use(Transloadit, {
      getAssemblyOptions,
      waitForEncoding: true
    })
    .use(Dashboard, {
      inline: true,
      maxHeight: 400,
      target: '#uppy-dashboard-container',
      note: 'Images only, 1–2 files, up to 1 MB'
    })
    .use(Instagram, {
      target: Dashboard,
      companionUrl: 'https://api2.transloadit.com/companion',
      companionAllowedHosts: Transloadit.COMPANION_PATTERN
    })
    .use(Facebook, {
      target: Dashboard,
      companionUrl: COMPANION
    })
    .use(Webcam, { target: Dashboard, modes: ['picture'] })

  if (zoomMode) {
    uppy.use(Zoom, {
      target: Dashboard,
      companionUrl: 'https://api2.transloadit.com/companion',
      companionAllowedHosts: Transloadit.COMPANION_PATTERN
    })
  }

  uppy
    .on('transloadit:result', (stepName, result) => {
      const file = uppy.getFile(result.localId)
      var resultContainer = document.createElement('div')
      if (!zoomMode) {
        resultContainer.innerHTML = `

Name: ${file.name}

            View

        `
      }

      if (zoomMode && stepName === 'watermarked') {
        resultContainer.innerHTML = `

Name: ${file.name}

            <video controls>
              <source src="${result.ssl_url}">
            </video>

            View

        `
      }
      document
        .getElementById('uppy-transloadit-result')
        .appendChild(resultContainer)
    })
}

window.initUppy = initUppy
<|endoftext|>


<commit_before>const Uppy = require('@uppy/core')
const Dashboard = require('@uppy/dashboard')
const Webcam = require('@uppy/webcam')
const Transloadit = require('@uppy/transloadit')
const Instagram = require('@uppy/instagram')

function initUppy () {
  if (window.uppy) {
    window.uppy.close()
  }

  const uppy = Uppy({
    debug: true,
    autoProceed: false,
    restrictions: {
      maxFileSize: 1024 * 1024 * 1024,
      maxNumberOfFiles: 2,
      minNumberOfFiles: 1,
      allowedFileTypes: ['image/*']
    }
  })

  uppy
    .use(Transloadit, {
      params: {
        auth: {
          key: window.TRANSLOADIT_API_KEY
        },
        // It's more secure to use a template_id and enable
        // Signature Authentication
        steps: {
          resize: {
            robot: '/image/resize',
            width: 250,
            height: 250,
            resize_strategy: 'fit',
            text: [
              {
                text: '© 2018 Transloadit.com',
                size: 12,
                font: 'Ubuntu',
                color: '#eeeeee',
                valign: 'bottom',
                align: 'right',
                x_offset: 16,
                y_offset: -10
              }
            ]
          }
        }
      },
      waitForEncoding: true
    })
    .use(Dashboard, {
      inline: true,
      maxHeight: 400,
      target: '#uppy-dashboard-container',
      note: 'Images only, 1–2 files, up to 1 MB'
    })
    .use(Instagram, { target: Dashboard, serverUrl: 'https://api2.transloadit.com/companion' })
    .use(Webcam, { target: Dashboard })

  uppy
    .on('transloadit:result', (stepName, result) => {
      const file = uppy.getFile(result.localId)
      var resultContainer = document.createElement('div')
      resultContainer.innerHTML = `

Name: ${file.name}

          View

      `
      document
        .getElementById('uppy-transloadit-result')
        .appendChild(resultContainer)
    })
}

window.initUppy = initUppy
<commit_msg>Add serverPattern to Transloadit Example (es6)<commit_after>const Uppy = require('@uppy/core')
const Dashboard = require('@uppy/dashboard')
const Webcam = require('@uppy/webcam')
const Transloadit = require('@uppy/transloadit')
const Instagram = require('@uppy/instagram')

function initUppy () {
  if (window.uppy) {
    window.uppy.close()
  }

  const uppy = Uppy({
    debug: true,
    autoProceed: false,
    restrictions: {
      maxFileSize: 1024 * 1024 * 1024,
      maxNumberOfFiles: 2,
      minNumberOfFiles: 1,
      allowedFileTypes: ['image/*']
    }
  })

  uppy
    .use(Transloadit, {
      params: {
        auth: {
          key: window.TRANSLOADIT_API_KEY
        },
        // It's more secure to use a template_id and enable
        // Signature Authentication
        steps: {
          resize: {
            robot: '/image/resize',
            width: 250,
            height: 250,
            resize_strategy: 'fit',
            text: [
              {
                text: '© 2018 Transloadit.com',
                size: 12,
                font: 'Ubuntu',
                color: '#eeeeee',
                valign: 'bottom',
                align: 'right',
                x_offset: 16,
                y_offset: -10
              }
            ]
          }
        }
      },
      waitForEncoding: true
    })
    .use(Dashboard, {
      inline: true,
      maxHeight: 400,
      target: '#uppy-dashboard-container',
      note: 'Images only, 1–2 files, up to 1 MB'
    })
    .use(Instagram, { target: Dashboard, serverUrl: 'https://api2.transloadit.com/companion', serverPattern: /\.transloadit\.com$/  })
    .use(Webcam, { target: Dashboard })

  uppy
    .on('transloadit:result', (stepName, result) => {
      const file = uppy.getFile(result.localId)
      var resultContainer = document.createElement('div')
      resultContainer.innerHTML = `

Name: ${file.name}

          View

      `
      document
        .getElementById('uppy-transloadit-result')
        .appendChild(resultContainer)
    })
}

window.initUppy = initUppy
<|endoftext|>


<commit_before>#!/usr/bin/env node
var path = require('path')
var argv = require('yargs').option('config', { alias: 'c', string: true, requiresArg: true }).argv;
var webpack = require('webpack')

var exposedLibraries = ['react', 'react-dom', 'superagent', 'react-list', 'bluebird', 'socket.io-client', 'filesaver.js-npm']

var defaultConfig = {
  devtool: 'hidden-source-map',
  entry: {
    main: './studio/main_dev'
  },
  output: {
    filename: './studio/main.js'
  },
  externals: [
    function (context, request, callback) {
      if (/babel-runtime/.test(request)) {
        return callback(null, 'Studio.runtime[\'' + request.substring('babel-runtime/'.length) + '\']')
      }

      if (exposedLibraries.indexOf(request) > -1) {
        return callback(null, 'Studio.libraries[\'' + request + '\']')
      }

      if (request === 'jsreport-studio') {
        return callback(null, 'Studio')
      }

      callback()
    }
  ],
  module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: [
            require.resolve('babel-preset-es2015'),
            require.resolve('babel-preset-react'),
            require.resolve('babel-preset-stage-0')
          ]
        }
      },
      {
        test: /\.scss$/,
        loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!postcss-loader!sass?outputStyle=expanded&sourceMap'
      }
    ]
  },
  postcss: function () {
    return [
      require('postcss-flexbugs-fixes'),
      require('autoprefixer')
    ]
  },
  resolveLoader: {
    modulesDirectories: [
      'node_modules', 'node_modules/jsreport-studio-dev/node_modules'
    ]
  },
  resolve: {
    modulesDirectories: [
      'node_modules', 'node_modules/jsreport-studio-dev/node_modules'
    ]
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      },
      __DEVELOPMENT__: false
    })
    //
    // // optimizations
    // new webpack.optimize.DedupePlugin(),
    // new webpack.optimize.OccurenceOrderPlugin(),
    // new webpack.optimize.UglifyJsPlugin({
    //   compress: {
    //     warnings: false
    //   }
    // })
  ]
}

var config

if (argv.config) {
  console.log('using custom webpack config at:', argv.config)

  try {
    config = require(path.resolve(process.cwd(), argv.config))
  } catch (e) {
    throw new Error('Error while trying to use config in ' + argv.config + ' : ' e.message)
  }
} else {
  config = defaultConfig
}

webpack(config, function (err, stats) {
  if (err) {
    console.err(err)
    return process.exit(1)
  }

  var jsonStats = stats.toJson()

  if (jsonStats.errors.length > 0) {
    console.error(jsonStats.errors)
    process.exit(1)
  }

  console.log(stats.toString({ colors: true, chunks: true, cached: false }))

  console.log('webpack build  ok')
})
<commit_msg>fix syntax error in build command<commit_after>#!/usr/bin/env node
var path = require('path')
var argv = require('yargs').option('config', { alias: 'c', string: true, requiresArg: true }).argv;
var webpack = require('webpack')

var exposedLibraries = ['react', 'react-dom', 'superagent', 'react-list', 'bluebird', 'socket.io-client', 'filesaver.js-npm']

var defaultConfig = {
  devtool: 'hidden-source-map',
  entry: {
    main: './studio/main_dev'
  },
  output: {
    filename: './studio/main.js'
  },
  externals: [
    function (context, request, callback) {
      if (/babel-runtime/.test(request)) {
        return callback(null, 'Studio.runtime[\'' + request.substring('babel-runtime/'.length) + '\']')
      }

      if (exposedLibraries.indexOf(request) > -1) {
        return callback(null, 'Studio.libraries[\'' + request + '\']')
      }

      if (request === 'jsreport-studio') {
        return callback(null, 'Studio')
      }

      callback()
    }
  ],
  module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' },
      {
        test: /.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          presets: [
            require.resolve('babel-preset-es2015'),
            require.resolve('babel-preset-react'),
            require.resolve('babel-preset-stage-0')
          ]
        }
      },
      {
        test: /\.scss$/,
        loader: 'style!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!postcss-loader!sass?outputStyle=expanded&sourceMap'
      }
    ]
  },
  postcss: function () {
    return [
      require('postcss-flexbugs-fixes'),
      require('autoprefixer')
    ]
  },
  resolveLoader: {
    modulesDirectories: [
      'node_modules', 'node_modules/jsreport-studio-dev/node_modules'
    ]
  },
  resolve: {
    modulesDirectories: [
      'node_modules', 'node_modules/jsreport-studio-dev/node_modules'
    ]
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify('production')
      },
      __DEVELOPMENT__: false
    })
    //
    // // optimizations
    // new webpack.optimize.DedupePlugin(),
    // new webpack.optimize.OccurenceOrderPlugin(),
    // new webpack.optimize.UglifyJsPlugin({
    //   compress: {
    //     warnings: false
    //   }
    // })
  ]
}

var config

if (argv.config) {
  console.log('using custom webpack config at:', argv.config)

  try {
    config = require(path.resolve(process.cwd(), argv.config))
  } catch (e) {
    throw new Error('Error while trying to use config in ' + argv.config + ' : ' + e.message)
  }
} else {
  config = defaultConfig
}

webpack(config, function (err, stats) {
  if (err) {
    console.err(err)
    return process.exit(1)
  }

  var jsonStats = stats.toJson()

  if (jsonStats.errors.length > 0) {
    console.error(jsonStats.errors)
    process.exit(1)
  }

  console.log(stats.toString({ colors: true, chunks: true, cached: false }))

  console.log('webpack build  ok')
})
<|endoftext|>


<commit_before>var path = require('path'),
    requirejs = require('requirejs'),
    rAppid = require(path.join(process.cwd(),'public','js/lib/rAppid.js')).rAppid,
    jsdom = require('jsdom').jsdom,
    flow = require('flow.js').flow,
    fs = require('fs');
fs.existsSync || (fs.existsSync = path.existsSync);

var createOnBuildWriteFnc = function(shim){
    return function(moduleName,path, contents){
        if(shim[moduleName]){
            contents = "define('"+moduleName+"', function () { " + contents + "; return "+ shim[moduleName].exports+"; });"
        } else if (moduleName == "rAppid") {
            // rollback content changes
            contents = contents.replace(/EMPTYDEFINE/g, 'define');
        }
        return contents;
    }
};

var optimizeConfig = {
    baseUrl: './public',
    modules: [],
    dir: "public-build",
    optimize: 'uglify',
    optimizeCss: "standard",
    nodeRequire: require,
    findNestedDependencies: false,
    optimizeAllPluginResources: true,
    preserveLicenseComments: false,
    //If using UglifyJS for script optimization, these config options can be
    //used to pass configuration values to UglifyJS.
    //See https://github.com/mishoo/UglifyJS for the possible values.
    uglify: {
        toplevel: true,
        ascii_only: true,
        beautify: false,
        "line-len": 1000
    },
    "paths": {
        "rAppid": "js/lib/rAppid",
        "text": 'js/plugins/text',
        "xaml": "js/plugins/xaml",
        "json": "js/plugins/json",
        "raw": "js/plugins/raw",
        "flow": "js/lib/flow",
        "inherit": "js/lib/inherit",
        "underscore": "js/lib/underscore",
        "JSON": "js/lib/JSON",
        "moment": "js/lib/moment"
    },
    onBuildRead: function (moduleName, path, contents) {

        if (moduleName == "rAppid") {
            // remove defines, because we don't want dep tracing
            contents = contents.replace(/define/g, 'EMPTYDEFINE');
        }
        return contents;
    },
    skipModuleInsertion: true,
    namespaceMap: rAppid.defaultNamespaceMap,
    rewriteMap: rAppid.defaultRewriteMap
};

var build = function (args, callback) {
    var basePath = process.cwd();
    // read out config.json
    var buildConfigPath = path.join(basePath, "build.json");
    var publicPath = path.join(basePath, "public");

    if (!path.existsSync(buildConfigPath)) {
        callback("Couldn't find build.json in " + buildConfigPath);
        return;
    }

    if (!path.existsSync(publicPath)) {
        callback("Couldn't find public dir");
        return;
    }

    var configPath = path.join(publicPath, "config.json");
    if (!path.existsSync(configPath)) {
        callback("Couldn't find config.json in " + publicPath);
        return;
    }

    var config = JSON.parse(fs.readFileSync(configPath));
    var buildConfig = JSON.parse(fs.readFileSync(buildConfigPath));

    optimizeConfig.onBuildWrite = createOnBuildWriteFnc(config.shim);

    if (buildConfig.uglify === false) {
        optimizeConfig.optimize = 'none';
    }

    var xamlClasses = config.xamlClasses;

    // find modules
    var isXamlClass, moduleConfig, mainModule;
    buildConfig.modules.forEach(function (module, index) {
        isXamlClass = xamlClasses.indexOf(module) > -1;
        moduleConfig = {
            name: module,
            create: true,
            include: []
        };

        if (index === 0) {
            moduleConfig.include = [
                'rAppid',
                'inherit',
                'flow',
                'underscore',
                'js/plugins/json',
                'js/lib/parser',
                'js/core/Bus',
                'js/core/Stage',
                'js/core/WindowManager',
                'js/core/HeadManager',
                'js/core/Injection'];
        }

        var realModuleName = (isXamlClass ? "xaml!" : "") + module;
        if (index === 0) {
            mainModule = module;
        } else {
            moduleConfig.exclude = [mainModule];
        }

        moduleConfig.include.push(realModuleName);

        if(isXamlClass){
            config.optimizedXAML = config.optimizedXAML || [];
            config.optimizedXAML.push(module);
        }

        optimizeConfig.modules.push(moduleConfig);
    });
    optimizeConfig.xamlClasses = config.xamlClasses;
    optimizeConfig.dir = buildConfig.targetDir || optimizeConfig.dir;

    var buildDirPath = path.join(basePath,optimizeConfig.dir);
    var newConfigPath = path.join(buildDirPath, "config.json");

    global.libxml = require("libxml");

    // start optimizing
    requirejs.optimize(optimizeConfig, function (results) {
        // create build-config
        fs.writeFileSync(newConfigPath, JSON.stringify(config));

        var indexFilePath = path.join(buildDirPath, buildConfig.indexFile || "index.html");
        var indexFile = fs.readFileSync(indexFilePath, "utf8");
        var content = String(indexFile);
        content = content.replace("js/lib/rAppid", mainModule);

        fs.writeFileSync(indexFilePath, content);
    });
};

build.usage = "rappidjs build";

module.exports = build;

<commit_msg>added history to core dependencies<commit_after>var path = require('path'),
    requirejs = require('requirejs'),
    rAppid = require(path.join(process.cwd(),'public','js/lib/rAppid.js')).rAppid,
    jsdom = require('jsdom').jsdom,
    flow = require('flow.js').flow,
    fs = require('fs');
fs.existsSync || (fs.existsSync = path.existsSync);

var createOnBuildWriteFnc = function(shim){
    return function(moduleName,path, contents){
        if(shim[moduleName]){
            contents = "define('"+moduleName+"', function () { " + contents + "; return "+ shim[moduleName].exports+"; });"
        } else if (moduleName == "rAppid") {
            // rollback content changes
            contents = contents.replace(/EMPTYDEFINE/g, 'define');
        }
        return contents;
    }
};

var optimizeConfig = {
    baseUrl: './public',
    modules: [],
    dir: "public-build",
    optimize: 'uglify',
    optimizeCss: "standard",
    nodeRequire: require,
    findNestedDependencies: false,
    optimizeAllPluginResources: true,
    preserveLicenseComments: false,
    //If using UglifyJS for script optimization, these config options can be
    //used to pass configuration values to UglifyJS.
    //See https://github.com/mishoo/UglifyJS for the possible values.
    uglify: {
        toplevel: true,
        ascii_only: true,
        beautify: false,
        "line-len": 1000
    },
    "paths": {
        "rAppid": "js/lib/rAppid",
        "text": 'js/plugins/text',
        "xaml": "js/plugins/xaml",
        "json": "js/plugins/json",
        "raw": "js/plugins/raw",
        "flow": "js/lib/flow",
        "inherit": "js/lib/inherit",
        "underscore": "js/lib/underscore",
        "JSON": "js/lib/JSON",
        "moment": "js/lib/moment"
    },
    onBuildRead: function (moduleName, path, contents) {

        if (moduleName == "rAppid") {
            // remove defines, because we don't want dep tracing
            contents = contents.replace(/define/g, 'EMPTYDEFINE');
        }
        return contents;
    },
    skipModuleInsertion: true,
    namespaceMap: rAppid.defaultNamespaceMap,
    rewriteMap: rAppid.defaultRewriteMap
};

var build = function (args, callback) {
    var basePath = process.cwd();
    // read out config.json
    var buildConfigPath = path.join(basePath, "build.json");
    var publicPath = path.join(basePath, "public");

    if (!path.existsSync(buildConfigPath)) {
        callback("Couldn't find build.json in " + buildConfigPath);
        return;
    }

    if (!path.existsSync(publicPath)) {
        callback("Couldn't find public dir");
        return;
    }

    var configPath = path.join(publicPath, "config.json");
    if (!path.existsSync(configPath)) {
        callback("Couldn't find config.json in " + publicPath);
        return;
    }

    var config = JSON.parse(fs.readFileSync(configPath));
    var buildConfig = JSON.parse(fs.readFileSync(buildConfigPath));

    optimizeConfig.onBuildWrite = createOnBuildWriteFnc(config.shim);

    if (buildConfig.uglify === false) {
        optimizeConfig.optimize = 'none';
    }

    var xamlClasses = config.xamlClasses;

    // find modules
    var isXamlClass, moduleConfig, mainModule;
    buildConfig.modules.forEach(function (module, index) {
        isXamlClass = xamlClasses.indexOf(module) > -1;
        moduleConfig = {
            name: module,
            create: true,
            include: []
        };

        if (index === 0) {
            moduleConfig.include = [
                'rAppid',
                'inherit',
                'flow',
                'underscore',
                'js/plugins/json',
                'js/lib/parser',
                'js/core/Bus',
                'js/core/Stage',
                'js/core/WindowManager',
                'js/core/HeadManager',
                'js/core/Injection',
                'js/core/History'];
        }

        var realModuleName = (isXamlClass ? "xaml!" : "") + module;
        if (index === 0) {
            mainModule = module;
        } else {
            moduleConfig.exclude = [mainModule];
        }

        moduleConfig.include.push(realModuleName);

        if(isXamlClass){
            config.optimizedXAML = config.optimizedXAML || [];
            config.optimizedXAML.push(module);
        }

        optimizeConfig.modules.push(moduleConfig);
    });
    optimizeConfig.xamlClasses = config.xamlClasses;
    optimizeConfig.dir = buildConfig.targetDir || optimizeConfig.dir;

    var buildDirPath = path.join(basePath,optimizeConfig.dir);
    var newConfigPath = path.join(buildDirPath, "config.json");

    global.libxml = require("libxml");

    // start optimizing
    requirejs.optimize(optimizeConfig, function (results) {
        // create build-config
        fs.writeFileSync(newConfigPath, JSON.stringify(config));

        var indexFilePath = path.join(buildDirPath, buildConfig.indexFile || "index.html");
        var indexFile = fs.readFileSync(indexFilePath, "utf8");
        var content = String(indexFile);
        content = content.replace("js/lib/rAppid", mainModule);

        fs.writeFileSync(indexFilePath, content);
    });
};

build.usage = "rappidjs build";

module.exports = build;

<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var updateNotifier = require('update-notifier')
var _db = require('underscore-db')
var yargs = require('yargs')
var chalk = require('chalk')
var got = require('got')
var pkg = require('../package.json')
var jsonServer = require('../src')

updateNotifier({packageName: pkg.name, packageVersion: pkg.version}).notify()

// Parse arguments
var argv = yargs
  .usage('$0 [options] <source>')
  .options({
    port: {
      alias: 'p',
      description: 'Set port',
      default: 3000
    },
    host: {
      alias: 'H',
      description: 'Set host',
      default: '0.0.0.0'
    },
    watch: {
      alias: 'w',
      description: 'Reload database on JSON file change'
    },
    routes: {
      alias: 'r',
      description: 'Load routes file'
    }
  })
  .help('help').alias('help', 'h')
  .version(pkg.version).alias('version', 'v')
  .example('$0 db.json', '')
  .example('$0 file.js', '')
  .example('$0 http://example.com/db.json', '')
  .epilog('https://github.com/typicode/json-server')
  .require(1, 'Missing <source> argument')
  .argv

function showResources (hostname, port, object) {
  for (var prop in object) {
    console.log(chalk.gray('  http://' + hostname + ':' + port + '/') + chalk.cyan(prop))
  }
}

function start (object, filename) {
  var port = process.env.PORT || argv.port
  var hostname = argv.host === '0.0.0.0' ? 'localhost' : argv.host

  console.log()
  showResources(hostname, port, object)
  console.log()
  console.log(
    'You can now go to ' + chalk.gray('http://' + hostname + ':' + port)
  )
  console.log()
  console.log(
    'Enter ' + chalk.cyan('s') + ' at any time to create a snapshot of the db'
  )

  // Snapshot
  process.stdin.resume()
  process.stdin.setEncoding('utf8')
  process.stdin.on('data', function (chunk) {
    if (chunk.trim().toLowerCase() === 's') {
      var file = 'db-' + Date.now() + '.json'
      _db.save(object, file)
      console.log('Saved snapshot to ' + chalk.cyan(file) + '\n')
    }
  })

  // Rewriter
  var routes = JSON.parse(fs.readFileSync(process.cwd() + '/' + argv.routes))
  var rewriter = jsonServer.rewriter(routes)

  // Router
  var router = jsonServer.router(filename ? filename : object)

  // Watcher
  if (filename && argv.watch) {
    console.log('Watching', chalk.cyan(source))

    var db = router.db
    var watchedDir = path.dirname(filename)
    var watchedFile = path.basename(filename)

    fs.watch(watchedDir, function (event, changedFile) {
      // lowdb generates 'rename' event on watchedFile
      // using it to know if file has been modified by the user
      if (event === 'change' && changedFile === watchedFile) {
        console.log(chalk.cyan(source), 'has changed, reloading database')

        try {
          var watchedFileObject = JSON.parse(fs.readFileSync(filename))
          db.object = watchedFileObject
          showResources(hostname, port, db.object)
        } catch (e) {
          console.log('Can\'t parse', chalk.cyan(source))
          console.log(e.message)
        }

        console.log()
      }
    })
  }
  console.log()

  var server = jsonServer.create()
  server.use(jsonServer.defaults)
  server.use(rewriter)
  server.use(router)
  server.listen(port, argv.host)
}

// Set file and port
var source = argv._[0]

// Say hi, load file and start server
console.log(chalk.cyan('  {^_^} Hi!\n'))
console.log('Loading database from ' + chalk.cyan(source))

// Remote source
if (/^(http|https):/.test(source)) {
  got(source, function (err, data) {
    if (err) {
      console.log('Error', err)
      process.exit(1)
    }
    var object = JSON.parse(data)
    start(object)
  })
// JSON file
} else if (/\.json$/.test(source)) {
  var filename = process.cwd() + '/' + source
  var object = require(filename)
  start(object, filename)
// JS file
} else if (/\.js$/.test(source)) {
  var object = require(process.cwd() + '/' + source)()
  start(object)
}
<commit_msg>Fix CLI<commit_after>#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var updateNotifier = require('update-notifier')
var _db = require('underscore-db')
var yargs = require('yargs')
var chalk = require('chalk')
var got = require('got')
var pkg = require('../package.json')
var jsonServer = require('../src')

updateNotifier({packageName: pkg.name, packageVersion: pkg.version}).notify()

// Parse arguments
var argv = yargs
  .usage('$0 [options] <source>')
  .options({
    port: {
      alias: 'p',
      description: 'Set port',
      default: 3000
    },
    host: {
      alias: 'H',
      description: 'Set host',
      default: '0.0.0.0'
    },
    watch: {
      alias: 'w',
      description: 'Reload database on JSON file change'
    },
    routes: {
      alias: 'r',
      description: 'Load routes file'
    }
  })
  .help('help').alias('help', 'h')
  .version(pkg.version).alias('version', 'v')
  .example('$0 db.json', '')
  .example('$0 file.js', '')
  .example('$0 http://example.com/db.json', '')
  .epilog('https://github.com/typicode/json-server')
  .require(1, 'Missing <source> argument')
  .argv

function showResources (hostname, port, object) {
  for (var prop in object) {
    console.log(chalk.gray('  http://' + hostname + ':' + port + '/') + chalk.cyan(prop))
  }
}

function start (object, filename) {
  var port = process.env.PORT || argv.port
  var hostname = argv.host === '0.0.0.0' ? 'localhost' : argv.host

  console.log()
  showResources(hostname, port, object)
  console.log()
  console.log(
    'You can now go to ' + chalk.gray('http://' + hostname + ':' + port)
  )
  console.log()
  console.log(
    'Enter ' + chalk.cyan('s') + ' at any time to create a snapshot of the db'
  )

  // Snapshot
  process.stdin.resume()
  process.stdin.setEncoding('utf8')
  process.stdin.on('data', function (chunk) {
    if (chunk.trim().toLowerCase() === 's') {
      var file = 'db-' + Date.now() + '.json'
      _db.save(object, file)
      console.log('Saved snapshot to ' + chalk.cyan(file) + '\n')
    }
  })

  // Router
  var router = jsonServer.router(filename ? filename : object)

  // Watcher
  if (filename && argv.watch) {
    console.log('Watching', chalk.cyan(source))

    var db = router.db
    var watchedDir = path.dirname(filename)
    var watchedFile = path.basename(filename)

    fs.watch(watchedDir, function (event, changedFile) {
      // lowdb generates 'rename' event on watchedFile
      // using it to know if file has been modified by the user
      if (event === 'change' && changedFile === watchedFile) {
        console.log(chalk.cyan(source), 'has changed, reloading database')

        try {
          var watchedFileObject = JSON.parse(fs.readFileSync(filename))
          db.object = watchedFileObject
          showResources(hostname, port, db.object)
        } catch (e) {
          console.log('Can\'t parse', chalk.cyan(source))
          console.log(e.message)
        }

        console.log()
      }
    })
  }
  console.log()

  var server = jsonServer.create()
  server.use(jsonServer.defaults)

  // Rewriter
  if (argv.routes) {
    var routes = JSON.parse(fs.readFileSync(process.cwd() + '/' + argv.routes))
    var rewriter = jsonServer.rewriter(routes)
    server.use(rewriter)
  }

  server.use(router)
  server.listen(port, argv.host)
}

// Set file and port
var source = argv._[0]

// Say hi, load file and start server
console.log(chalk.cyan('  {^_^} Hi!\n'))
console.log('Loading database from ' + chalk.cyan(source))

// Remote source
if (/^(http|https):/.test(source)) {
  got(source, function (err, data) {
    if (err) {
      console.log('Error', err)
      process.exit(1)
    }
    var object = JSON.parse(data)
    start(object)
  })
// JSON file
} else if (/\.json$/.test(source)) {
  var filename = process.cwd() + '/' + source
  var object = require(filename)
  start(object, filename)
// JS file
} else if (/\.js$/.test(source)) {
  var object = require(process.cwd() + '/' + source)()
  start(object)
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

// Native
const http = require('http');
const path = require('path');
const fs = require('fs');
const {promisify} = require('util');
const {URL} = require('url');

// Packages
const Ajv = require('ajv');
const checkForUpdate = require('update-check');
const chalk = require('chalk');
const arg = require('arg');
const handler = require('serve-handler');
const schema = require('@zeit/schemas/deployment/config-static');

// Utilities
const pkg = require('../package');

const readFile = promisify(fs.readFile);

const warning = message => chalk`{yellow WARNING:} ${message}`;
const info = message => chalk`{magenta INFO:} ${message}`;
const error = message => chalk`{red ERROR:} ${message}`;

const updateCheck = async isDebugging => {
	let update = null;

	try {
		update = await checkForUpdate(pkg);
	} catch (err) {
		const suffix = isDebugging ? ':' : ' (use `--debug` to see full error)';
		console.error(warning(`Checking for updates failed${suffix}`));

		if (isDebugging) {
			console.error(err);
		}
	}

	if (!update) {
		return;
	}

	console.log(`${chalk.bgRed('UPDATE AVAILABLE')} The latest version of \`serve\` is ${update.latest}`);
};

const getHelp = () => chalk`
  {bold.cyan serve} - Static file serving and directory listing

  {bold USAGE}

      {bold $} {cyan serve} --help
      {bold $} {cyan serve} --version
      {bold $} {cyan serve} [-l {underline listen_uri} [-l ...]] [{underline directory}]

      By default, {cyan serve} will listen on {bold 0.0.0.0:3000} and serve the
      current working directory on that address.

      Specifying a single {bold --listen} argument will overwrite the default, not supplement it.

  {bold OPTIONS}

      --help                              Shows this help message

      -v, --version                       Displays the current version of serve

      -l, --listen {underline listen_uri}             Specify a URI endpoint on which to listen (see below) -
                                          more than one may be specified to listen in multiple places

      -d, --debug                         Show debugging information

      -s, --single                        Rewrite all not-found requests to \`index.html\`

      -c, --config                        Specify custom path to \`serve.json\`

  {bold ENDPOINTS}

      Listen endpoints (specified by the {bold --listen} or {bold -l} options above) instruct {cyan serve}
      to listen on one or more interfaces/ports, UNIX domain sockets, or Windows named pipes.

      For TCP ports on hostname "localhost":

          {bold $} {cyan serve} -l {underline 1234}

      For TCP (traditional host/port) endpoints:

          {bold $} {cyan serve} -l tcp://{underline hostname}:{underline 1234}

      For UNIX domain socket endpoints:

          {bold $} {cyan serve} -l unix:{underline /path/to/socket.sock}

      For Windows named pipe endpoints:

          {bold $} {cyan serve} -l pipe:\\\\.\\pipe\\{underline PipeName}
`;

const parseEndpoint = str => {
	if (!isNaN(str)) {
		return [str];
	}

	const url = new URL(str);

	switch (url.protocol) {
	case 'pipe:': {
		// some special handling
		const cutStr = str.replace(/^pipe:/, '');

		if (cutStr.slice(0, 4) !== '\\\\.\\') {
			throw new Error(`Invalid Windows named pipe endpoint: ${str}`);
		}

		return [cutStr];
	}
	case 'unix:':
		if (!url.pathname) {
			throw new Error(`Invalid UNIX domain socket endpoint: ${str}`);
		}

		return [url.pathname];
	case 'tcp:':
		url.port = url.port || '3000';
		return [parseInt(url.port, 10), url.hostname];
	default:
		throw new Error(`Unknown --listen endpoint scheme (protocol): ${url.protocol}`);
	}
};

const registerShutdown = fn => {
	let run = false;

	const wrapper = () => {
		if (!run) {
			run = true;
			fn();
		}
	};

	process.on('SIGINT', wrapper);
	process.on('SIGTERM', wrapper);
	process.on('exit', wrapper);
};

const startEndpoint = (endpoint, config) => {
	const server = http.createServer((request, response) => handler(request, response, config));

	server.on('error', err => {
		console.error('serve:', err.stack);
		process.exit(1);
	});

	server.listen(...endpoint, () => {
		const details = server.address();
		registerShutdown(() => server.close());

		if (typeof details === 'string') {
			console.log(info(`Accepting connections at ${details}`));
		} else if (typeof details === 'object' && details.port) {
			const address = details.address === '::' ? 'localhost' : details.address;
			console.log(info(`Accepting connections at http://${address}:${details.port}`));
		} else {
			console.log(info('Accepting connections'));
		}
	});
};

const loadConfig = async (cwd, entry, args) => {
	const files = [
		'serve.json',
		'now.json',
		'package.json'
	];

	if (args['--config']) {
		files.unshift(args['--config']);
	}

	const config = {};

	for (const file of files) {
		const location = path.join(entry, file);
		let content = null;

		try {
			content = await readFile(location, 'utf8');
		} catch (err) {
			if (err.code === 'ENOENT') {
				continue;
			}

			console.error(error(`Not able to read ${location}: ${err.message}`));
			process.exit(1);
		}

		try {
			content = JSON.parse(content);
		} catch (err) {
			console.error(error(`Could not parse ${location} as JSON: ${err.message}`));
			process.exit(1);
		}

		if (typeof content !== 'object') {
			console.error(warning(`Didn't find a valid object in ${location}. Skipping...`));
			continue;
		}

		try {
			switch (file) {
			case 'now.json':
				content = content.static;
				break;
			case 'package.json':
				content = content.now.static;
				break;
			}
		} catch (err) {
			continue;
		}

		Object.assign(config, content);
		console.log(info(`Discovered configuration in \`${file}\``));

		break;
	}

	if (entry) {
		const {public} = config;
		config.public = path.relative(cwd, (public ? path.join(entry, public) : entry));
	}

	if (Object.keys(config).length !== 0) {
		const ajv = new Ajv();
		const validateSchema = ajv.compile(schema);

		if (!validateSchema(config)) {
			const defaultMessage = error('The configuration you provided is wrong:');
			const {message, params} = validateSchema.errors[0];

			console.error(`${defaultMessage}\n${message}\n${JSON.stringify(params)}`);
			process.exit(1);
		}
	}

	return config;
};

(async () => {
	let args = null;

	try {
		args = arg({
			'--help': Boolean,
			'--version': Boolean,
			'--listen': [parseEndpoint],
			'--single': Boolean,
			'--debug': Boolean,
			'--config': String,
			'-h': '--help',
			'-v': '--version',
			'-l': '--listen',
			'-s': '--single',
			'-d': '--debug',
			'-c': '--config',
			// This is deprecated and only for backwards-compatibility.
			'-p': '--listen'
		});
	} catch (err) {
		console.error(error(err.message));
		process.exit(1);
	}

	await updateCheck(args['--debug']);

	if (args['--version']) {
		console.log(pkg.version);
		return;
	}

	if (args['--help']) {
		console.log(getHelp());
		return;
	}

	if (!args['--listen']) {
		// Default endpoint
		args['--listen'] = [[3000]];
	}

	if (args._.length > 1) {
		console.error(error('Please provide one path argument at maximum'));
		process.exit(1);
	}

	const cwd = process.cwd();
	const entry = args._.length > 0 ? path.join(cwd, args._[0]) : cwd;

	const config = await loadConfig(cwd, entry, args);

	if (args['--single']) {
		const {rewrites} = config;
		const existingRewrites = Array.isArray(rewrites) ? rewrites : [];

		// As the first rewrite rule, make `--single` work
		config.rewrites = [{
			source: '**',
			destination: '/index.html'
		}, ...existingRewrites];
	}

	for (const endpoint of args['--listen']) {
		startEndpoint(endpoint, config);
	}

	registerShutdown(() => {
		console.log(`\n${info('Gracefully shutting down. Please wait...')}`);

		process.on('SIGINT', () => {
			console.log(`\n${warning('Force-closing all open sockets...')}`);
			process.exit(0);
		});
	});
})();
<commit_msg>Reverted default port back to 5000 (#427)<commit_after>#!/usr/bin/env node

// Native
const http = require('http');
const path = require('path');
const fs = require('fs');
const {promisify} = require('util');
const {URL} = require('url');

// Packages
const Ajv = require('ajv');
const checkForUpdate = require('update-check');
const chalk = require('chalk');
const arg = require('arg');
const handler = require('serve-handler');
const schema = require('@zeit/schemas/deployment/config-static');

// Utilities
const pkg = require('../package');

const readFile = promisify(fs.readFile);

const warning = message => chalk`{yellow WARNING:} ${message}`;
const info = message => chalk`{magenta INFO:} ${message}`;
const error = message => chalk`{red ERROR:} ${message}`;

const updateCheck = async isDebugging => {
	let update = null;

	try {
		update = await checkForUpdate(pkg);
	} catch (err) {
		const suffix = isDebugging ? ':' : ' (use `--debug` to see full error)';
		console.error(warning(`Checking for updates failed${suffix}`));

		if (isDebugging) {
			console.error(err);
		}
	}

	if (!update) {
		return;
	}

	console.log(`${chalk.bgRed('UPDATE AVAILABLE')} The latest version of \`serve\` is ${update.latest}`);
};

const getHelp = () => chalk`
  {bold.cyan serve} - Static file serving and directory listing

  {bold USAGE}

      {bold $} {cyan serve} --help
      {bold $} {cyan serve} --version
      {bold $} {cyan serve} [-l {underline listen_uri} [-l ...]] [{underline directory}]

      By default, {cyan serve} will listen on {bold 0.0.0.0:5000} and serve the
      current working directory on that address.

      Specifying a single {bold --listen} argument will overwrite the default, not supplement it.

  {bold OPTIONS}

      --help                              Shows this help message

      -v, --version                       Displays the current version of serve

      -l, --listen {underline listen_uri}             Specify a URI endpoint on which to listen (see below) -
                                          more than one may be specified to listen in multiple places

      -d, --debug                         Show debugging information

      -s, --single                        Rewrite all not-found requests to \`index.html\`

      -c, --config                        Specify custom path to \`serve.json\`

  {bold ENDPOINTS}

      Listen endpoints (specified by the {bold --listen} or {bold -l} options above) instruct {cyan serve}
      to listen on one or more interfaces/ports, UNIX domain sockets, or Windows named pipes.

      For TCP ports on hostname "localhost":

          {bold $} {cyan serve} -l {underline 1234}

      For TCP (traditional host/port) endpoints:

          {bold $} {cyan serve} -l tcp://{underline hostname}:{underline 1234}

      For UNIX domain socket endpoints:

          {bold $} {cyan serve} -l unix:{underline /path/to/socket.sock}

      For Windows named pipe endpoints:

          {bold $} {cyan serve} -l pipe:\\\\.\\pipe\\{underline PipeName}
`;

const parseEndpoint = str => {
	if (!isNaN(str)) {
		return [str];
	}

	const url = new URL(str);

	switch (url.protocol) {
	case 'pipe:': {
		// some special handling
		const cutStr = str.replace(/^pipe:/, '');

		if (cutStr.slice(0, 4) !== '\\\\.\\') {
			throw new Error(`Invalid Windows named pipe endpoint: ${str}`);
		}

		return [cutStr];
	}
	case 'unix:':
		if (!url.pathname) {
			throw new Error(`Invalid UNIX domain socket endpoint: ${str}`);
		}

		return [url.pathname];
	case 'tcp:':
		url.port = url.port || '5000';
		return [parseInt(url.port, 10), url.hostname];
	default:
		throw new Error(`Unknown --listen endpoint scheme (protocol): ${url.protocol}`);
	}
};

const registerShutdown = fn => {
	let run = false;

	const wrapper = () => {
		if (!run) {
			run = true;
			fn();
		}
	};

	process.on('SIGINT', wrapper);
	process.on('SIGTERM', wrapper);
	process.on('exit', wrapper);
};

const startEndpoint = (endpoint, config) => {
	const server = http.createServer((request, response) => handler(request, response, config));

	server.on('error', err => {
		console.error('serve:', err.stack);
		process.exit(1);
	});

	server.listen(...endpoint, () => {
		const details = server.address();
		registerShutdown(() => server.close());

		if (typeof details === 'string') {
			console.log(info(`Accepting connections at ${details}`));
		} else if (typeof details === 'object' && details.port) {
			const address = details.address === '::' ? 'localhost' : details.address;
			console.log(info(`Accepting connections at http://${address}:${details.port}`));
		} else {
			console.log(info('Accepting connections'));
		}
	});
};

const loadConfig = async (cwd, entry, args) => {
	const files = [
		'serve.json',
		'now.json',
		'package.json'
	];

	if (args['--config']) {
		files.unshift(args['--config']);
	}

	const config = {};

	for (const file of files) {
		const location = path.join(entry, file);
		let content = null;

		try {
			content = await readFile(location, 'utf8');
		} catch (err) {
			if (err.code === 'ENOENT') {
				continue;
			}

			console.error(error(`Not able to read ${location}: ${err.message}`));
			process.exit(1);
		}

		try {
			content = JSON.parse(content);
		} catch (err) {
			console.error(error(`Could not parse ${location} as JSON: ${err.message}`));
			process.exit(1);
		}

		if (typeof content !== 'object') {
			console.error(warning(`Didn't find a valid object in ${location}. Skipping...`));
			continue;
		}

		try {
			switch (file) {
			case 'now.json':
				content = content.static;
				break;
			case 'package.json':
				content = content.now.static;
				break;
			}
		} catch (err) {
			continue;
		}

		Object.assign(config, content);
		console.log(info(`Discovered configuration in \`${file}\``));

		break;
	}

	if (entry) {
		const {public} = config;
		config.public = path.relative(cwd, (public ? path.join(entry, public) : entry));
	}

	if (Object.keys(config).length !== 0) {
		const ajv = new Ajv();
		const validateSchema = ajv.compile(schema);

		if (!validateSchema(config)) {
			const defaultMessage = error('The configuration you provided is wrong:');
			const {message, params} = validateSchema.errors[0];

			console.error(`${defaultMessage}\n${message}\n${JSON.stringify(params)}`);
			process.exit(1);
		}
	}

	return config;
};

(async () => {
	let args = null;

	try {
		args = arg({
			'--help': Boolean,
			'--version': Boolean,
			'--listen': [parseEndpoint],
			'--single': Boolean,
			'--debug': Boolean,
			'--config': String,
			'-h': '--help',
			'-v': '--version',
			'-l': '--listen',
			'-s': '--single',
			'-d': '--debug',
			'-c': '--config',
			// This is deprecated and only for backwards-compatibility.
			'-p': '--listen'
		});
	} catch (err) {
		console.error(error(err.message));
		process.exit(1);
	}

	await updateCheck(args['--debug']);

	if (args['--version']) {
		console.log(pkg.version);
		return;
	}

	if (args['--help']) {
		console.log(getHelp());
		return;
	}

	if (!args['--listen']) {
		// Default endpoint
		args['--listen'] = [[5000]];
	}

	if (args._.length > 1) {
		console.error(error('Please provide one path argument at maximum'));
		process.exit(1);
	}

	const cwd = process.cwd();
	const entry = args._.length > 0 ? path.join(cwd, args._[0]) : cwd;

	const config = await loadConfig(cwd, entry, args);

	if (args['--single']) {
		const {rewrites} = config;
		const existingRewrites = Array.isArray(rewrites) ? rewrites : [];

		// As the first rewrite rule, make `--single` work
		config.rewrites = [{
			source: '**',
			destination: '/index.html'
		}, ...existingRewrites];
	}

	for (const endpoint of args['--listen']) {
		startEndpoint(endpoint, config);
	}

	registerShutdown(() => {
		console.log(`\n${info('Gracefully shutting down. Please wait...')}`);

		process.on('SIGINT', () => {
			console.log(`\n${warning('Force-closing all open sockets...')}`);
			process.exit(0);
		});
	});
})();
<|endoftext|>


<commit_before>/*
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *  Contributor(s):
 *  - LouCypher (original code)
 */

const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/Services.jsm");

/**
 * Start setting default preferences
 * http://starkravingfinkle.org/blog/2011/01/restartless-add-ons-%e2%80%93-default-preferences/
 */
const PREF_BRANCH = "extensions.json-inspector@loucypher.";
const PREFS = {
  description: "chrome://json-inspector/locale/json-inspector.properties",
  //firstRun: true,
  copyResponse: 0
};

let addonId;

function setDefaultPrefs() {
  try {
    // Check for old pref from v1.0
    let prefs = Services.prefs.getBranch(PREF_BRANCH);
    if (prefs.getPrefType("copyResponse") == prefs.PREF_BOOL) {
      prefs.clearUserPref("copyResponse");  // Clear/remove old pref
      prefs.setIntPref("copyResponse", 2);  // Convert to new pref
    }
  } catch(ex) {
  }

  let branch = Services.prefs.getDefaultBranch(PREF_BRANCH);
  for (let [key, val] in Iterator(PREFS)) {
    switch (typeof val) {
      case "boolean":
        branch.setBoolPref(key, val);
        break;
      case "number":
        branch.setIntPref(key, val);
        break;
      case "string":
        branch.setCharPref(key, val);
        break;
    }
  }
}
/*
 * End setting default preferences
 **/

function log(aString) {
  Services.console.logStringMessage("JSON Inspector:\n" + aString);
}

function setResourceName(aData) aData.id.toLowerCase().match(/[^\@]+/).toString()
                                                      .replace(/[^\w]/g, "");

function resProtocolHandler(aResourceName, aURI) {
  Services.io.getProtocolHandler("resource")
             .QueryInterface(Ci.nsIResProtocolHandler)
             .setSubstitution(aResourceName, aURI, null)
}

function getJSIwindow() Services.wm.getMostRecentWindow("devtools:jsonInspector");

function closeJSIwindow() {
  let win = getJSIwindow();
  if (win)
    win.close();
}

function jsonInspector(aEvent) {
  let win = getJSIwindow();
  if (win)
    win.focus();

  else {
    let node = aEvent.target;
    let globalWin = node.ownerGlobal ? node.ownerGlobal : node.ownerDocument.defaultView;
    globalWin.openDialog("chrome://json-inspector/content/", "json-inspector",
                         "chrome, dialog=no, centerscreen, minimizable, resizable");
  }
}

function addCommand(aDocument, aId, aLabel, aCallback) {
  let commandset = aDocument.getElementById("mainCommandSet") || // Firefox and SeaMonkey
                   aDocument.getElementById("mailCommands");     // Thunderbird

  let command = commandset.appendChild(aDocument.createElement("command"));
  command.id = aId;
  command.className = "json-inspector";
  command.setAttribute("label", aLabel);
  command.addEventListener("command", aCallback);
}

function addMenuitem(aDocument, aCommand) {
  let menuitem = aDocument.createElement("menuitem");
  menuitem.setAttribute("command", aCommand);
  menuitem.setAttribute("image", "chrome://json-inspector/skin/json.png");
  menuitem.className = "json-inspector menuitem-iconic";
  return menuitem;
}

function init(aWindow) {
  let document = aWindow.document;

  // Insert commands to main commandset
  addCommand(document, "Tools:JSONInspector", "JSON Inspector", jsonInspector);
  addCommand(document, "Tools:JSONInspectorPrefs", "JSON Inspector Options", function() {
    let view = "addons://detail/" + encodeURIComponent(addonId) + "/preferences";
    "toEM" in aWindow ? aWindow.toEM(view)
                      : "openAddonsMgr" in aWindow ? aWindow.openAddonsMgr(view)
                                                   : aWindow.BrowserOpenAddonsMgr(view);
  });

  // Firefox
  // Insert menuitem to Web Developer menu
  let devToolsSeparators = document.querySelectorAll("menuseparator[id$='devToolsEndSeparator']");
  for (let i = 0; i < devToolsSeparators.length; i++) {
    let dtSep = devToolsSeparators[i];
    if (dtSep)
      dtSep.parentNode.insertBefore(addMenuitem(document, "Tools:JSONInspector"), dtSep);
  };

  // SeaMonkey
  // Insert menuitem to Web Development menu
  let toolsPopup = document.getElementById("toolsPopup");
  if (toolsPopup)
    toolsPopup.appendChild(addMenuitem(document, "Tools:JSONInspector"));

  // Thunderbird
  // Insert menuitem to Tools menu
  let prefSep = document.querySelector("#taskPopup #prefSep");
  if (prefSep) {
    prefSep.parentNode.insertBefore(addMenuitem(document, "Tools:JSONInspector"), prefSep);
  }

  // Add options menu
  let appPrefSep = document.querySelector("#appmenu_customizeMenu menuseparator:not([id]):not([class])");
  //log(appPrefSep);
  if (appPrefSep)
    appPrefSep.parentNode.insertBefore(addMenuitem(document, "Tools:JSONInspectorPrefs"), appPrefSep);

  let menupref = document.getElementById("menu_preferences");
  if (menupref)
    menupref.parentNode.insertBefore(addMenuitem(document, "Tools:JSONInspectorPrefs"), menupref);

  let button = document.querySelector("#navigator-toolbox toolbarbutton.json-inspector");
  if (button && button.disabled)
    button.removeAttribute("disabled");

  unload(function() {
    let items = document.querySelectorAll(".json-inspector");
    for (let i = 0; i < items.length; i++) {
      if (items[i].localName != "toolbarbutton")
        items[i].parentNode.removeChild(items[i]);
      else
        items[i].setAttribute("disabled", "true");
    }
  }, aWindow)
}

/**
 * Handle the add-on being activated on install/enable
 */
function startup(data, reason) {
  setDefaultPrefs();

  // Add resource alias
  let resourceName = setResourceName(data);
  //log(resourceName);
  resProtocolHandler(resourceName, data.resourceURI);

  // Load module
  Cu.import("resource://" + resourceName + "/modules/watchwindows.jsm");

  addonId = data.id;

  watchWindows(init);
}

/**
 * Handle the add-on being deactivated on uninstall/disable
 */
function shutdown(data, reason) {
  // Clean up with unloaders when we're deactivating
  if (reason == APP_SHUTDOWN)
    return;

  // Close existing JSON Inspector window
  closeJSIwindow();

  unload();

  // Unload module
  Cu.unload("resource://" + resourceName + "/modules/watchwindows.jsm");

  // Remove resource
  resProtocolHandler(setResourceName(data), null);
}

/**
 * Handle the add-on being installed
 */
function install(data, reason) {
  // Close existing JSON Inspector window
  closeJSIwindow();

/*// Do something on first install only
  let prefs = Services.prefs.getBranch(PREF_BRANCH);
  if (prefs.getBoolPref("firstRun")) {
    // doSomething();
    prefs.setBoolPref("firstRun", false);
  }
*/
}

/**
 * Handle the add-on being uninstalled
 */
function uninstall(data, reason) {
  // Close existing JSON Inspector window
  closeJSIwindow();
}
<commit_msg>Fixed: unable to remove `resourceName` on shutdown<commit_after>/*
 *  This Source Code Form is subject to the terms of the Mozilla Public
 *  License, v. 2.0. If a copy of the MPL was not distributed with this
 *  file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 *  Contributor(s):
 *  - LouCypher (original code)
 */

const { classes: Cc, interfaces: Ci, utils: Cu } = Components;
Cu.import("resource://gre/modules/Services.jsm");

/**
 * Start setting default preferences
 * http://starkravingfinkle.org/blog/2011/01/restartless-add-ons-%e2%80%93-default-preferences/
 */
const PREF_BRANCH = "extensions.json-inspector@loucypher.";
const PREFS = {
  description: "chrome://json-inspector/locale/json-inspector.properties",
  //firstRun: true,
  copyResponse: 0
};

let addonId;

function setDefaultPrefs() {
  try {
    // Check for old pref from v1.0
    let prefs = Services.prefs.getBranch(PREF_BRANCH);
    if (prefs.getPrefType("copyResponse") == prefs.PREF_BOOL) {
      prefs.clearUserPref("copyResponse");  // Clear/remove old pref
      prefs.setIntPref("copyResponse", 2);  // Convert to new pref
    }
  } catch(ex) {
  }

  let branch = Services.prefs.getDefaultBranch(PREF_BRANCH);
  for (let [key, val] in Iterator(PREFS)) {
    switch (typeof val) {
      case "boolean":
        branch.setBoolPref(key, val);
        break;
      case "number":
        branch.setIntPref(key, val);
        break;
      case "string":
        branch.setCharPref(key, val);
        break;
    }
  }
}
/*
 * End setting default preferences
 **/

function log(aString) {
  Services.console.logStringMessage("JSON Inspector:\n" + aString);
}

function setResourceName(aData) aData.id.toLowerCase().match(/[^\@]+/).toString()
                                                      .replace(/[^\w]/g, "");

function resProtocolHandler(aResourceName, aURI) {
  Services.io.getProtocolHandler("resource")
             .QueryInterface(Ci.nsIResProtocolHandler)
             .setSubstitution(aResourceName, aURI, null)
}

function getJSIwindow() Services.wm.getMostRecentWindow("devtools:jsonInspector");

function closeJSIwindow() {
  let win = getJSIwindow();
  if (win)
    win.close();
}

function jsonInspector(aEvent) {
  let win = getJSIwindow();
  if (win)
    win.focus();

  else {
    let node = aEvent.target;
    let globalWin = node.ownerGlobal ? node.ownerGlobal : node.ownerDocument.defaultView;
    globalWin.openDialog("chrome://json-inspector/content/", "json-inspector",
                         "chrome, dialog=no, centerscreen, minimizable, resizable");
  }
}

function addCommand(aDocument, aId, aLabel, aCallback) {
  let commandset = aDocument.getElementById("mainCommandSet") || // Firefox and SeaMonkey
                   aDocument.getElementById("mailCommands");     // Thunderbird

  let command = commandset.appendChild(aDocument.createElement("command"));
  command.id = aId;
  command.className = "json-inspector";
  command.setAttribute("label", aLabel);
  command.addEventListener("command", aCallback);
}

function addMenuitem(aDocument, aCommand) {
  let menuitem = aDocument.createElement("menuitem");
  menuitem.setAttribute("command", aCommand);
  menuitem.setAttribute("image", "chrome://json-inspector/skin/json.png");
  menuitem.className = "json-inspector menuitem-iconic";
  return menuitem;
}

function init(aWindow) {
  let document = aWindow.document;

  // Insert commands to main commandset
  addCommand(document, "Tools:JSONInspector", "JSON Inspector", jsonInspector);
  addCommand(document, "Tools:JSONInspectorPrefs", "JSON Inspector Options", function() {
    let view = "addons://detail/" + encodeURIComponent(addonId) + "/preferences";
    "toEM" in aWindow ? aWindow.toEM(view)
                      : "openAddonsMgr" in aWindow ? aWindow.openAddonsMgr(view)
                                                   : aWindow.BrowserOpenAddonsMgr(view);
  });

  // Firefox
  // Insert menuitem to Web Developer menu
  let devToolsSeparators = document.querySelectorAll("menuseparator[id$='devToolsEndSeparator']");
  for (let i = 0; i < devToolsSeparators.length; i++) {
    let dtSep = devToolsSeparators[i];
    if (dtSep)
      dtSep.parentNode.insertBefore(addMenuitem(document, "Tools:JSONInspector"), dtSep);
  };

  // SeaMonkey
  // Insert menuitem to Web Development menu
  let toolsPopup = document.getElementById("toolsPopup");
  if (toolsPopup)
    toolsPopup.appendChild(addMenuitem(document, "Tools:JSONInspector"));

  // Thunderbird
  // Insert menuitem to Tools menu
  let prefSep = document.querySelector("#taskPopup #prefSep");
  if (prefSep) {
    prefSep.parentNode.insertBefore(addMenuitem(document, "Tools:JSONInspector"), prefSep);
  }

  // Add options menu
  let appPrefSep = document.querySelector("#appmenu_customizeMenu menuseparator:not([id]):not([class])");
  //log(appPrefSep);
  if (appPrefSep)
    appPrefSep.parentNode.insertBefore(addMenuitem(document, "Tools:JSONInspectorPrefs"), appPrefSep);

  let menupref = document.getElementById("menu_preferences");
  if (menupref)
    menupref.parentNode.insertBefore(addMenuitem(document, "Tools:JSONInspectorPrefs"), menupref);

  let button = document.querySelector("#navigator-toolbox toolbarbutton.json-inspector");
  if (button && button.disabled)
    button.removeAttribute("disabled");

  unload(function() {
    let items = document.querySelectorAll(".json-inspector");
    for (let i = 0; i < items.length; i++) {
      if (items[i].localName != "toolbarbutton")
        items[i].parentNode.removeChild(items[i]);
      else
        items[i].setAttribute("disabled", "true");
    }
  }, aWindow)
}

/**
 * Handle the add-on being activated on install/enable
 */
function startup(data, reason) {
  setDefaultPrefs();

  let resourceName = setResourceName(data);
  //log(resourceName);

  // Add resource alias
  resProtocolHandler(resourceName, data.resourceURI);

  // Load module
  Cu.import("resource://" + resourceName + "/modules/watchwindows.jsm");

  addonId = data.id;

  watchWindows(init);
}

/**
 * Handle the add-on being deactivated on uninstall/disable
 */
function shutdown(data, reason) {
  // Clean up with unloaders when we're deactivating
  if (reason == APP_SHUTDOWN)
    return;

  // Close existing JSON Inspector window
  closeJSIwindow();

  unload();

  let resourceName = setResourceName(data);

  // Unload module
  Cu.unload("resource://" + resourceName + "/modules/watchwindows.jsm");

  // Remove resource
  resProtocolHandler(resourceName, null);
}

/**
 * Handle the add-on being installed
 */
function install(data, reason) {
  // Close existing JSON Inspector window
  closeJSIwindow();

/*// Do something on first install only
  let prefs = Services.prefs.getBranch(PREF_BRANCH);
  if (prefs.getBoolPref("firstRun")) {
    // doSomething();
    prefs.setBoolPref("firstRun", false);
  }
*/
}

/**
 * Handle the add-on being uninstalled
 */
function uninstall(data, reason) {
  // Close existing JSON Inspector window
  closeJSIwindow();
}
<|endoftext|>


<commit_before>'use strict'

let _ = require('lodash')
let moment = require('moment')
let winston = require('winston')
let request = require('request')
let WebClient = require('@slack/client').WebClient
let config = require('../config')
let web = new WebClient(config.SLACK_API_TOKEN)

let isWeekend = () => {
  let weekDay = moment().day()
  return weekDay === 0 || weekDay === 6
}

let postMessageHandler = (err, info) => {
  if (err) return winston.error('SLACK: postMessage failed:', err)
  if (info && !info.ok) return winston.error('SLACK: invalid postMessage response:', info)
}

let onlySubscribed = (allowed) => (service) => allowed.indexOf(service.name) !== -1
let onlyUnsubscribed = (allowed) => (service) => allowed.indexOf(service.name) === -1
let getTitle = (service) => service.title

let prepareMessage = (json, subscribedServices) => {
  let allServices = config.SERVICES
  let availableServices = _.map(_.filter(allServices, onlyUnsubscribed(subscribedServices)), getTitle)
  let message = 'Other available restaurants: ' + availableServices.join(', ') + '\n\n'

  let jsonMenus = _.filter(json, onlySubscribed(subscribedServices))
  for (let i = 0; i < jsonMenus.length; i++) {
    message += `*${jsonMenus[i].title}*\n`

    if (!jsonMenus[i].menu[0]) {
      message += 'No menu was found today, check it out yourself and report bugs to @michal.brasna!\n'
    } else {
      for (let j = 0; j < jsonMenus[i].menu[0].items.length; j++) {
        let menuItem = jsonMenus[i].menu[0].items[j]
        message += `- ${menuItem.item} (${menuItem.amount}) _${menuItem.price}_\n`
      }
    }

    message += '\n'
  }

  return message
}

// don't bother on weekends
if (isWeekend()) process.exit(0)

request(config.URL + 'api/next', (err, response, body) => {
  if (err) return winston.error('SLACK: request failed', err)

  let json = null
  try {
    json = JSON.parse(body)
  } catch (e) {
    return winston.error('SLACK: invalid JSON', e, body)
  }

  let options = {
    username: 'sbks-luncher'
  }

  for (let i = 0; i < config.NOTIFICATIONS.length; i++) {
    let message = prepareMessage(json, config.NOTIFICATIONS[i].services)
    web.chat.postMessage(config.NOTIFICATIONS[i].user, message, options, postMessageHandler)
  }
})
<commit_msg>Dump statusCode and statusMessage on slack error<commit_after>'use strict'

let _ = require('lodash')
let moment = require('moment')
let winston = require('winston')
let request = require('request')
let WebClient = require('@slack/client').WebClient
let config = require('../config')
let web = new WebClient(config.SLACK_API_TOKEN)

let isWeekend = () => {
  let weekDay = moment().day()
  return weekDay === 0 || weekDay === 6
}

let postMessageHandler = (err, info) => {
  if (err) return winston.error('SLACK: postMessage failed:', err)
  if (info && !info.ok) return winston.error('SLACK: invalid postMessage response:', info)
}

let onlySubscribed = (allowed) => (service) => allowed.indexOf(service.name) !== -1
let onlyUnsubscribed = (allowed) => (service) => allowed.indexOf(service.name) === -1
let getTitle = (service) => service.title

let prepareMessage = (json, subscribedServices) => {
  let allServices = config.SERVICES
  let availableServices = _.map(_.filter(allServices, onlyUnsubscribed(subscribedServices)), getTitle)
  let message = 'Other available restaurants: ' + availableServices.join(', ') + '\n\n'

  let jsonMenus = _.filter(json, onlySubscribed(subscribedServices))
  for (let i = 0; i < jsonMenus.length; i++) {
    message += `*${jsonMenus[i].title}*\n`

    if (!jsonMenus[i].menu[0]) {
      message += 'No menu was found today, check it out yourself and report bugs to @michal.brasna!\n'
    } else {
      for (let j = 0; j < jsonMenus[i].menu[0].items.length; j++) {
        let menuItem = jsonMenus[i].menu[0].items[j]
        message += `- ${menuItem.item} (${menuItem.amount}) _${menuItem.price}_\n`
      }
    }

    message += '\n'
  }

  return message
}

// don't bother on weekends
if (isWeekend()) process.exit(0)

request(config.URL + 'api/next', (err, response, body) => {
  if (err) return winston.error('SLACK: request failed', err)

  let json = null
  try {
    json = JSON.parse(body)
  } catch (e) {
    return winston.error('SLACK: invalid JSON', e, body, response.statusCode, response.statusMessage)
  }

  let options = {
    username: 'sbks-luncher'
  }

  for (let i = 0; i < config.NOTIFICATIONS.length; i++) {
    let message = prepareMessage(json, config.NOTIFICATIONS[i].services)
    web.chat.postMessage(config.NOTIFICATIONS[i].user, message, options, postMessageHandler)
  }
})
<|endoftext|>


<commit_before>import { select, local } from "d3-selection";
var instanceLocal = local();

function noop (){
} // no operation

function children(){
  return this.children;
}

function exitInstance(d, i){
  select(this).selectAll("*").each(function (){
    var instance = instanceLocal.get(this);
    instanceLocal.remove(this) && instance.exit();
  });
  var transition = instanceLocal.get(this).exit(d, i);
  (transition || select(this)).remove();
}

export default function (tagName){
  var enter = noop,
      update = noop,
      exit = noop,
      key;

  function setInstance(d, i){
    instanceLocal.set(this, {
      owner: component,
      exit: function (){
        return exit.call(this, d, i);
      }.bind(this)
    });
  }

  function belongsToMe(){
    var instance = instanceLocal.get(this);
    return instance && instance.owner === component;
  }

  function component(selection, data){
    var instances = selection
      .selectAll(children)
      .filter(belongsToMe)
      .data(Array.isArray(data) ? data : [data], key);
    instances
      .enter().append(tagName)
        .each(setInstance)
        .each(enter)
      .merge(instances)
        .each(update);
    instances
      .exit()
        .each(exitInstance);
  }
  component.update = function(_) { return (update = _, component); };
  component.enter = function(_) { return (enter = _, component); };
  component.exit = function(_) { return (exit = _, component); };
  component.key = function(_) { return (key = _, component); };

  return component;
};
<commit_msg>Rename setInstance to enterInstance, call enter there<commit_after>import { select, local } from "d3-selection";
var instanceLocal = local();

function noop (){} // no operation

function children(){
  return this.children;
}

function exitInstance(d, i){
  select(this).selectAll("*").each(function (){
    var instance = instanceLocal.get(this);
    instanceLocal.remove(this) && instance.exit();
  });
  var transition = instanceLocal.get(this).exit(d, i);
  (transition || select(this)).remove();
}

export default function (tagName){
  var enter = noop,
      update = noop,
      exit = noop,
      key;

  function enterInstance(d, i){
    instanceLocal.set(this, {
      owner: component,
      exit: function (){
        return exit.call(this, d, i);
      }.bind(this)
    });
    enter.call(this, d, i);
  }

  function belongsToMe(){
    var instance = instanceLocal.get(this);
    return instance && instance.owner === component;
  }

  function component(selection, data){
    var instances = selection
      .selectAll(children)
      .filter(belongsToMe)
      .data(Array.isArray(data) ? data : [data], key);
    instances
      .enter().append(tagName)
        .each(enterInstance)
      .merge(instances)
        .each(update);
    instances
      .exit()
        .each(exitInstance);
  }
  component.update = function(_) { return (update = _, component); };
  component.enter = function(_) { return (enter = _, component); };
  component.exit = function(_) { return (exit = _, component); };
  component.key = function(_) { return (key = _, component); };

  return component;
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';
var gutil = require('gulp-util');
var prettyTime = require('pretty-hrtime');
var glob = require('glob');
var path = require('path');
var chalk = require('chalk');
var archy = require('archy');
var Liftoff = require('liftoff');
var taskTree = require('../lib/taskTree');
var log = require('../lib/log');
var slushPackage = require('../package');
var argv = require('minimist')(process.argv.slice(2));
var versionFlag = argv.v || argv.version;
var generatorName = argv._.shift();

if (!generatorName) {
  if (versionFlag) {
    log(slushPackage.version);
  } else {
    logGenerators(getAllGenerators());
  }
  process.exit(0);
}

var generator = getGenerator(generatorName);

if (!generator) {
  log(chalk.red('No generator by name: "' + generatorName + '" was found!'));
  log(chalk.red('Try installing it with `npm install -g slush-' + generatorName + '` first.'));
  process.exit(1);
}

// Setting cwd and slushfile dir:
argv.cwd = process.cwd();
argv.slushfile = path.join(generator.path, 'slushfile.js');

var cli = new Liftoff({
  processTitle: 'slush',
  moduleName: 'gulp',
  configName: 'slushfile'
  // completions: require('../lib/completion') FIXME
});

cli.on('require', function(name) {
  gutil.log('Requiring external module', chalk.magenta(name));
});

cli.on('requireFail', function(name) {
  gutil.log(chalk.red('Failed to load external module'), chalk.magenta(name));
});

cli.launch(handleArguments, argv);

function handleArguments(env) {

  var argv = env.argv;
  var tasksFlag = argv.T || argv.tasks;
  var tasks = argv._;
  var toRun = tasks.length ? tasks : ['default'];

  if (versionFlag) {
    log(slushPackage.version);
    if (env.modulePackage) {
      gutil.log('Generator version', env.modulePackage.version);
    }
    process.exit(0);
  }

  if (!env.modulePath) {
    gutil.log(chalk.red('No local gulp install found in'), chalk.magenta(env.cwd));
    log(chalk.red('This is an issue with the `slush-' + generator.name + '` generator'));
    process.exit(1);
  }

  if (!env.configPath) {
    log(chalk.red('No slushfile found'));
    log(chalk.red('This is an issue with the `slush-' + generator.name + '` generator'));
    process.exit(1);
  }

  require(env.configPath);
  log('Using slushfile', chalk.magenta(env.configPath));

  var gulpInst = require(env.modulePath);
  logEvents(generator.name, gulpInst);

  if (process.cwd() !== env.cwd) {
    process.chdir(env.cwd);
    gutil.log('Working directory changed to', chalk.magenta(env.cwd));
  }

  process.nextTick(function() {
    if (tasksFlag) {
      return logTasks(generator.name, gulpInst);
    }
    gulpInst.start.apply(gulpInst, toRun);
  });
}

function logGenerators(generators) {
  var tree = {
    label: 'Installed generators',
    nodes: generators.map(function (gen) {
      return {label: gen.name};
    })
  };
  archy(tree).split('\n').forEach(function(v) {
    if (v.trim().length === 0) return;
    log(v);
  });
}

function logTasks(name, localGulp) {
  var tree = taskTree(localGulp.tasks);
  tree.label = 'Tasks for generator ' + chalk.magenta(name);
  archy(tree).split('\n').forEach(function(v) {
    if (v.trim().length === 0) return;
    gutil.log(v);
  });
}

// format orchestrator errors
function formatError(e) {
  if (!e.err) return e.message;
  if (e.err.message) return e.err.message;
  return JSON.stringify(e.err);
}

// wire up logging events
function logEvents(name, gulpInst) {
  gulpInst.on('task_start', function(e) {
    gutil.log('Starting', "'" + chalk.cyan(name + ':' + e.task) + "'...");
  });

  gulpInst.on('task_stop', function(e) {
    var time = prettyTime(e.hrDuration);
    gutil.log('Finished', "'" + chalk.cyan(name + ':' + e.task) + "'", 'after', chalk.magenta(time));
  });

  gulpInst.on('task_err', function(e) {
    var msg = formatError(e);
    var time = prettyTime(e.hrDuration);
    gutil.log("'" + chalk.cyan(name + ':' + e.task) + "'", 'errored after', chalk.magenta(time), chalk.red(msg));
  });

  gulpInst.on('task_not_found', function(err) {
    log(chalk.red("Task '" + err.task + "' was not defined in `slush-" + name + "` but you tried to run it."));
    process.exit(1);
  });

  gulpInst.on('stop', function () {
    log('Scaffolding done');
  });
}

function getGenerator (name) {
  return getAllGenerators().filter(function (gen) {
    return gen.name === name;
  })[0];
}

function getAllGenerators () {
  return findGenerators(require.main.paths);
}

function findGenerators (searchpaths) {
  return searchpaths.reduce(function (arr, searchpath) {
    return arr.concat(glob.sync('slush-*', {cwd: searchpath, stat: true}).map(function (match) {
      return {path: path.join(searchpath, match), name: match.slice(6)};
    }));
  }, []);
}
<commit_msg>Print generator path instead of cwd when generator is missing gulp<commit_after>#!/usr/bin/env node

'use strict';
var gutil = require('gulp-util');
var prettyTime = require('pretty-hrtime');
var glob = require('glob');
var path = require('path');
var chalk = require('chalk');
var archy = require('archy');
var Liftoff = require('liftoff');
var taskTree = require('../lib/taskTree');
var log = require('../lib/log');
var slushPackage = require('../package');
var argv = require('minimist')(process.argv.slice(2));
var versionFlag = argv.v || argv.version;
var generatorName = argv._.shift();

if (!generatorName) {
  if (versionFlag) {
    log(slushPackage.version);
  } else {
    logGenerators(getAllGenerators());
  }
  process.exit(0);
}

var generator = getGenerator(generatorName);

if (!generator) {
  log(chalk.red('No generator by name: "' + generatorName + '" was found!'));
  log(chalk.red('Try installing it with `npm install -g slush-' + generatorName + '` first.'));
  process.exit(1);
}

// Setting cwd and slushfile dir:
argv.cwd = process.cwd();
argv.slushfile = path.join(generator.path, 'slushfile.js');

var cli = new Liftoff({
  processTitle: 'slush',
  moduleName: 'gulp',
  configName: 'slushfile'
  // completions: require('../lib/completion') FIXME
});

cli.on('require', function(name) {
  gutil.log('Requiring external module', chalk.magenta(name));
});

cli.on('requireFail', function(name) {
  gutil.log(chalk.red('Failed to load external module'), chalk.magenta(name));
});

cli.launch(handleArguments, argv);

function handleArguments(env) {

  var argv = env.argv;
  var tasksFlag = argv.T || argv.tasks;
  var tasks = argv._;
  var toRun = tasks.length ? tasks : ['default'];

  if (versionFlag) {
    log(slushPackage.version);
    if (env.modulePackage) {
      gutil.log('Generator version', env.modulePackage.version);
    }
    process.exit(0);
  }

  if (!env.modulePath) {
    gutil.log(chalk.red('No local gulp install found in'), chalk.magenta(generator.path));
    log(chalk.red('This is an issue with the `slush-' + generator.name + '` generator'));
    process.exit(1);
  }

  if (!env.configPath) {
    log(chalk.red('No slushfile found'));
    log(chalk.red('This is an issue with the `slush-' + generator.name + '` generator'));
    process.exit(1);
  }

  require(env.configPath);
  log('Using slushfile', chalk.magenta(env.configPath));

  var gulpInst = require(env.modulePath);
  logEvents(generator.name, gulpInst);

  if (process.cwd() !== env.cwd) {
    process.chdir(env.cwd);
    gutil.log('Working directory changed to', chalk.magenta(env.cwd));
  }

  process.nextTick(function() {
    if (tasksFlag) {
      return logTasks(generator.name, gulpInst);
    }
    gulpInst.start.apply(gulpInst, toRun);
  });
}

function logGenerators(generators) {
  var tree = {
    label: 'Installed generators',
    nodes: generators.map(function (gen) {
      return {label: gen.name};
    })
  };
  archy(tree).split('\n').forEach(function(v) {
    if (v.trim().length === 0) return;
    log(v);
  });
}

function logTasks(name, localGulp) {
  var tree = taskTree(localGulp.tasks);
  tree.label = 'Tasks for generator ' + chalk.magenta(name);
  archy(tree).split('\n').forEach(function(v) {
    if (v.trim().length === 0) return;
    gutil.log(v);
  });
}

// format orchestrator errors
function formatError(e) {
  if (!e.err) return e.message;
  if (e.err.message) return e.err.message;
  return JSON.stringify(e.err);
}

// wire up logging events
function logEvents(name, gulpInst) {
  gulpInst.on('task_start', function(e) {
    gutil.log('Starting', "'" + chalk.cyan(name + ':' + e.task) + "'...");
  });

  gulpInst.on('task_stop', function(e) {
    var time = prettyTime(e.hrDuration);
    gutil.log('Finished', "'" + chalk.cyan(name + ':' + e.task) + "'", 'after', chalk.magenta(time));
  });

  gulpInst.on('task_err', function(e) {
    var msg = formatError(e);
    var time = prettyTime(e.hrDuration);
    gutil.log("'" + chalk.cyan(name + ':' + e.task) + "'", 'errored after', chalk.magenta(time), chalk.red(msg));
  });

  gulpInst.on('task_not_found', function(err) {
    log(chalk.red("Task '" + err.task + "' was not defined in `slush-" + name + "` but you tried to run it."));
    process.exit(1);
  });

  gulpInst.on('stop', function () {
    log('Scaffolding done');
  });
}

function getGenerator (name) {
  return getAllGenerators().filter(function (gen) {
    return gen.name === name;
  })[0];
}

function getAllGenerators () {
  return findGenerators(require.main.paths);
}

function findGenerators (searchpaths) {
  return searchpaths.reduce(function (arr, searchpath) {
    return arr.concat(glob.sync('slush-*', {cwd: searchpath, stat: true}).map(function (match) {
      return {path: path.join(searchpath, match), name: match.slice(6)};
    }));
  }, []);
}
<|endoftext|>