Deploy specified app package to ios-sim simulator
@param  {String} appPath Path to application package
@param  {String} target  Target device type
@return {Promise}        Resolves when deploy succeeds otherwise rejects
180370
function deployToSim(appPath, target) {
    // Select target device for emulator. Default is 'iPhone-6' 
    if (!target) {
        return require('./list-emulator-images').run()
        .then(function (emulators) {
            if (emulators.length > 0) {
                target = emulators[0];
            }
            emulators.forEach(function (emulator) {
                if (emulator.indexOf('iPhone') === 0) {
                    target = emulator;
                }
            });
            events.emit('log','No target specified for emulator. Deploying to ' + target + ' simulator');
            return startSim(appPath, target);
        });
    } else {
        return startSim(appPath, target);
    }
}
1134373
function(filePath, targetPath, callback) {
            client
                .moveFile(filePath, targetPath)
                .then(function() {
                    __executeCallbackAsync(callback, [null]);
                })
                .catch(callback);
        }
260813
function packageProject(cordovaPlatforms, args, /* optional */ projectPath) {
    if (typeof (cordovaPlatforms) == 'string') {
        cordovaPlatforms = [cordovaPlatforms];
    }
    if (!projectPath) {
        projectPath = defaultConfig.projectPath;
    }

    return setupCordova().then(function (cordova) {
        var promise = Q(cordova);
        cordovaPlatforms.forEach(function (platform) {
            if (platform == 'ios') {
                promise = promise.then(function () { return _createIpa(projectPath, args); });
            } else {
                console.log('Platform ' + platform + ' does not require a separate package step.');
            }
        });

        return promise;
    });
}
863526
function(folder) {
		var type = config.moduleType;
		var appPath;
		if (folder) {
			if (path.isAbsolute(folder)) {
				appPath = path.join(folder);
			} else {
				appPath = path.join(process.cwd(), folder);
			}
		} else {
			appPath = path.join(process.cwd());
		}
		var appSrc = config.apps[type];
		helpers.gitClone(appSrc, appPath);
	}
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;
	}
845000
def generate_apprepo_file(_apprepo_path, options)
      # v = options[:app].latest_version
      # generate_apprepo_file(v, File.join(apprepo_path, 'manifest.json'))

      # Generate the final Repofile here
      gem_path = Helper.gem_path('apprepo')
      apprepo = File.read("#{gem_path}/../assets/RepofileDefault")
      apprepo.gsub!('[[APP_IDENTIFIER]]', options[:app].bundle_id)
      apprepo.gsub!('[[APPREPO_IPA_PATH]]', options[:app].file_path)
      apprepo.gsub!('[[APP_VERSION]]', options[:app].version)
      apprepo.gsub!('[[APP_NAME]]', options[:app].name)
      # apprepo (was deliver)
    end
