Force rewriting of a script into an ES6 module, such as for imported files that contain no
"import" or "export" statements.
424481
void forceToEs6Module(Node root) {
    if (Es6RewriteModules.isEs6ModuleRoot(root)) {
      return;
    }
    Node moduleNode = new Node(Token.MODULE_BODY).srcref(root);
    moduleNode.addChildrenToBack(root.removeChildren());
    root.addChildToBack(moduleNode);
    compiler.reportChangeToChangeScope(root);
  }
1148532
function(refPath) {
		var require = function(relModuleId) {
			var moduleId = resolveModuleId(relModuleId, refPath),
				module = getModule(moduleId);

			if (!module) {
				throw "Module not loaded";
			}
			else if (module.error) {
				throw "Error loading module";
			}

			if (!module.exports) {
				module.exports = {};
				var moduleDir = moduleId.substring(0, moduleId.lastIndexOf('/')+1),
					injects = module.injects,
					args = [];

				for (var i = 0, n = injects.length; i<n; i++) {
					if (injects[i] == 'require') {
						args.push(createRequireFunc(moduleDir));
					}
					else if (injects[i] == 'exports') {
						args.push(module.exports);
					}
					else if (injects[i] == 'module') {
						args.push(module.module);
					}
				}

				module.factory.apply(null, args);
			}
			return module.exports;
		};

		require.ensure = function(deps, cb) {
			ensureImpl(deps, cb, refPath);
		};

		if (_mainProgram != null) {
			require.main = getModule(_mainProgram).module;
		}

		return require;
	}
544807
function() {

    var hookPath = path.resolve(this.options.dest, this.hookName);

    var existingCode = this.getHookContent(hookPath);

    if (existingCode) {
      this.validateScriptLanguage(existingCode);
    }

    var hookContent;
    if(this.hasMarkers(existingCode)) {
      hookContent = this.insertBindingCode(existingCode);
    } else {
      hookContent = this.appendBindingCode(existingCode);
    }

    fs.writeFileSync(hookPath, hookContent);

    fs.chmodSync(hookPath, '755');
  }
83068
function replaceModuleExports(path, name) {
  const { scope } = path;
  const oldName = path.node.name;

  // Skip if not global scope
  if (scope.hasBinding(oldName, true)) return;

  // TODO: correctly replace foo.exports with object.property?
  if (!isPropertyOrKey(path)) {
    path.node.name = oldName == 'module' ? name : `${name}.exports`;
  }
}
923082
function transform (dir, contents) {
  var imports = [];

  contents = contents.replace(IMPORT_RE, function (match, obj, includePath) {
    if (!MODULE_LOCATIONS[includePath]) {
      imports.push(match);
      return '';
    }
    var includeFile = path.join(dir, MODULE_LOCATIONS[includePath]);
    console.log(dir, includeFile);
    if (includeFile.substr(-3) !== '.js') {
      includeFile += '.js';
    }
    return 'var ' + obj + '=' + inlineModule(includeFile) + ';';
  });

  var services = imports.map(getParts).map(serviceify);
  contents = traceur.compile(contents, TRACEUR_OPTS);
  return detraceurify(unwrapify(contents, services));
}
568882
function wrap(err, js) {
		if (err) { return next(err); }

		var deps = exports.dependencies(id, js), params = [], undef = '';

		// make sure require, exports, and module are properly passed into the factory
		if (/\brequire\b/.test(js)) { params.push('require'); }
		if (/\bexports\b/.test(js)) { params.push('exports'); }
		if (/\bmodule\b/.test(js)) { params.push('module'); }

		// make sure code follows the `exports` path instead of `define` path once wrapped
		if (/\bdefine\.amd\b/.test(js)) { undef = 'var define;'; }

		if (deps.length) {
			deps = ',' + JSON.stringify(params.concat(deps));
		} else if (params.length) {
			params = [ 'require', 'exports', 'module' ];
		}

		js = 'define(' + JSON.stringify(id) + deps + ',function(' + params + ')' +
				'{' + js + '\n' + undef + '}' + // rely on hoisting for define
			');\n';
		next(null, js);
	}
