Pack all seperate .js files back into a raw google script file

@param {String} rootFolder - relative path to the rootFolder of the project
@param {String} fileName - which file we should add to local.json
@returns {void}
774940
function removeRemoteSingleFile(rootFolder, fileName) {
    // Read every local file and create a correct local.json file
    const fileNameWithoutExtension = path.join(path.parse(fileName).dir, path.parse(fileName).name);
    const extension = path.parse(fileName).ext;

    // Read remote
    const remote = path.join(rootFolder, constants.META_DIR, constants.META_REMOTE);
    const remoteData = JSON.parse(fs.readFileSync(remote, 'utf8'));

    // Check if file is in remote
    let inRemote = false;
    for (let index = 0; index < remoteData.files.length; index++) {
        if (remoteData.files[index].name === fileNameWithoutExtension) {
            inRemote = true;
            // lets remove the file
            remoteData.files.splice(index, 1);
            break;
        }
    }

    // If not in remote
    if (!inRemote) {
        throw {
            message: `Can't seem to find '${fileName}' in the remote Google Apps Script file`,
            print: true,
        };
    }

    // Write to local.json
    writeLocalJson(remoteData, rootFolder);
}
1020304
function initBook(rootFolder) {
    var extension = '.md';

    return fs.mkdirp(rootFolder)

    // Parse the summary and readme
    .then(function() {
        var fs = createNodeFS(rootFolder);
        var book = Book.createForFS(fs);

        return Parse.parseReadme(book)

        // Setup default readme if doesn't found one
        .fail(function() {
            var readmeFile = File.createWithFilepath('README' + extension);
            var readme = Readme.create(readmeFile);
            return book.setReadme(readme);
        });
    })
    .then(Parse.parseSummary)

    .then(function(book) {
        var logger = book.getLogger();
        var summary = book.getSummary();
        var summaryFile = summary.getFile();
        var summaryFilename = summaryFile.getPath() || ('SUMMARY' + extension);

        var articles = summary.getArticlesAsList();

        // Write pages
        return Promise.forEach(articles, function(article) {
            var articlePath = article.getPath();
            var filePath = articlePath? path.join(rootFolder, articlePath) : null;
            if (!filePath) {
                return;
            }

            return fs.assertFile(filePath, function() {
                return fs.ensureFile(filePath)
                .then(function() {
                    logger.info.ln('create', article.getPath());
                    return fs.writeFile(filePath, '# ' + article.getTitle() + '\n\n');
                });
            });
        })

        // Write summary
        .then(function() {
            var filePath = path.join(rootFolder, summaryFilename);

            return fs.ensureFile(filePath)
            .then(function() {
                logger.info.ln('create ' + path.basename(filePath));
                return fs.writeFile(filePath, summary.toText(extension));
            });
        })

        // Log end
        .then(function() {
            logger.info.ln('initialization is finished');
        });
    });
}
907496
public function setJSFromFile(string $filename, Scopable $scope = null, bool $relativeToRootPath = true): void
    {
        $this->jsElement = new HtmlFromFile($filename, $scope, $relativeToRootPath);
    }