1138936
function targetPath(fromPath, basePath, targetDirectory) {
  // console.log('targetPath:fromPath: ' + fromPath);
  // console.log('targetPath:basePath: ' + basePath);
  // console.log('targetPath:targetDirectory: ' + targetDirectory);
  var relativePath = path.relative(basePath, fromPath);
  // console.log('targetPath:relativePath: ' + relativePath);
  // console.log('targetPath: ' + path.resolve(targetDirectory, relativePath));
  return path.resolve(targetDirectory, relativePath);
}
279504
func (s *MappingEntry) SetTargetPath(v string) *MappingEntry {
	s.TargetPath = &v
	return s
}
559307
function downloadPlatform(projectRoot, platform, version, opts) {
    var target = version ? (platform + '@' + version) : platform;
    return Q().then(function() {
        if (opts.fetch) {
            //append cordova to platform
            if(platform in platforms) {
                target = 'judpack-'+target;
            }

            //gitURLs don't supply a platform, it equals null
            if(!platform) {
                target = version;
            }

            events.emit('log', 'Using cordova-fetch for '+ target);
            return fetch(target, projectRoot, opts);
        }

        if (cordova_util.isUrl(version)) {
            events.emit('log', 'git cloning: ' + version);
            var parts = version.split('#');
            var git_url = parts[0];
            var branchToCheckout = parts[1];
            return lazy_load.git_clone(git_url, branchToCheckout).fail(function(err) {
                // If it looks like a url, but cannot be cloned, try handling it differently.
                // it's because it's a tarball of the form:
                //     - wp8@https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git;a=snapshot;h=3.7.0;sf=tgz
                //     - https://api.github.com/repos/msopenTech/cordova-browser/tarball/my-branch
                events.emit('verbose', err.message);
                events.emit('verbose', 'Cloning failed. Let\'s try handling it as a tarball');
                return lazy_load.based_on_config(projectRoot, target, opts);
            });
        }
        return lazy_load.based_on_config(projectRoot, target, opts);
    }).fail(function (error) {
        var message = 'Failed to fetch platform ' + target +
            '\nProbably this is either a connection problem, or platform spec is incorrect.' +
            '\nCheck your connection and platform name/version/URL.' +
            '\n' + error;
        return Q.reject(new CordovaError(message));
    }).then(function(libDir) {
        return getPlatformDetailsFromDir(libDir, platform);
    });
}
1355425
function parseManifest(target) {
  return new Promise((resolve, reject) => {
    fs.readFile(target, (err, data) => {
      if (err) reject(err)
      const doc = parser.parseFromString(data.toString(), 'application/xml')
      resolve(doc)
    })
  })
}
483764
function AppLoader(appLoaderOpts, errEmitter) {
	this.load = load

	function load(cb) { // load data from parent process and all app Files
		var isError
		var cbCounter = 3
		var parentApps = {}
		var appFileApps = {}
		var launchBrowser

		parentloader.load(parentDataReceiver)
		appfileloader.loadAppFiles(appLoaderOpts.appFiles, fileDataReceiver)
		doneLoading()

		function parentDataReceiver(err, result) {
			if (result) {
				if (result.appMap) parentApps = result.appMap
				if (result.time) appLoaderOpts.launchTime = result.time
			}
			doneLoading(err)
		}

		function fileDataReceiver(err, appConfigs) {
			if (!err) appFileApps = appConfigs
			doneLoading(err)
		}

		function doneLoading(err) {
			if (!err) {
				if (!--cbCounter) updateAppEntity()
			} else if (!isError) {
				isError = true
				cb(err)
			}
		}

		/*
		appFileApps: the apps we should have
		parentApps: the apps that are currently running
		appLoaderOpts.apps: the apps frontend has configured

		app structure in config file json:
		key: app Name
		.id: optional string default derived from App name: app id
		.state: optional string default run: state on Node God launch, any of 'run', 'debug', 'stop'
		.folder: optional string folder: app launch folder default app id, absolute path or relative to Node God's parent folder
		.start: optional array of string: launch command and arguments for app, default ['node', .folder + '/app']
		.debug: optional array of string: debug launch command and arguments for app, default ['node', '--debug-brk', .folder + '/app']
		.watchFiles: optional string or regexp or array of those, default none: file to watch for app restart
		.watchCopy: optional object default none: key: destination path, value: source path
		- paths to file or folder, relative to .folder
		.signal boolean default from Node God settings: whether process accepts SIGUSR2 signal
		*/
		function updateAppEntity() {

			var feApps = {} // key: app id configured in frontend
			for (var appId in appLoaderOpts.apps) feApps[appId] = true

			var pApps = {} // key: app id that parent process has running
			for (var appId in parentApps) pApps[appId] = true
			for (var appId in appFileApps) { // create or update front end AppEntity instances
				var o = getAppConfig(appFileApps[appId], appId)
				if (!feApps[o.id]) appLoaderOpts.apps[o.id] = new appentity.AppEntity(o, parentApps[o.id]) // app is new to frontend
					.on('data', appLoaderOpts.appListener)
					.on('error', getErrorListener(o.id))
				else appLoaderOpts.apps[o.id].update(o)
				delete feApps[o.id]
				delete pApps[o.id]
			}

			for (var appId in feApps) { // close front end apps
				var appEntity = appLoaderOpts[o.id]
				delete appLoaderOpts[o.id]
				appEntity.close()
				appEntity.removeAllListener()
				delete pApps[o.id]
			}

			for (var appId in pApps) { // kill spurious patent process apps
				// TODO
			}

			if (launchBrowser) {
				appLoaderOpts.launchedBrowser = true
				haraldutil.browseTo(launchBrowser)
			}

			cb()
		}

		function getErrorListener(appId) {
			return listener

			function listener(err) {
				errEmitter.emit('error', new Error(appId + ': ' + err.message))
			}
		}

		function getAppConfig(fileApp, appId) {
			var o = {
				id: appId,
				name: fileApp.name,
			}

			o.state = states[fileApp.state || 0] ||  states[0]

			o.folder = path.resolve(appLoaderOpts.parentFolder, String(fileApp.folder || o.id)) // absolute path

			o.start = Array.isArray(fileApp.start) ? fileApp.start.map(makeString) :
				['node', path.join(o.folder, 'app')]

			o.debug = Array.isArray(fileApp.debug) ? fileApp.debug.map(makeString) :
				['node', '--debug-brk', path.join(o.folder, 'app')]

			o.watchFiles = typeof fileApp.watchFiles === 'string' || fileApp.watchFiles instanceof RegExp ? [fileApp.watchFiles] :
				Array.isArray(fileApp.watchFiles) ? fileApp.watchFiles.map(makeStringOrRegExp) :
				[]

			o.watchFileExclude = Array.isArray(fileApp.watchFileExclude) ? fileApp.watchFileExclude.map(makeString) :
				[]

			o.watchCopy = {}
			for (var dest in fileApp.watchCopy)
				o.watchCopy[
					path.resolve(o.folder, String(dest))] =
					path.resolve(o.folder, String(fileApp.watchCopy[dest]))

			o.signal = fileApp.signal != null ? !!fileApp.signal : appLoaderOpts.signal

			if (fileApp.launchBrowser && !appLoaderOpts.launchedBrowser) launchBrowser = fileApp.launchBrowser

			return o
		}

		function makeString(v) {
			return String(v)
		}

		function makeStringOrRegExp(v) {
			return v instanceof RegExp ? v : String(v)
		}
	}
}
392643
function create(appName, callback) {
    commons.post(format('/%s/apps/', deis.version), {
      id: appName
    }, callback);
  }
