Represents a worker.
@alias module:workers.Worker
@constructor
@param {String} file
481578
function Worker(file) {
  if (!(this instanceof Worker))
    return new Worker(file);

  EventEmitter.call(this);

  this.id = -1;
  this.framer = new Framer();
  this.parser = new Parser();
  this.pending = new Map();

  this.child = new Child(file);

  this.init();
}
438480
function define (File, utils) {
  const { debug, error, strong } = utils.cnsl;

  return class COFFEESCRIPTFile extends File {
    /**
     * Compile file contents
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     * @returns {null}
     */
    compile (buildOptions, fn) {
      try {
        const options = Object.assign({ sourceMap: this.hasMaps }, DEFAULT_OPTIONS, this.options.pluginOptions.coffeescript || {});
        const results = coffee.compile(this.content, options);
        let content, map;

        if ('string' != typeof results) {
          content = results.js;
          map = results.v3SourceMap;
        } else {
          content = results;
        }

        this.setContent(content);
        if (map) this.setMap(map);
        debug(`compile: ${strong(this.relpath)}`, 4);
      } catch (err) {
        if (!this.options.runtimeOptions.watch) return fn(err);
        error(err, 4, false);
      }
      fn();
    }
  };
}
64324
function open(file) {
  if (!file) {
    console.log('No output file, force logging to console')
    config.logToConsole = true
    return
  }
  if (fs.existsSync(file)) {
    var suffix = (new Date()).toJSON()//(new Date()).getTime()
    var newfile = file+'.'+suffix
    console.log('Move datafile to', newfile)
    fs.renameSync(file, newfile)
  }
  dataFile = new DataFile(file)
}
675154
function parse_javascript(file /*, options*/) {
  let source = fs.readFileSync(file, 'utf8');

  let nodes, list = {};

  try {
    nodes = parser.parse(source);
  } catch (err) {
    throw new Error(`${err} [${file}:${err.line},${err.column}]`);
  }

  // do pre-distribute early work
  _.each(nodes, node /*, id*/ => {
    let clone;

    // assign hierarchy helpers
    node.aliases  = [];
    node.children = [];

    // set source fiel of the node
    node.file = file;

    if (node.type === 'class') {
      node.subclasses = [];
    }

    // collect sections
    if (node.type === 'section') {
      list[node.id] = node;
      return;
    }

    // elements with undefined section get '' section,
    // and will be resolved later, when we'll have full
    // element list
    list[(node.section || '') + '.' + node.id] = node;

    // bound methods produce two methods with the same description but different signatures
    // E.g. Element.foo(@element, a, b) becomes
    // Element.foo(element, a, b) and Element#foo(a, b)
    if (node.type === 'method' && node.bound) {
      clone = _.clone(node);
      clone.id = node.id.replace(/(.+)\.(.+)$/, '$1#$2');

      // link to methods
      node.bound = clone.id;
      clone.bound = node.id;

      // insert bound method clone
      list[(node.section || '') + '.' + clone.id] = clone;
    }
  });

  // TODO: section.related_to should mark related element as belonging to the section
  //_.each(list, function (node, id) {
  //  var ref_id = '.' + node.related_to, ref;
  //  if ('section' === node.type && node.related_to && list[ref_id]) {
  //    ref = list[ref_id];
  //    ref.id = node.id + '.' + node.related_to;
  //    delete list[ref_id];
  //    list[ref.id] = ref;
  //  }
  //});

  return list;
}
1057610
function WorkerHandler(script, _options) {
  this.script = script || getDefaultWorker();
  var options = _options || {};
  this.debugPort = options.debugPort;

  if (environment.platform == 'browser') {
    // check whether Worker is supported by the browser
    // Workaround for a bug in PhantomJS (Or QtWebkit): https://github.com/ariya/phantomjs/issues/14534
    if (typeof Worker !== 'function' && (typeof Worker !== 'object' || typeof Worker.prototype.constructor !== 'function')) {
      throw new Error('WorkerPool: Web workers not supported by the browser');
    }

    this.worker = setupBrowserWorker(this.script, Worker);
  } else {
    var WorkerThreads;

    if (options.nodeWorker === 'thread') {
      WorkerThreads = ensureWorkerThreads();
      this.worker = setupWorkerThreadWorker(this.script, WorkerThreads);
    } else if (options.nodeWorker === 'auto') {
      WorkerThreads = tryRequire('worker_threads');
      if (WorkerThreads) {
        this.worker = setupWorkerThreadWorker(this.script, WorkerThreads);
      } else {
        this.worker = setupProcessWorker(this.script, resolveForkOptions(options), require('child_process'));
      }
    } else {
      this.worker = setupProcessWorker(this.script, resolveForkOptions(options), require('child_process'));
    }
  }

  var me = this;

  // The ready message is only sent if the worker.add method is called (And the default script is not used)
  if (!script) {
    this.worker.ready = true;
  }

  // queue for requests that are received before the worker is ready
  this.requestQueue = [];
  this.worker.on('message', function (response) {
    if (typeof response === 'string' && response === 'ready') {
      me.worker.ready = true;
      dispatchQueuedRequests();
    } else {
      // find the task from the processing queue, and run the tasks callback
      var id = response.id;
      var task = me.processing[id];
      if (task !== undefined) {
        // remove the task from the queue
        delete me.processing[id];

        // test if we need to terminate
        if (me.terminating === true) {
          // complete worker termination if all tasks are finished
          me.terminate();
        }

        // resolve the task's promise
        if (response.error) {
          task.resolver.reject(objectToError(response.error));
        }
        else {
          task.resolver.resolve(response.result);
        }
      }
    }
  });

  // reject all running tasks on worker error
  function onError(error) {
    me.terminated = true;
    if (me.terminating && me.terminationHandler) {
      me.terminationHandler(me);
    }
    me.terminating = false;

    for (var id in me.processing) {
      if (me.processing[id] !== undefined) {
        me.processing[id].resolver.reject(error);
      }
    }
    me.processing = Object.create(null);
  }

  // send all queued requests to worker
  function dispatchQueuedRequests()
  {
    me.requestQueue.forEach(me.worker.send.bind(me.worker));
    me.requestQueue = [];
  }

  var worker = this.worker;
  // listen for worker messages error and exit
  this.worker.on('error', onError);
  this.worker.on('exit', function (exitCode, signalCode) {
    var message = 'Workerpool Worker terminated Unexpectedly\n';

    message += '    exitCode: `' + exitCode + '`\n';
    message += '    signalCode: `' + signalCode + '`\n';

    message += '    workerpool.script: `' +  me.script + '`\n';
    message += '    spawnArgs: `' +  worker.spawnargs + '`\n';
    message += '    spawnfile: `' + worker.spawnfile + '`\n'

    message += '    stdout: `' + worker.stdout + '`\n'
    message += '    stderr: `' + worker.stderr + '`\n'

    onError(new Error(message));
  });

  this.processing = Object.create(null); // queue with tasks currently in progress

  this.terminating = false;
  this.terminated = false;
  this.terminationHandler = null;
  this.lastId = 0;
}
821803
function Worker(baseUrl, opts = {}) {

  if (!(this instanceof Worker)) {
    return new Worker(baseUrl, opts);
  }

  // inheritance
  Emitter.call(this);

  this.options = extend({
    workerId: uuid.v4()
  }, defaultOptions, opts);

  this.subscriptions = {};

  this.state = STATE_NEW;

  // apply extensions
  if (this.options.use) {
    this.extend(this.options.use);
  }

  // local variables
  this.engineApi = new EngineApi(
    baseUrl,
    this.options.requestOptions,
    this.options.apiVersion
  );

  if (this.options.pollingDelay) {
    throw new Error('options.pollingDelay got replaced with options.autoPoll');
  }

  // start
  if (this.options.autoPoll) {
    this.start();
  }
}
749649
function onFile( error, file ) {
		if ( error ) {
			debug( 'Error encountered while attempting to read a temporary output file %s: %s', outFile, error.message );
			return done( error );
		}
		debug( 'Successfully read temporary output file: %s', outFile );
		unlink( outFile, onDelete );

		/**
		* FUNCTION: onDelete( [error] )
		*	Callback invoked upon deleting a file.
		*
		* @private
		* @param {Error} [error] - error object
		* @returns {Void}
		*/
		function onDelete( error ) {
			if ( error ) {
				debug( 'Error encountered while attempting to delete a temporary output file %s: %s', outFile, error.message );
				return done( error );
			}
			debug( 'Successfully deleted temporary output file: %s', outFile );
			done( null, file );
		} // end FUNCTION onDelete()
	}