243485
function script(req, res, next) {
  switch (req.get('SHELL')) {
  case '/bin/sh':
  case '/bin/bash':
    res.render(__dirname + '/init.bash');
    break;
  default:
    next(new Error('Unsupported shell: ' + req.get('SHELL')));
  }
}
511759
function writeJSConfigFile(config, filePath) {
    debug(`Writing JS config file: ${filePath}`);

    let contentToWrite;
    const stringifiedContent = `module.exports = ${stringify(config, { cmp: sortByKey, space: 4 })};`;

    try {
        const CLIEngine = require("../cli-engine");
        const linter = new CLIEngine({
            baseConfig: config,
            fix: true,
            useEslintrc: false
        });
        const report = linter.executeOnText(stringifiedContent);

        contentToWrite = report.results[0].output || stringifiedContent;
    } catch (e) {
        debug("Error linting JavaScript config file, writing unlinted version");
        const errorMessage = e.message;

        contentToWrite = stringifiedContent;
        e.message = "An error occurred while generating your JavaScript config file. ";
        e.message += "A config file was still generated, but the config file itself may not follow your linting rules.";
        e.message += `\nError: ${errorMessage}`;
        throw e;
    } finally {
        fs.writeFileSync(filePath, contentToWrite, "utf8");
    }
}
503380
function createElementScript() {
  return gulp
    .src(`./${config.src.path}/${config.src.entrypoint}`)
    .pipe(
      modifyFile(content => {
        /**
         * Strip the imports and exports out of the parse code and return them.
         *
         * @param {Program} parsedCode
         *   The parsed code.
         * @returns {{imports:Map<number,Object>, exports:Map<number,Object>}}
         */
        const stripImportsAndExports = parsedCode => {
          // Get info about the code.
          const codeIndexesToRemove = [];
          const imports = new Map();
          const exports = new Map();
          for (const [nodeIndex, node] of parsedCode.body.entries()) {
            switch (node.type) {
              case 'ImportDeclaration':
                for (const specifiers of node.specifiers) {
                  let importedName;
                  if (specifiers.type === 'ImportDefaultSpecifier') {
                    importedName = specifiers.local.name;
                  } else if (specifiers.type === 'ImportSpecifier') {
                    importedName = specifiers.imported.name;
                  }

                  if (
                    importedName != null &&
                    importedName.toLowerCase().startsWith('catalyst')
                  ) {
                    imports.set(nodeIndex, node);
                    codeIndexesToRemove.push(nodeIndex);
                  } else {
                    throw new Error(
                      `Cannot automatically process import "${importedName}."`
                    );
                  }
                }
                break;

              case 'ExportDefaultDeclaration':
              case 'ExportNamedDeclaration':
                exports.set(nodeIndex, parsedCode.body[nodeIndex]);
                codeIndexesToRemove.push(nodeIndex);
                break;

              // Different type? Do nothing.
              default:
            }
          }

          // Remove imports and exports.
          parsedCode.body = parsedCode.body.filter(
            (e, i) => !codeIndexesToRemove.includes(i)
          );

          return {
            imports: imports,
            exports: exports
          };
        };

        /**
         * Replace catalyst element's imports with globally accessible object import.
         *
         * @param {Program} parsedCode
         *   The parsed code with the imports already stripped out.
         * @param {Map<number,Object>} imports
         *   The imports that have been stripped out of the parsed code.
         */
        const processImports = (parsedCode, imports) => {
          for (const [importDefIndex, importDef] of imports) {
            for (const specifier of Object.values(importDef.specifiers)) {
              const localName = specifier.local.name;
              const importedName = specifier.imported
                ? specifier.imported.name
                : localName;

              if (importedName.toLowerCase().startsWith('catalyst')) {
                parsedCode.body.splice(
                  importDefIndex,
                  0,
                  esprima.parseScript(
                    `let ${localName} = window.CatalystElements.${importedName};`
                  )
                );
              } else {
                throw new Error(
                  `Cannot automatically process import "${importedName}."`
                );
              }
            }
          }
        };

        /**
         * Replace exports with globally accessible object exports.
         *
         * @param {Program} parsedCode
         *   The parsed code with the exports already stripped out.
         * @param {Map<number,Object>} exports
         *   The exports that have been stripped out of the parsed code.
         */
        const processExports = (parsedCode, exports) => {
          const exportNamesUsed = [];

          // Replace exports with globally accessible object exports.
          for (const [exportDefIndex, exportDef] of exports) {
            if (exportDef.declaration === null) {
              for (const specifier of Object.values(exportDef.specifiers)) {
                const localName = specifier.local.name;
                const exportedName = specifier.imported
                  ? specifier.imported.name
                  : localName;

                if (!exportNamesUsed.includes(exportedName)) {
                  parsedCode.body.splice(
                    exportDefIndex,
                    0,
                    esprima.parseScript(
                      `window.CatalystElements.${exportedName} = ${localName};`
                    )
                  );
                  exportNamesUsed.push(exportedName);
                }
              }
            } else if (exportDef.declaration.type === 'Identifier') {
              if (!exportNamesUsed.includes(exportDef.declaration.name)) {
                parsedCode.body.splice(
                  exportDefIndex,
                  0,
                  esprima.parseScript(
                    `window.CatalystElements.${exportDef.declaration.name} = ${
                      exportDef.declaration.name
                    };`
                  )
                );
                exportNamesUsed.push(exportDef.declaration.name);
              }
            } else {
              console.error(
                `Cannot automatically process declaration in ${exportDef.type}.`
              );
            }
          }
        };

        // Parse the code.
        const parsedCode = esprima.parseModule(content);

        // Run functions defined above.
        const { imports, exports } = stripImportsAndExports(parsedCode);
        processImports(parsedCode, imports);
        processExports(parsedCode, exports);

        // Generate the updated code.
        return (
          'window.CatalystElements = window.CatalystElements || {};\n' +
          `${escodegen.generate(parsedCode)}`
        );
      })
    )
    .pipe(
      rename(path => {
        path.basename = config.element.tag;
        path.extname = `.script${path.extname}`;
      })
    )
    .pipe(gulp.dest(`./${config.temp.path}`));
}
879821
def reload_including_local(module):
    
    try:
        reload(module)
    except ImportError:
        # This can happen if the module was loaded in the immediate script
        # directory.  Add the service path and try again.
        if not hasattr(cherrypy.thread_data, "modulepath"):
            raise
        path = os.path.abspath(cherrypy.thread_data.modulepath)
        root = os.path.abspath(cherrypy.config.get("webroot"))
        if path not in sys.path and (path == root or path.startswith(root + os.path.sep)):
            oldpath = sys.path
            try:
                sys.path = [path] + sys.path
                reload(module)
            finally:
                sys.path = oldpath
        else:
            raise