864790
function load(inPath)
{
  var keys;

  // Group description file can be specified as relative to CWD
  var configFilePath = pathlib.resolve(process.cwd(),inPath);

  // Paths are relative to the config file (inPath) + /public by default
  var configDir = pathlib.dirname(configFilePath);
  var baseDir = pathlib.resolve(configDir,'public');

  // Load the JSON description of the groups
  var input = JSON.parse(stripJsonComments(fs.readFileSync(configFilePath,'utf8')));
  var ret = {};

  // 1. Resolve everything to absolute paths

  // 1a. Root file dirs -- relative to the config file
  ret.rootFileDirs = (input.rootFileDirs||[]).map(function(path) {
    return pathlib.resolve(configDir, path);
  });

  // 1b. Static file dirs -- relative to the config file
  ret.staticFileDirs = {};
  keys = Object.keys(input.staticFileDirs||{});
  keys.forEach(function(key) {
    var paths = input.staticFileDirs[key];
    if ( !util.isArray(paths) )
      paths = [paths];

    ret.staticFileDirs[key] = paths.map(function(path) {
      return pathlib.resolve(configDir, path);
    });
  });

  // 1c. Groups
  keys = Object.keys(input.groups||{});

  // Loop over each group definition
  ret.groups = {};
  keys.forEach(function(groupName) {
    var group = input.groups[groupName];
    var subKeys = Object.keys(group);

    var newGroup = {};

    // You can override the base directory per-group
    if ( group.baseDir )
    {
      var paths = group.baseDir;
      if ( !util.isArray(paths) )
        paths = [paths];

      newGroup.customBaseDir = true;
      newGroup.baseDir = paths.map(function(path) {
        // If baseDir is specified for the group, it's relative to the location of the asset file
        return pathlib.resolve(configDir, path);
      });
    }
    else
    {
      newGroup.customBaseDir = false;
      newGroup.baseDir = [baseDir];
    }

    newGroup.include = group.include || [];

    // Loop over each key in the group definition
    subKeys.forEach(function(subKey) {
      if ( SPECIAL_KEYS.indexOf(subKey) >= 0 )
      {
        // We've already dealt with these
        return;
      }

      if ( HANDLER_KEYS.indexOf(subKey) === -1 )
      {
        throw new Error('Unknown group property: '+ subKey);
      }

      // Resolve file names into absolute paths
      newGroup[subKey] = (group[subKey]||[]).map(function(filename) {
        return resolveFile(newGroup.baseDir, !newGroup.customBaseDir, filename, subKey);
      });
    });

    ret.groups[groupName] = newGroup;
  });

  // 2. Process each group into a flat list of the file names needed
  keys = Object.keys(ret.groups);
  keys.forEach(function(groupName) {
    var flattened = _flatten(ret.groups, groupName);

    // Remember if we're supposed to save the output or not for compliling
    flattened.saveOutput = input.groups[groupName].saveOutput !== false;

    ret.groups[groupName] = flattened;
  });

  return ret;
}
446395
function buildJscadWorkerScript(fullpath, fullscript) {
// determine the relative base path for include(<relativepath>)
  var relpath = fullpath;
  if (relpath.lastIndexOf('/') >= 0) {
    relpath = relpath.substring(0,relpath.lastIndexOf('/')+1);
  }
  var source = "";
  source += 'onmessage = function(e) {\n';
  source += '  include = includeJscad;\n';
  source += '  self.relpath = "'+relpath+'";\n';
  source += '\n';
  source += fullscript+'\n';
  source += includeJscad.toString()+'\n';
  source += runJscadWorker.toString()+'\n';
  source += '  runJscadWorker(e);\n';
  source += '};';
  return source;
}
961916
function(folder_wildcard) {
            var tmp = document.getElementsByTagName("script");
            //weird, this array changes by its own, so we use a copy
            var script_files = [];
            for (var i in tmp) {
                script_files.push(tmp[i]);
            }

            var docHeadObj = document.getElementsByTagName("head")[0];
            folder_wildcard = document.location.href + folder_wildcard;

            for (var i in script_files) {
                var src = script_files[i].src;
                if (
                    !src ||
                    src.substr(0, folder_wildcard.length) != folder_wildcard
                ) {
                    continue;
                }

                try {
                    if (LiteGraph.debug) {
                        console.log("Reloading: " + src);
                    }
                    var dynamicScript = document.createElement("script");
                    dynamicScript.type = "text/javascript";
                    dynamicScript.src = src;
                    docHeadObj.appendChild(dynamicScript);
                    docHeadObj.removeChild(script_files[i]);
                } catch (err) {
                    if (LiteGraph.throw_errors) {
                        throw err;
                    }
                    if (LiteGraph.debug) {
                        console.log("Error while reloading " + src);
                    }
                }
            }

            if (LiteGraph.debug) {
                console.log("Nodes reloaded");
            }
        }