43040
function (file) {
        if (file.tslint) {
            // Version 5.0.0 of tslint no longer has a failureCount member
            // It was renamed to errorCount. See tslint issue #2439
            var failureCount = file.tslint.errorCount;
            if (!options.allowWarnings) {
                failureCount += file.tslint.warningCount;
            }
            if (failureCount > 0) {
                errorFiles.push(file);
                Array.prototype.push.apply(allFailures, file.tslint.failures);
                if (options.reportLimit <= 0 || (options.reportLimit && options.reportLimit > totalReported)) {
                    if (file.tslint.output !== undefined) {
                        // If any errors were found, print all warnings and errors
                        console.log(file.tslint.output);
                    }
                    totalReported += failureCount;
                    if (options.reportLimit > 0 &&
                        options.reportLimit <= totalReported) {
                        log("More than " + options.reportLimit
                            + " failures reported. Turning off reporter.");
                    }
                }
            }
            else if (options.allowWarnings && file.tslint.warningCount > 0) {
                // Íf only warnings were emitted, format and print them
                // Figure out which formatter the user requested in `tslintPlugin()` and construct one
                var formatterConstructor = TSLint.findFormatter(tslintPlugin.pluginOptions.formatter);
                var formatter = new formatterConstructor();
                // Get just the warnings
                var warnings = file.tslint.failures.filter(function (failure) { return failure.getRuleSeverity() === "warning"; });
                // Print the output of those
                console.log(formatter.format(warnings));
            }
        }
        // Pass file
        this.emit("data", file);
    }