523831
function transformJSX(ast, pragma) {
	assert(t.isFile(ast) || t.isProgram(ast), '<ast> must be a babel ast for transformJSX(ast: AST, pragma: String): AST');
	assert(typeof pragma === 'string' && pragma, '<pragma> must be a non-empty string for transformJSX(ast: AST, pragma: String): AST');

	const call = buildCall(pragma);

	traverse(ast, {
		JSXElement: {
			exit(path) {
				const openingElement = path.get('openingElement');
				const expression = buildElementCall(call, openingElement);
				expression.arguments = [...expression.arguments, ...path.node.children];
				path.replaceWith(t.inherits(expression, path.node));
			}
		}
	});
	return ast;
}
796509
private String checkinScriptCommand() {

        String exportModules = "";
        if ((m_modulesToExport != null) && !m_modulesToExport.isEmpty()) {
            StringBuffer exportModulesParam = new StringBuffer();
            for (String moduleName : m_modulesToExport) {
                exportModulesParam.append(" ").append(moduleName);
            }
            exportModulesParam.replace(0, 1, " \"");
            exportModulesParam.append("\" ");
            exportModules = " --modules " + exportModulesParam.toString();

        }
        String commitMessage = "";
        if (m_commitMessage != null) {
            commitMessage = " -msg \"" + m_commitMessage.replace("\"", "\\\"") + "\"";
        }
        String gitUserName = "";
        if (m_gitUserName != null) {
            if (m_gitUserName.trim().isEmpty()) {
                gitUserName = " --ignore-default-git-user-name";
            } else {
                gitUserName = " --git-user-name \"" + m_gitUserName + "\"";
            }
        }
        String gitUserEmail = "";
        if (m_gitUserEmail != null) {
            if (m_gitUserEmail.trim().isEmpty()) {
                gitUserEmail = " --ignore-default-git-user-email";
            } else {
                gitUserEmail = " --git-user-email \"" + m_gitUserEmail + "\"";
            }
        }
        String autoPullBefore = "";
        if (m_autoPullBefore != null) {
            autoPullBefore = m_autoPullBefore.booleanValue() ? " --pull-before " : " --no-pull-before";
        }
        String autoPullAfter = "";
        if (m_autoPullAfter != null) {
            autoPullAfter = m_autoPullAfter.booleanValue() ? " --pull-after " : " --no-pull-after";
        }
        String autoPush = "";
        if (m_autoPush != null) {
            autoPush = m_autoPush.booleanValue() ? " --push " : " --no-push";
        }
        String exportFolder = " --export-folder \"" + m_currentConfiguration.getModuleExportPath() + "\"";
        String exportMode = " --export-mode " + m_currentConfiguration.getExportMode();
        String excludeLibs = "";
        if (m_excludeLibs != null) {
            excludeLibs = m_excludeLibs.booleanValue() ? " --exclude-libs" : " --no-exclude-libs";
        }
        String commitMode = "";
        if (m_commitMode != null) {
            commitMode = m_commitMode.booleanValue() ? " --commit" : " --no-commit";
        }
        String ignoreUncleanMode = "";
        if (m_ignoreUnclean != null) {
            ignoreUncleanMode = m_ignoreUnclean.booleanValue() ? " --ignore-unclean" : " --no-ignore-unclean";
        }
        String copyAndUnzip = "";
        if (m_copyAndUnzip != null) {
            copyAndUnzip = m_copyAndUnzip.booleanValue() ? " --copy-and-unzip" : " --no-copy-and-unzip";
        }

        String configFilePath = m_currentConfiguration.getFilePath();

        return "\""
            + DEFAULT_SCRIPT_FILE
            + "\""
            + exportModules
            + commitMessage
            + gitUserName
            + gitUserEmail
            + autoPullBefore
            + autoPullAfter
            + autoPush
            + exportFolder
            + exportMode
            + excludeLibs
            + commitMode
            + ignoreUncleanMode
            + copyAndUnzip
            + " \""
            + configFilePath
            + "\"";
    }