651202
function ensureFolder(rootFolder) {
    return rmDir(rootFolder)
    .fail(function() {
        return Promise();
    })
    .then(function() {
        return Promise.nfcall(mkdirp, rootFolder);
    });
}
167625
function(root) {
    var files;
    var ignored = ['node_modules/', 'bower_components/', 'dist/', 'tmp/', 'blueprints/'];
    files = walkSync(root).filter(function(file){
      return !ignored.map(function(i){
        return file.indexOf(i) !== -1;
      }).reduce(function(total,value){
        // if we have a true value, then don't include
        return total ? total : (value ? value : total);
      });
    });
    return {
      js: filterByExt(files,'.js'),
      hbs: filterByExt(files,'.hbs')
    };
  }
502312
function resolvePath (moduleName, relativePath)
{
  if (! moduleName) {
    return null;
  }

  if (! relativePath) {
    return null;
  }

  const mainPath = require.resolve(moduleName);
  if (! mainPath) {
    return null;
  }

  const rootLocations = [];
  const dirs = mainPath.split(path.sep);
  let lastSegment = dirs.pop();
  while (lastSegment) {
    const location = dirs.concat(['package.json']).join(path.sep);
    rootLocations.push(location);
    lastSegment = dirs.pop();
  }

  for(const location of rootLocations) {
    if (fs.existsSync(location)) {
      const cli = path.resolve(path.dirname(location), relativePath);
      if (fs.existsSync(cli)) {
        return cli;
      }
    }
  }

  return null;
}
1279117
static private Module addFilesInDir(File dir, int rootPrefix, File root,
                                        Set<String> suffixes, boolean allow_javas,
                                        List<String> excludeFiles, List<String> includeFiles, boolean all,
                                        Map<String,Source> foundFiles,
                                        Map<String,Module> foundModules,
                                        Module currentModule,
                                        boolean inGensrc,
                                        boolean inLinksrc)
        throws ProblemException
    {
        for (File f : dir.listFiles()) {
            if (f.isFile()) {
                boolean should_add =
                    (excludeFiles == null || excludeFiles.isEmpty() || !hasFileMatch(f.getPath(), excludeFiles))
                    && (includeFiles == null || includeFiles.isEmpty() || hasFileMatch(f.getPath(), includeFiles));

                if (should_add) {
                    if (!allow_javas && f.getName().endsWith(".java")) {
                        throw new ProblemException("No .java files are allowed in the source root "+dir.getPath()+
                                                   ", please remove "+f.getName());
                    }
                    // Extract the file name relative the root.
                    String fn = f.getPath().substring(rootPrefix);
                    // Extract the package name.
                    int sp = fn.lastIndexOf(File.separatorChar);
                    String pkg = "";
                    if (sp != -1) {
                        pkg = fn.substring(0,sp).replace(File.separatorChar,'.');
                    }
                    // Is this a module-info.java file?
                    if (fn.endsWith("module-info.java")) {
                        // Aha! We have recursed into a module!
                        if (!currentModule.name().equals("")) {
                            throw new ProblemException("You have an extra module-info.java inside a module! Please remove "+fn);
                        }
                        String module_name = fn.substring(0,fn.length()-16);
                        currentModule = new Module(module_name, f.getPath());
                        foundModules.put(module_name, currentModule);
                    }
                    // Extract the suffix.
                    int dp = fn.lastIndexOf(".");
                    String suffix = "";
                    if (dp > 0) {
                        suffix = fn.substring(dp);
                    }
                    // Should the file be added?
                    if (all || suffixes.contains(suffix)) {
                        Source of = foundFiles.get(f.getPath());
                        if (of != null) {
                            throw new ProblemException("You have already added the file "+fn+" from "+of.file().getPath());
                        }
                        of = currentModule.lookupSource(f.getPath());
                        if (of != null) {
                            // Oups, the source is already added, could be ok, could be not, lets check.
                            if (inLinksrc) {
                                // So we are collecting sources for linking only.
                                if (of.isLinkedOnly()) {
                                    // Ouch, this one is also for linking only. Bad.
                                    throw new ProblemException("You have already added the link only file "+fn+" from "+of.file().getPath());
                                }
                                // Ok, the existing source is to be compiled. Thus this link only is redundant
                                // since all compiled are also linked to. Continue to the next source.
                                // But we need to add the source, so that it will be visible to linking,
                                // if not the multi core compile will fail because a JavaCompiler cannot
                                // find the necessary dependencies for its part of the source.
                                foundFiles.put(f.getPath(), of);
                                continue;
                            } else {
                                // We are looking for sources to compile, if we find an existing to be compiled
                                // source with the same name, it is an internal error, since we must
                                // find the sources to be compiled before we find the sources to be linked to.
                                throw new ProblemException("Internal error: Double add of file "+fn+" from "+of.file().getPath());
                            }
                        }
                        Source s = new Source(currentModule, f.getPath(), f, root);
                        if (inGensrc) s.markAsGenerated();
                        if (inLinksrc) {
                            s.markAsLinkedOnly();
                        }
                        pkg = currentModule.name()+":"+pkg;
                        foundFiles.put(f.getPath(), s);
                        currentModule.addSource(pkg, s);
                    }
                }
            }
        }
        return currentModule;
    }