515172
function writeFile (file, callback) {
  fs.outputFile(path.resolve(this._destination, path.join(file.path.dir, file.path.name + file.path.ext)), file.content, function (err) {
    if (err) callback(err);
    callback(null);
  });
}
1116725
function Worker(vfs) {
    Agent.call(this, {

        // Endpoints for writable streams at meta.stream (and meta.process.stdin)
        write: write,
        end: end,

        // Endpoint for readable stream at meta.stream (and meta.process.{stdout,stderr})
        destroy: destroy,

        // Endpoints for readable streams at options.stream
        onData: onData,
        onEnd: onEnd,

        // Endpoint for writable streams at options.stream
        onClose: onClose,

        // Endpoints for processes at meta.process
        kill: kill,

        // Endpoint for watchers at meta.watcher
        close: closeWatcher,

        // Endpoint for apis at meta.api
        call: call,

        // Endpoints for vfs itself
        subscribe: subscribe,
        unsubscribe: unsubscribe,
        emit: vfs.emit,

        // special vfs-socket api
        ping: ping,

        // Route other calls to the local vfs instance
        resolve:  route("resolve"),
        stat:     route("stat"),
        readfile: route("readfile"),
        readdir:  route("readdir"),
        mkfile:   route("mkfile"),
        mkdir:    route("mkdir"),
        rmfile:   route("rmfile"),
        rmdir:    route("rmdir"),
        rename:   route("rename"),
        copy:     route("copy"),
        symlink:  route("symlink"),
        watch:    route("watch"),
        connect:  route("connect"),
        spawn:    route("spawn"),
        execFile: route("execFile"),
        extend:   route("extend"),
        unextend: route("unextend"),
        use:      route("use")

    });

    var proxyStreams = {};
    var streams = {};
    var watchers = {};
    var processes = {};
    var apis = {};
    var handlers = {};
    var remote = this.remoteApi;

    function subscribe(name, callback) {
        handlers[name] = function (value) {
            remote.onEvent(name, value);
        };
        vfs.on(name, handlers[name], callback);
    }

    function unsubscribe(name, callback) {
        var handler = handlers[name];
        if (!handler) return;
        delete handlers[name];
        vfs.off(name, handler, callback);
    }

    // Resume readable streams that we paused when the channel drains
    // Forward drain events to all the writable proxy streams.
    this.on("drain", function () {
        Object.keys(streams).forEach(function (id) {
            var stream = streams[id];
            if (stream.readable && stream.resume) stream.resume();
        });
        Object.keys(proxyStreams).forEach(function (id) {
            var stream = proxyStreams[id];
            if (stream.writable) stream.emit("drain");
        });
    });

    // Cleanup streams, proxy streams, proxy processes, and proxy apis on disconnect.
    this.on("disconnect", function (err) {
        if (!err) {
            err = new Error("EDISCONNECT: vfs socket disconnected");
            err.code = "EDISCONNECT";
        }
        Object.keys(streams).forEach(function (id) {
            var stream = streams[id];
            stream.emit("close", err);
        });
        Object.keys(proxyStreams).forEach(onClose);
        Object.keys(processes).forEach(function (pid) {
            var process = processes[pid];
            process.kill();
            delete processes[pid];
        });
        Object.keys(watchers).forEach(function (id) {
            var watcher = watchers[id];
            delete watchers[id];
            watcher.close();
        });
    });
    
    function makeStreamProxy(token) {
        var stream = new Stream();
        var id = token.id;
        stream.id = id;
        proxyStreams[id] = stream;
        if (token.hasOwnProperty("readable")) stream.readable = token.readable;
        if (token.hasOwnProperty("writable")) stream.writable = token.writable;

        if (stream.writable) {
            stream.write = function (chunk) {
                return remote.write(id, chunk);
            };
            stream.end = function (chunk) {
                if (chunk) remote.end(id, chunk);
                else remote.end(id);
            };
        }
        if (stream.readable) {
            stream.destroy = function () {
                remote.destroy(id);
            };
        }

        return stream;
    }

    var nextStreamID = 1;
    function storeStream(stream) {
        nextStreamID = nextStreamID++ % 10000;
        while (streams.hasOwnProperty(nextStreamID)) { nextStreamID++ % 10000; }
        var id = nextStreamID;
        streams[id] = stream;
        stream.id = id;
        if (stream.readable) {
            stream.on("data", function (chunk) {
                if (remote.onData(id, chunk) === false) {
                    stream.pause && stream.pause();
                }
            });
            stream.on("end", function () {
                delete streams[id];
                remote.onEnd(id);
            });
        }
        stream.on("close", function () {
            delete streams[id];
            remote.onClose(id);
        });
        var token = {id: id};
        if (stream.hasOwnProperty("readable")) token.readable = stream.readable;
        if (stream.hasOwnProperty("writable")) token.writable = stream.writable;
        return token;
    }

    function storeProcess(process) {
        var pid = process.pid;
        processes[pid] = process;
        process.on("exit", function (code, signal) {
            delete processes[pid];
            remote.onExit(pid, code, signal);
        });
        process.on("close", function () {
            delete processes[pid];
            delete streams[process.stdout.id];
            delete streams[process.stderr.id];
            delete streams[process.stdin.id];
            remote.onProcessClose(pid);
        });

        process.kill = function(code) {
            killtree(pid, code);
        };

        var token = {pid: pid};
        token.stdin = storeStream(process.stdin);
        token.stdout = storeStream(process.stdout);
        token.stderr = storeStream(process.stderr);
        return token;
    }

    function killtree(pid, code) {
        childrenOfPid(pid, function(err, pidlist){
            if (err) {
                console.error(err.stack);
                return;
            }
            pidlist.forEach(function (pid) {
                try {
                    process.kill(pid, code || "SIGKILL");
                } catch(e) {
                    // kill may throw if the pid does not exist.
                }
            });
        });
    }

    function childrenOfPid(pid, callback) {
        execFile("ps", ["-A", "-oppid,pid"], function(code, stdout, stderr) {
            if (code)
                return callback(code + ":" + stderr);

            var parents = {};
            stdout.split("\n").slice(1).forEach(function(line) {
                var col = line.trim().split(/\s+/g);
                (parents[col[0]] || (parents[col[0]] = [])).push(col[1]);
            });

            function search(roots) {
            var res = roots.concat();
            for (var c, i = 0; i < roots.length; i++) {
                if ((c = parents[roots[i]]) && c.length)
                    res.push.apply(res, search(c));
                }
                return res;
            }
            callback(null, search([pid]));
        });
    }

    var nextWatcherID = 1;
    function storeWatcher(watcher) {
        while (watchers.hasOwnProperty(nextWatcherID)) { nextWatcherID++; }
        var id = nextWatcherID;
        watchers[id] = watcher;
        watcher.id = id;
        watcher.on("change", function (event, filename) {
            remote.onChange(id, event, filename);
        });
        var token = {id: id};
        return token;
    }

    function storeApi(api) {
        var name = api.name;
        apis[name] = api;
        var token = { name: name, names: api.names };
        return token;
    }

    // Remote side writing to our local writable streams
    function write(id, chunk) {
        // They want to write to our real stream
        var stream = streams[id];
        if (!stream) return;
        stream.write(chunk);
    }
    function destroy(id) {
        var stream = streams[id];
        if (!stream) return;
        delete streams[id];
        stream.destroy();
        nextStreamID = id;
    }
    function end(id, chunk) {
        var stream = streams[id];
        if (!stream) return;
        delete streams[id];
        if (chunk) stream.end(chunk);
        else stream.end();
        nextStreamID = id;
    }

    function kill(pid, code) {
        var process = processes[pid];
        if (!process) return;
        process.kill(code);
    }

    function closeWatcher(id) {
        var watcher = watchers[id];
        if (!watcher) return;
        delete watchers[id];
        watcher.close();
        nextWatcherID = id;
    }

    function call(name, fnName, args) {
        var api = apis[name];
        if (!api) return;

        // If the last arg is a function, assume it's a callback and process it.
        if (typeof args[args.length - 1] == "function") {
            var callback = args[args.length - 1];
            args[args.length - 1] = function (err, meta) {
                if (err || (meta && typeof meta === "object")) {
                    return processCallback(err, meta, callback);
                }
                callback(err, meta);
            };
        }

        api[fnName].apply(api, args);
    }

    function onData(id, chunk) {
        var stream = proxyStreams[id];
        if (!stream) return;
        stream.emit("data", chunk);
    }
    function onEnd(id) {
        var stream = proxyStreams[id];
        if (!stream) return;
        // TODO: not delete proxy if close is going to be called later.
        // but somehow do delete proxy if close won't be called later.
        delete proxyStreams[id];
        stream.emit("end");
    }
    function onClose(id) {
        var stream = proxyStreams[id];
        if (!stream) return;
        delete proxyStreams[id];
        stream.emit("close");
    }

    // Can be used for keepalive checks.
    function ping(callback) {
        callback();
    }

    function processCallback(err, meta, callback) {
        // Make error objects serializable
        if (err) {
            var nerr = {
                stack: process.pid + ": " + err.stack
            };
            if (err.hasOwnProperty("code")) nerr.code = err.code;
            if (err.hasOwnProperty("message")) nerr.message = err.message;
            return callback(nerr);
        }
        var token = {};
        var keys = Object.keys(meta);
        for (var i = 0, l = keys.length; i < l; i++) {
            var key = keys[i];
            switch (key) {
                case "stream": token.stream = storeStream(meta.stream); break;
                case "process": token.process = storeProcess(meta.process); break;
                case "watcher": token.watcher = storeWatcher(meta.watcher); break;
                case "api": token.api = storeApi(meta.api); break;
                default: token[key] = meta[key]; break;
            }
        }
        // Call the remote callback with the result
        callback(null, token);
    }

    function route(name) {
        return function wrapped(path, options, callback) {
            if (typeof callback !== "function") {
                throw new Error(name + ": callback must be function");
            }
            // Call the real local function, but intercept the callback
            if (options.stream) {
                options.stream = makeStreamProxy(options.stream);
            }
            vfs[name](path, options, function (err, meta) {
                processCallback(err, meta, callback);
            });
        };
    }
}
1287569
def _create_worker(self, worker):
        """"""
        worker.sig_started.connect(self._start)
        self._workers.append(worker)