578844
function importScript(src) {
  // Scan all search paths in order, trying to find the file.
  //var relPath = path.join(path.dirname(process.argv[1]) + '/', src);
  var filePath = src;//path.relative(process.cwd(), relPath);
  for (var n = 0; n < SEARCH_PATHS.length; n++) {
    var searchPath = path.join(process.cwd(), SEARCH_PATHS[n]);
    var searchFilePath = path.join(searchPath, filePath);
    if (fileExistsSync(searchFilePath)) {
      var sourceCode = fs.readFileSync(searchFilePath, 'utf8');
      try {
        vm.runInThisContext(sourceCode, searchFilePath);
      } catch (e) {
        console.log('Error running script ' + src);
        throw e;
      }
      return true;
    }
  }

  // File not found.
  console.log('ERROR: could not find ' + src);
  return false;
}
741027
function transformFile(from, to, modulesDirectory) {
  var contents = fs.readFileSync(from, 'utf8');

  // modules
  var modules = getModules(contents);
  for (var index in modules) {
    var module = modules[index];
    if (modulesManifest.hasOwnProperty(module)) {
      continue;
    }
    var modulePath = path_util.modulePath(module, node_modules);
    if (modulePath === null) {
      continue;
    }
    var targetPath = path_util.targetPath(modulePath, node_modules, modulesDirectory);
    modulesManifest[module] = path.relative(process.cwd(), targetPath);
    if (!fs.existsSync(targetPath)) {
      transformFile(modulePath, targetPath, modulesDirectory);
    }
    var relativePath = path_util.relativePath(to, targetPath);
    var re = eval('\/require\\\(\[\'\"\]' + module + '\[\'\"\]\\\)\/ig');
    contents = contents.replace(re, 'require(\'' + relativePath + '\')');
  }

  // requires
  var requires = getRequires(contents);
  for (var index in requires) {
    var require = requires[index];
    var requirePath = path_util.requirePath(from, require);
    if (requirePath === null) {
      continue;
    }
    if (requiresManifest.hasOwnProperty(requirePath)) {
      continue;
    } else {
      requiresManifest[requirePath] = true;
    }
    var targetPath = path_util.targetPath(requirePath, node_modules, modulesDirectory);
    if (!fs.existsSync(targetPath)) {
      transformFile(requirePath, targetPath, modulesDirectory);
    }
  }

  var dirname = path.dirname(to);
  fs.mkdirsSync(dirname);
  fs.writeFileSync(to, contents, 'utf8');
}
396732
function extendExportSymbols(target, source, lookupTable, exportNode) {
            for (var id in source) {
                if (id !== "default" && !target[id]) {
                    target[id] = source[id];
                    if (lookupTable && exportNode) {
                        lookupTable[id] = {
                            specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
                        };
                    }
                }
                else if (lookupTable && exportNode && id !== "default" && target[id] && resolveSymbol(target[id]) !== resolveSymbol(source[id])) {
                    if (!lookupTable[id].exportsWithDuplicate) {
                        lookupTable[id].exportsWithDuplicate = [exportNode];
                    }
                    else {
                        lookupTable[id].exportsWithDuplicate.push(exportNode);
                    }
                }
            }
        }
776059
function transformCode(transformFn, code, url) {
  let source;
  if (url != null) {
    source = url;
  } else {
    source = 'Inline Babel script';
    inlineScriptCount++;
    if (inlineScriptCount > 1) {
      source += ' (' + inlineScriptCount + ')';
    }
  }

  return transformFn(
    code,
    {
      filename: source,
      ...babelOpts
    }
  ).code;
}
563783
function moveImports(code, imports) {
    return code.replace(RE_IMPORTS, function (_, indent, imprt) {
        imprt = imprt.trim();
        if (imprt.slice(-1) !== ';') {
            imprt += ';';
        }
        imports.push(imprt);
        return indent; // keep only the indentation
    });
}