962052
public void copyResourceToDir(String path, String filename, String dir) {
		String fullpath = path + ProcessorConstants.SEPARATORCHAR + filename;
		messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, " javascript copy js : " + fullpath + " to : "+dir);
		try (Writer writer = getFileObjectWriter(dir, "org.ocelotds."+filename)) {
			bodyWriter.write(writer, OcelotProcessor.class.getResourceAsStream(fullpath));
		} catch (IOException ex) {
			messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING, " FAILED TO CREATE : " + filename);
		}
	}
1330779
protected void appendJsNode(HttpServletRequest request, Document document, DocumentFragment head, Js js, String relativeRoot) {
        final String scriptPath = getElementPath(request, js, relativeRoot);

        if (resourcesDao.isConditional(js)) {
            Comment c = document.createComment("");
            c.appendData(OPEN_COND_COMMENT_PRE);
            c.appendData(js.getConditional());
            c.appendData(OPEN_COND_COMMENT_POST);
            c.appendData(OPEN_SCRIPT);
            c.appendData(scriptPath);
            c.appendData(CLOSE_SCRIPT);
            c.appendData(CLOSE_COND_COMMENT);
            head.appendChild(c);
        }
        else {
            Element element = document.createElement(SCRIPT);
            element.setAttribute(TYPE, "text/javascript");
            element.setAttribute(SRC, scriptPath);
            element.appendChild(document.createTextNode(" "));

            head.appendChild(element);
        }
    }