77776
function define (File, utils) {
  const { callable } = utils;
  const { debug, error, strong } = utils.cnsl;
  const { regexpEscape, uniqueMatch } = utils.string;

  return class NUNJUCKSFile extends File {
    /**
     * Constructor
     * @param {String} id
     * @param {String} filepath
     * @param {Object} options
     *  - {Object} caches
     *  - {Object} fileExtensions
     *  - {Function} fileFactory
     *  - {Object} globalAliases
     *  - {Array} npmModulepaths
     *  - {Object} pluginOptions
     *  - {Object} runtimeOptions
     */
    constructor (id, filepath, options) {
      super(id, filepath, options);

      this.workflows.writeable = WORKFLOW_WRITEABLE;
    }

    /**
     * Parse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    parse (buildOptions, fn) {
      super.parse(buildOptions, (err) => {
        if (err) return fn(err);

        // Find sidecar json file
        const sidecarData = super.parseSidecarDependency();
        // Parse includes
        let matches = uniqueMatch(this.content, RE_INCLUDE)
          .map((match) => {
            match.id = match.match;
            match.isInclude = true;
            return match;
          });

        // Parse imports
        matches.push(...uniqueMatch(this.content, RE_IMPORT)
          .map((match) => {
            match.id = match.match;
            match.isImport = true;
            return match;
          }));
        if (sidecarData) matches.push(sidecarData);

        super.addDependencies(matches, buildOptions);
        fn();
      });
    }

    /**
     * Replace relative dependency references with fully resolved
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    replaceReferences (buildOptions, fn) {
      [...this.getAllDependencies(), this].forEach((file) => {
        if (file instanceof NUNJUCKSFile && this.dependencyReferences.length) {
          let content = file.content;

          file.dependencyReferences.forEach((reference) => {
            if (reference.file && reference.isImport) {
              const context = reference.context.replace(reference.id, reference.file.filepath);

              // Create new RegExp so that flags work properly
              content = content.replace(new RegExp(regexpEscape(reference.context), 'g'), context);
            }
          });

          file.setContent(content);
        }
      });
      fn();
    }

    /**
     * Inline css/img/js dependency content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineInlineable (buildOptions, fn) {
      // Only dependencies
      parallel([...this.getAllDependencies()].reduce((inlineable, file) => {
        if (file instanceof NUNJUCKSFile && this.dependencyReferences.length) {
          inlineable.push(callable(file, 'inline', buildOptions));
        }
        return inlineable;
      }, []), fn);
    }

    /**
     * Inline included content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineIncludes (buildOptions, fn) {
      [...this.getAllDependencies(), this].forEach((file) => {
        if (file instanceof NUNJUCKSFile && file.dependencyReferences.length) {
          let content = file.content;

          file.dependencyReferences.forEach((reference) => {
            if (reference.file && reference.context && reference.isInclude) {
              content = content.replace(new RegExp(regexpEscape(reference.context), 'g'), reference.file.content);
            }
          });

          file.setContent(content);
        }
      });
      fn();
    }

    /**
     * Compile file contents
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    compile (buildOptions, fn) {
      const options = Object.assign({}, DEFAULT_OPTIONS, this.options.pluginOptions.nunjucks);

      nunjucks.configure(null, options);
      nunjucks.renderString(this.content, this.findSidecarDependency(), (err, content) => {
        if (err) {
          if (!this.options.runtimeOptions.watch) return fn(err);
          error(err, 4, false);
        }
        this.setContent(content);
        debug(`compile: ${strong(this.relpath)}`, 4);
        fn();
      });
    }

    /**
     * Reparse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    reparse (buildOptions, fn) {
      this.allDependencies = null;
      this.allDependencyReferences = null;
      this.dependencies = [];
      this.dependencyReferences = [];

      super.parse(buildOptions, fn);
    }
  };
}
73684
function startWorker(port) {
        var worker = child.fork(serverWorker, [
            '--port', port,
            '--server', serverFile,
            '--allowForcedExit', allowForcedExit,
            '--config', JSON.stringify(config.app || {}),
            '--title', workerTitle
        ]);

        worker.on('exit', createWorkerExitHandler(port));
        return worker;
    }
149165
function define(File, utils) {
  return class IMGFile extends File {
    /**
     * Constructor
     * @param {String} id
     * @param {String} filepath
     * @param {Object} options
     *  - {Function} buildFactory
     *  - {Object} fileCache
     *  - {Object} fileExtensions
     *  - {Function} fileFactory
     *  - {Array} npmModulepaths
     *  - {Object} pluginOptions
     *  - {Object} runtimeOptions
     *  - {String} webroot
     */
    constructor(id, filepath, options) {
      super(id, filepath, 'img', options);

      this.hasMaps = false;
      this.map = null;
      this.workflows.writeable = WORKFLOW_WRITEABLE;
    }

    /**
     * Read and store file contents
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    load(buildOptions, fn) {
      // Make sure to load as Buffer
      if (this.extension != 'svg') this.encoding = null;
      super.load(buildOptions, fn);
      this.map = null;
    }

    /**
     * Parse file contents for dependency references [no-op]
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    parse(buildOptions, fn) {
      debug(`parse: ${strong(this.relpath)}`, 4);
      fn();
    }
  };
}
494665
function loadFile(file) {
    console.log('loadFile:', file);

    // <file> can be Image, File URL object or URL string (http://* or data:image/*)
    rasterToGcode.load(file).then(function(rtg) {
        console.log('rasterToGcode:', rtg);
    })
    .catch(function(error) {
        console.error('error:', error);
    });
}
111423
function processFile(file, flow){
  var fconsole = flow.console;
  var scriptSequenceId = 0;
  var jsSequence = false;
  var conditionalBlock;
  var head;
  var body;

  // get ast
  var ast = at.parse(file.content);

  // debug output
  //console.log(require('util').inspect(ast, false, null));

  var handlers = {
    '*': function(node){
      // nothing to do if text node contains whitespace only
      if (node.type == 'text' && !NON_WHITESPACE.test(node.data))
        return;

      // scripts with src continue script sequence
      if (node.type == 'tag' && node.name == 'script')
        return;

      scriptSequenceId += jsSequence;
      jsSequence = false;
    },
    comment: function(node){
      var conditional = node.data.match(/^(\[if\s+[^\]]+\]>)((?:.|[\r\n])*)(<!\[endif\])$/i);
      if (conditional)
      {
        node.prefix = conditional[1];
        node.ast = at.parse(conditional[2]);
        node.postfix = conditional[3];

        scriptSequenceId += jsSequence;
        jsSequence = false;

        conditionalBlock = true;
        at.walk(node.ast, handlers, { file: file });
        conditionalBlock = false;
      }
    },
    tag: function(node){
      var attrs = at.getAttrs(node);

      switch (node.name)
      {
        case 'head':
          if (!head)
          {
            fconsole.log('<head> tag found (store reference)');
            head = node;
          }
          else
          {
            flow.warn({
              file: this.file.relpath,
              message: 'more than one <head> tag is prohibited (ignore)'
            });
          }

          break;

        case 'body':
          if (!body)
          {
            fconsole.log('<body> tag found (store reference)');
            body = node;
          }
          else
          {
            flow.warn({
              file: this.file.relpath,
              message: 'more than one <body> tag is prohibited (ignore)'
            });
          }

          break;

        case 'script':
          // ignore <script> tags with type other than text/javascript
          if (attrs.type && attrs.type != 'text/javascript')
          {
            fconsole.log('<script> with unknown type `' + attrs.type + '` ignored');
            return;
          }

          // external script
          if (attrs.src)
          {
            var uri = resolveUri(attrs.src);

            if (uri.filename)
            {
              fconsole.start('External script found: <script src="' + attrs.src + '">');
              jsSequence = true;
              node.loc = file.location(node.info.start);

              var scriptFile = flow.files.add({
                initiator: {
                  file: file,
                  loc: node.loc,
                  token: at.translate(node)
                },

                type: 'script',
                htmlFile: file,
                htmlNode: node,
                filename: file.resolve(attrs.src),
                package: 'script' + (scriptSequenceId || '')
              });

              if (!scriptFile)
                return;

              file.link(scriptFile, node);

              fconsole.endl();
              return;
            }

            if (uri.mime == 'text/javascript')
            {
              fconsole.start('Inline script with data uri found');
              jsSequence = true;

              var scriptFile = flow.files.add({
                type: 'script',
                inline: true,
                htmlFile: file,
                htmlNode: node,
                baseURI: file.baseURI,
                content: uri.content,
                package: 'script' + (scriptSequenceId || '')
              });

              if (attrs['build-filename'])
                scriptFile.sourceFilename = attrs['build-filename'];

              file.link(scriptFile, node);

              fconsole.endl();
              return;
            }

            if (!uri.url) // external url
            {
              flow.warn({
                file: this.file.relpath,
                message: 'script ignored: ' + at.translate(node)
              });
            }
          }
          else
          {
            fconsole.log('Inline script found\n');

            file.link(flow.files.add({
              type: 'script',
              inline: true,
              htmlFile: file,
              htmlNode: node,
              baseURI: file.baseURI,
              content: at.getText(node),
              embed: {
                file: file.filename,
                start: node.info.startContent,
                end: node.info.endContent
              }
            }), node);
          }

          break;

        //
        // style
        //
        case 'link':

          if (at.rel(node, 'stylesheet') && attrs.href)
          {
            // <link rel="stylesheet">');
            fconsole.log('External style found: ' + at.translate(node));
            node.loc = file.location(node.info.start);

            var styleLinkFile = flow.files.add({
              initiator: {
                file: file,
                loc: node.loc,
                token: at.translate(node)
              },

              type: 'style',
              htmlFile: file,
              htmlNode: node,
              htmlId: attrs.id,
              filename: file.resolve(attrs.href),
              media: attrs.media || 'all',
              conditional: conditionalBlock
            });

            if (styleLinkFile)
            {
              if (styleLinkFile.htmlNode !== node)
                flow.warn({
                  file: this.file.relpath,
                  fatal: true,
                  message: 'Duplicate <link> found: ' + at.translate(node)
                });

              file.link(styleLinkFile, node);
            }
          }

          break;

        case 'style':
          var attrs = at.getAttrs(node);

          // ignore <style> with type other than text/css
          if (attrs.type && attrs.type != 'text/css')
          {
            flow.warn({
              file: this.file.relpath,
              message: '<style> with unknown type ' + attrs.type + ' ignored'
            });
            return;
          }

          // <style> or <style type="text/css">
          fconsole.log('Inline style found');

          var styleFile = flow.files.add({
            type: 'style',
            inline: true,
            htmlFile: file,
            htmlNode: node,
            htmlId: attrs.id,
            baseURI: file.baseURI,
            media: attrs.media || 'all',
            conditional: conditionalBlock,
            content: at.getText(node),
            embed: {
              file: file.filename,
              start: node.info.startContent,
              end: node.info.endContent
            }
          });

          if (attrs['build-filename'])
            styleFile.sourceFilename = attrs['build-filename'];

          file.link(styleFile, node);

          break;

        default:
          var attrs = at.getAttrs(node);
          if (attrs.style)
          {
            var styleFile = flow.files.add({
              type: 'style-block',
              inline: true,
              htmlFile: file,
              htmlNode: node,
              baseURI: file.baseURI,
              rule: true,
              content: attrs.style
            });

            if (flow.options.verbose)
            {
              var nodeClone = {};
              for (var key in node)
                if (key != 'children')
                  nodeClone[key] = node[key];
                else
                  nodeClone[key] = [];

              fconsole.log('Style attribute found: ' + at.translate(nodeClone));
            }

            file.link(styleFile, node);
          }
      }
    }
  };

  at.walk(ast, handlers, { file: file });

  // save result in file
  file.ast = ast;
}
146112
function(file) {
      var sections = file.contents.toString().split(END_REG);

      var blocks = [],
        files = [];

      var self = this;

      sections.forEach(function(s) {
        if (s.match(START_REG)) {
          // s[0] html code
          // s[1] string 'css' or 'js'
          // s[2] string dest url
          // s[3] tags of link or script
          s = s.split(START_REG);
          blocks.push(s[0]);
          switch (s[1]) {
            case 'css':
              blocks.push('<link rel="stylesheet" href="' + s[2] + '">');
              break;
            case 'js':
              blocks.push('<script src="' + s[2] + '"></script>');
              break;
            default:
              throw new gutil.PluginError('gulp-htmlbuild', 'only build:css build:js accept\n');
          }
          var paths = self.matchContentPaths(s[1] === 'css' ? CSSFILE_REG : JSFILE_REG, s[3]);
          var source = concatSource(paths);
          files.push({
            type: s[1],
            dest: resolveSrc(s[2], self.filedir),
            source: source
          });
        } else {
          blocks.push(s);
        }
      });

      return {
        blocks: blocks,
        files: files
      }
    }