836642
function prepareProject(cordovaPlatforms, args, /* optional */ projectPath) {
    if (typeof (cordovaPlatforms) == "string") {
        cordovaPlatforms = [cordovaPlatforms];
    }

    if (!projectPath) {
        projectPath = defaultConfig.projectPath;
    }

    var appendedVersion = cache.getModuleVersionFromConfig(defaultConfig);
    if (appendedVersion) {
        appendedVersion = '@' + appendedVersion;
    } else {
        appendedVersion = '';
    }

    return utilities.isCompatibleNpmPackage(defaultConfig.nodePackageName + appendedVersion).then(function (compatibilityResult) {
        switch (compatibilityResult) {
            case utilities.NodeCompatibilityResult.IncompatibleVersion4Ios:
                throw new Error('This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471');
            case utilities.NodeCompatibilityResult.IncompatibleVersion5:
                throw new Error('This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471');
        }

        return setupCordova();
    }).then(function (cordova) {
        return addSupportPluginIfRequested(cordova, defaultConfig);
    }).then(function (cordova) {
        // Add platforms if not done already
        var promise = _addPlatformsToProject(cordovaPlatforms, projectPath, cordova);
        //Build each platform with args in args object
        cordovaPlatforms.forEach(function (platform) {
            promise = promise.then(function () {
                // Build app with platform specific args if specified
                var callArgs = utilities.getCallArgs(platform, args);
                var argsString = _getArgsString(callArgs.options);
                console.log('Queueing prepare for platform ' + platform + ' w/options: ' + argsString);
                return cordova.raw.prepare(callArgs);
            });
        });

        return promise;
    });
}
485260
async function parse(apkPath, target = `${os.tmpdir()}/apktoolDecodes`) {
  const cmd = `java -jar ${apktoolPath} d ${apkPath} -f -o ${target}`
  await shell(cmd)
  const MainfestFilePath = `${target}/AndroidManifest.xml`
  const doc = await parseManifest(MainfestFilePath)
  return parseDoc(doc)
}
106739
function create(options) {
  console.log('Creating app: ', options.name);

  if (!options.status)
    options.status = (code, msg) => {
      console.log(msg);
    };
  if (!options.type) options.type = 'rekit-react';

  const prjDir = path.join(options.location || process.cwd(), options.name);
  return new Promise(async (resolve, reject) => {
    try {
      if (fs.existsSync(prjDir)) {
        reject('FOLDER_EXISTS');
        return;
      }
      fs.mkdirSync(prjDir);
      let gitRepo;
      if (options.source) {
        if (/^https?:/.test(options.source)) {
          // It's a git repo
          gitRepo = options.source;
        } else {
          // It's a local folder
          const srcDir = path.isAbsolute(options.source)
            ? options.source
            : path.join(process.cwd(), options.source);
          options.status('CREATE_APP_COPY_FILES', `Copy files from ${srcDir}...`);
          await fs.copy(srcDir, prjDir, {
            filter: src => !/\/(\.git|node_modules\/|node_modules$)/.test(src) || path.basename(src) === '.gitignore',
          });
        }
      } else if (options.type) {
        // Get gitRepo
        options.status(
          'QUERY_APP_TYPES_GIT_REPO',
          `Looking for the git repo for app type ${options.type}...`,
        );
        const appTypes = await getAppTypes();
        const appType = _.find(appTypes, { id: options.type });
        if (!appType) reject('APP_TYPE_NOT_SUPPORTED');
        gitRepo = appType.repo;
      } else {
        await fs.remove(prjDir);
        reject('NO_SOURCE_OR_APP_TYPE');
      }

      if (gitRepo) {
        options.status('CLONE_PROJECT', `Downloading project from ${gitRepo}...`);
        await cloneRepo(gitRepo, prjDir);
      }

      postCreate(prjDir, options);
      options.status('CREATION_SUCCESS', '😃App creation success.');
      resolve();
    } catch (err) {
      console.log('Failed to create project.');
      fs.removeSync(prjDir);
      reject(err);
    }
  });
}
259916
function (deployPath) {
  const envFilePath = setupHelper.setupFolderAbsolutePath() + '/' + setupConfig.env_vars_file
    , clearCacheOfExpr = /(openst-platform\/config\/)|(openst-platform\/lib\/)|(openst-platform\/services\/)/;

  return new Promise(function (onResolve, onReject) {
    // source env
    shellSource(envFilePath, async function (err) {
      if (err) {
        throw err;
      }
      Object.keys(require.cache).forEach(function (key) {
        if (key.search(clearCacheOfExpr) !== -1) {
          delete require.cache[key];
        }
      });

      const setupHelper = require(deployPath);
      return onResolve(await setupHelper.perform());
    });
  });

}
806011
function attachHMRServer({httpServer, path, packagerServer}) {
  let client = null;

  function disconnect() {
    client = null;
    packagerServer.setHMRFileChangeListener(null);
  }

  // For the give platform and entry file, returns a promise with:
  //   - The full list of dependencies.
  //   - The shallow dependencies each file on the dependency list has
  //   - Inverse shallow dependencies map
  function getDependencies(platform, bundleEntry) {
    return packagerServer.getDependencies({
      platform: platform,
      dev: true,
      hot: true,
      entryFile: bundleEntry,
    }).then(response => {
      const {getModuleId} = response;

      // for each dependency builds the object:
      // `{path: '/a/b/c.js', deps: ['modA', 'modB', ...]}`
      return Promise.all(Object.values(response.dependencies).map(dep => {
        return dep.getName().then(depName => {
          if (dep.isAsset() || dep.isJSON()) {
            return Promise.resolve({path: dep.path, deps: []});
          }
          return packagerServer.getShallowDependencies({
            platform: platform,
            dev: true,
            hot: true,
            entryFile: dep.path
          })
            .then(deps => {
              return {
                path: dep.path,
                name: depName,
                deps,
              };
            });
        });
      }))
      .then(deps => {
        // list with all the dependencies' filenames the bundle entry has
        const dependenciesCache = response.dependencies.map(dep => dep.path);

        // map from module name to path
        const moduleToFilenameCache = Object.create(null);
        deps.forEach(dep => {
          moduleToFilenameCache[dep.name] = dep.path;
        });

        // map that indicates the shallow dependency each file included on the
        // bundle has
        const shallowDependencies = Object.create(null);
        deps.forEach(dep => {
          shallowDependencies[dep.path] = dep.deps;
        });

        // map from module name to the modules' dependencies the bundle entry
        // has
        const dependenciesModulesCache = Object.create(null);
        response.dependencies.forEach(dep => {
          dependenciesModulesCache[getModuleId(dep)] = dep;
        });


        const inverseDependenciesCache = Object.create(null);
        const inverseDependencies = getInverseDependencies(response);
        for (const [module, dependents] of inverseDependencies) {
          inverseDependenciesCache[getModuleId(module)] =
            Array.from(dependents).map(getModuleId);
        }

        return {
          dependenciesCache,
          dependenciesModulesCache,
          shallowDependencies,
          inverseDependenciesCache,
          resolutionResponse: response,
        };
      });
    });
  }

  const WebSocketServer = require('ws').Server;
  const wss = new WebSocketServer({
    server: httpServer,
    path: path,
  });

  wss.on('connection', ws => {
    const params = querystring.parse(url.parse(ws.upgradeReq.url).query);

    getDependencies(params.platform, params.bundleEntry)
      .then(({
        dependenciesCache,
        dependenciesModulesCache,
        shallowDependencies,
        inverseDependenciesCache,
      }) => {
        client = {
          ws,
          platform: params.platform,
          bundleEntry: params.bundleEntry,
          dependenciesCache,
          dependenciesModulesCache,
          shallowDependencies,
          inverseDependenciesCache,
        };

        packagerServer.setHMRFileChangeListener((type, filename) => {
          if (!client) {
            return;
          }

          const blacklisted = blacklist.find(blacklistedPath =>
            filename.indexOf(blacklistedPath) !== -1
          );

          if (blacklisted) {
            return;
          }

          client.ws.send(JSON.stringify({type: 'update-start'}));
          const promise = type === 'delete'
            ? Promise.resolve()
            : packagerServer.getShallowDependencies({
                entryFile: filename,
                platform: client.platform,
                dev: true,
                hot: true,
              }).then(deps => {
                if (!client) {
                  return [];
                }

                // if the file dependencies have change we need to invalidate the
                // dependencies caches because the list of files we need to send
                // to the client may have changed
                const oldDependencies = client.shallowDependencies[filename];
                if (arrayEquals(deps, oldDependencies)) {
                  // Need to create a resolution response to pass to the bundler
                  // to process requires after transform. By providing a
                  // specific response we can compute a non recursive one which
                  // is the least we need and improve performance.
                  return packagerServer.getDependencies({
                    platform: client.platform,
                    dev: true,
                    hot: true,
                    entryFile: filename,
                    recursive: true,
                  }).then(response => {
                    const module = packagerServer.getModuleForPath(filename);

                    return response.copy({dependencies: [module]});
                  });
                }

                // if there're new dependencies compare the full list of
                // dependencies we used to have with the one we now have
                return getDependencies(client.platform, client.bundleEntry)
                  .then(({
                    dependenciesCache: depsCache,
                    dependenciesModulesCache: depsModulesCache,
                    shallowDependencies: shallowDeps,
                    inverseDependenciesCache: inverseDepsCache,
                    resolutionResponse,
                  }) => {
                    if (!client) {
                      return {};
                    }

                    // build list of modules for which we'll send HMR updates
                    const modulesToUpdate = [packagerServer.getModuleForPath(filename)];
                    Object.keys(depsModulesCache).forEach(module => {
                      if (!client.dependenciesModulesCache[module]) {
                        modulesToUpdate.push(depsModulesCache[module]);
                      }
                    });

                    // Need to send modules to the client in an order it can
                    // process them: if a new dependency graph was uncovered
                    // because a new dependency was added, the file that was
                    // changed, which is the root of the dependency tree that
                    // will be sent, needs to be the last module that gets
                    // processed. Reversing the new modules makes sense
                    // because we get them through the resolver which returns
                    // a BFS ordered list.
                    modulesToUpdate.reverse();

                    // invalidate caches
                    client.dependenciesCache = depsCache;
                    client.dependenciesModulesCache = depsModulesCache;
                    client.shallowDependencies = shallowDeps;
                    client.inverseDependenciesCache = inverseDepsCache;

                    return resolutionResponse.copy({
                      dependencies: modulesToUpdate
                    });
                  });
              })
              .then((resolutionResponse) => {
                if (!client) {
                  return;
                }

                // make sure the file was modified is part of the bundle
                if (!client.shallowDependencies[filename]) {
                  return;
                }

                const httpServerAddress = httpServer.address();

                // Sanitize the value from the HTTP server
                let packagerHost = 'localhost';
                if (httpServer.address().address &&
                    httpServer.address().address !== '::' &&
                    httpServer.address().address !== '') {
                  packagerHost = httpServerAddress.address;
                }

                return packagerServer.buildBundleForHMR({
                  entryFile: client.bundleEntry,
                  platform: client.platform,
                  resolutionResponse,
                }, packagerHost, httpServerAddress.port);
              })
              .then(bundle => {
                if (!client || !bundle || bundle.isEmpty()) {
                  return;
                }

                return JSON.stringify({
                  type: 'update',
                  body: {
                    modules: bundle.getModulesIdsAndCode(),
                    inverseDependencies: client.inverseDependenciesCache,
                    sourceURLs: bundle.getSourceURLs(),
                    sourceMappingURLs: bundle.getSourceMappingURLs(),
                  },
                });
              })
              .catch(error => {
                // send errors to the client instead of killing packager server
                let body;
                if (error.type === 'TransformError' ||
                    error.type === 'NotFoundError' ||
                    error.type === 'UnableToResolveError') {
                  body = {
                    type: error.type,
                    description: error.description,
                    filename: error.filename,
                    lineNumber: error.lineNumber,
                  };
                } else {
                  console.error(error.stack || error);
                  body = {
                    type: 'InternalError',
                    description: 'react-packager has encountered an internal error, ' +
                      'please check your terminal error output for more details',
                  };
                }

                return JSON.stringify({type: 'error', body});
              })
              .then(update => {
                if (!client || !update) {
                  return;
                }

                client.ws.send(update);
              });

          promise.then(() => {
            client.ws.send(JSON.stringify({type: 'update-done'}));
          });
        });

        client.ws.on('error', e => {
          console.error('[Hot Module Replacement] Unexpected error', e);
          disconnect();
        });

        client.ws.on('close', () => disconnect());
      })
    .catch(err => {
      throw err;
    });
  });
}