557835
function _filesToFile (files, target, separator, callback) {

			if ("undefined" === typeof files) {
				throw new ReferenceError("missing \"files\" argument");
			}
				else if ("object" !== typeof files || !(files instanceof Array)) {
					throw new TypeError("\"files\" argument is not an Array");
				}
			else if ("undefined" === typeof target) {
				throw new ReferenceError("missing \"target\" argument");
			}
				else if ("string" !== typeof target) {
					throw new TypeError("\"target\" argument is not a string");
				}
			else if ("undefined" === typeof callback && "undefined" === typeof separator) {
				throw new ReferenceError("missing \"callback\" argument");
			}
				else if ("function" !== typeof callback && "function" !== typeof separator) {
					throw new TypeError("\"callback\" argument is not a function");
				}
			else {

				const _target = target.trim();

				if ("" === _target) {
					throw new Error("\"target\" argument is empty");
				}
				else {

					const _callback = "undefined" === typeof callback ? separator : callback;

					Promise.resolve().then(() => {
						return isFileProm(_target);
					}).then((exists) => {

						return !exists ? Promise.resolve() : new Promise((resolve, reject) => {

							fs.unlink(_target, (err) => {
								return err ? reject(err) : resolve();
							});

						});

					}).then(() => {

						if (!files.length) {

							return new Promise((resolve, reject) => {

								fs.writeFile(_target, "", (err) => {
									return err ? reject(err) : resolve();
								});

							});

						}
						else {

							return filesToStreamProm(files, "string" === typeof separator ? separator : " ").then((readStream) => {

								return new Promise((resolve, reject) => {

									let error = false;
									readStream.once("error", (_err) => {
										error = true; reject(_err);
									}).pipe(fs.createWriteStream(_target, { "flags": "a" }).once("error", (_err) => {
										error = true; reject(_err);
									}).once("close", () => {

										if (!error) {
											resolve();
										}

									}));

								});

							});

						}

					}).then(() => {
						_callback(null);
					}).catch(_callback);

				}

			}

		}
180977
function (fileName) {
            var dir;
            if (currDirRegExp.test(fileName)) {
                dir = frontSlash(location.href);
                if (dir.indexOf('/') !== -1) {
                    dir = dir.split('/');

                    //Pull off protocol and host, just want
                    //to allow paths (other build parts, like
                    //require._isSupportedBuildUrl do not support
                    //full URLs), but a full path from
                    //the root.
                    dir.splice(0, 3);

                    dir.pop();
                    dir = '/' + dir.join('/');
                }

                fileName = dir + fileName.substring(1);
            }

            return fileName;
        }
678848
function includedFile(fileName) {
            var relativePath = fileName.substring(appDir.length + 1);
            var result = false;
            for (var i = 0; i < onlyIncludeList.length; i++) {
                var prefix = onlyIncludeList[i];
                if (relativePath.indexOf(prefix) === 0) {
                    result = true;
                    break;
                }
            }
            return result;
        }
544954
function TS2JS(tsFile) {
  const srcFolder = path.join(__dirname, '..', 'src');
  const distFolder = path.join(__dirname, '..', 'build', 'main');

  const tsPathObj = path.parse(tsFile);

  return path.format({
    dir: tsPathObj.dir.replace(srcFolder, distFolder),
    ext: '.js',
    name: tsPathObj.name,
    root: tsPathObj.root
  });
}
1104986
async function downloadDependencies(rootFolder, dependencyList) {
    const includeFolder = path.join(rootFolder, constants.INCLUDE_DIR);
    fs.removeSync(includeFolder);
    const contentPath = path.join(includeFolder, 'content.json');

    // Create new content.json
    createFile({
        name: contentPath,
        source: JSON.stringify(dependencyList),
    });

    // Extensions
    const extensions = eaft.getCodeExtensions();

    // Download new dependencies
    for (const dependency of Reflect.ownKeys(dependencyList)) {
        const dependencies = dependencyList[dependency].dependencies;
        const package = dependencyList[dependency].packageName;
        const version = dependencyList[dependency].version;
        const isRootDependency = dependencyList[dependency].isRootDependency;

        // Use package name as dependency if it is a root dependency
        let dependencyName;
        if (isRootDependency) {
            dependencyName = package;
        } else {
            dependencyName = dependency;
        }
        const packagePath = path.join(includeFolder, dependencyName);

        // Get library code
        url = `${constants.FIREBASE_DATABASE_URL}/package/${package}/version/${version}/code.json`;
        const library = await request({
            url,
            method: "GET",
            json: true,
            headers: {
                "content-type": "application/json",
            },
        });

        // Write library files
        for (const file of library.files) {
            const extension = eaft.getExtensionFromFiletype(file.type, extensions);
            const fileName = `${file.name}${extension}`;
            const source = processSource(file.source, dependencyList, dependency);
            createFile({
                name: path.join(packagePath, fileName),
                source,
            });
        }
    }
}