How to use installPackage method in Karma

Best JavaScript code snippet using karma

Webapps.js

Source:Webapps.js Github

copy

Full Screen

1/* This Source Code Form is subject to the terms of the Mozilla Public2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,3 * You can obtain one at http://mozilla.org/MPL/2.0/. */4const Cc = Components.classes;5const Ci = Components.interfaces;6const Cu = Components.utils;7const Cr = Components.results;8Cu.import("resource://gre/modules/XPCOMUtils.jsm");9Cu.import("resource://gre/modules/Services.jsm");10Cu.import("resource://gre/modules/DOMRequestHelper.jsm");11Cu.import("resource://gre/modules/ObjectWrapper.jsm");12XPCOMUtils.defineLazyServiceGetter(this, "cpmm",13 "@mozilla.org/childprocessmessagemanager;1",14 "nsIMessageSender");15function convertAppsArray(aApps, aWindow) {16 let apps = Cu.createArrayIn(aWindow);17 for (let i = 0; i < aApps.length; i++) {18 let app = aApps[i];19 apps.push(createApplicationObject(aWindow, app.origin, app.manifest, app.manifestURL, 20 app.receipts, app.installOrigin, app.installTime));21 }22 return apps;23}24function WebappsRegistry() {25}26WebappsRegistry.prototype = {27 __proto__: DOMRequestIpcHelper.prototype,28 __exposedProps__: {29 install: 'r',30#ifdef MOZ_PHOENIX31# Firefox Desktop: installPackage not implemented32#elifdef ANDROID33#ifndef MOZ_WIDGET_GONK34# Firefox Android (Fennec): installPackage not implemented35#else36# B2G Gonk: installPackage implemented37 installPackage: 'r',38#endif39#else40# B2G Desktop and others: installPackage implementation status varies41 installPackage: 'r',42#endif43 getSelf: 'r',44 getInstalled: 'r',45 mgmt: 'r'46 },47 /** from https://developer.mozilla.org/en/OpenWebApps/The_Manifest48 * only the name property is mandatory49 */50 checkManifest: function(aManifest, aInstallOrigin) {51 if (aManifest.name == undefined)52 return false;53 if (aManifest.installs_allowed_from) {54 return aManifest.installs_allowed_from.some(function(aOrigin) {55 return aOrigin == "*" || aOrigin == aInstallOrigin;56 });57 }58 return true;59 },60 receiveMessage: function(aMessage) {61 let msg = aMessage.json;62 if (msg.oid != this._id)63 return64 let req = this.getRequest(msg.requestID);65 if (!req)66 return;67 let app = msg.app;68 switch (aMessage.name) {69 case "Webapps:Install:Return:OK":70 Services.DOMRequest.fireSuccess(req, createApplicationObject(this._window, app.origin, app.manifest, app.manifestURL, app.receipts,71 app.installOrigin, app.installTime));72 break;73 case "Webapps:Install:Return:KO":74 Services.DOMRequest.fireError(req, msg.error || "DENIED");75 break;76 case "Webapps:GetSelf:Return:OK":77 if (msg.apps.length) {78 app = msg.apps[0];79 Services.DOMRequest.fireSuccess(req, createApplicationObject(this._window, app.origin, app.manifest, app.manifestURL, app.receipts,80 app.installOrigin, app.installTime));81 } else {82 Services.DOMRequest.fireSuccess(req, null);83 }84 break;85 case "Webapps:GetInstalled:Return:OK":86 Services.DOMRequest.fireSuccess(req, convertAppsArray(msg.apps, this._window));87 break;88 case "Webapps:GetSelf:Return:KO":89 Services.DOMRequest.fireError(req, "ERROR");90 break;91 }92 this.removeRequest(msg.requestID);93 },94 _getOrigin: function(aURL) {95 let uri = Services.io.newURI(aURL, null, null);96 return uri.prePath; 97 },98 _validateScheme: function(aURL) {99 let scheme = Services.io.newURI(aURL, null, null).scheme;100 if (scheme != "http" && scheme != "https") {101 throw new Components.Exception(102 "INVALID_URL_SCHEME: '" + scheme + "'; must be 'http' or 'https'",103 Cr.NS_ERROR_FAILURE104 );105 }106 },107 // mozIDOMApplicationRegistry implementation108 109 install: function(aURL, aParams) {110 this._validateScheme(aURL);111 let installURL = this._window.location.href;112 let installOrigin = this._getOrigin(installURL);113 let request = this.createRequest();114 let requestID = this.getRequestId(request);115 let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);116 xhr.open("GET", aURL, true);117 xhr.channel.loadFlags |= Ci.nsIRequest.VALIDATE_ALWAYS;118 xhr.addEventListener("load", (function() {119 if (xhr.status == 200) {120 try {121 let manifest = JSON.parse(xhr.responseText, installOrigin);122 if (!this.checkManifest(manifest, installOrigin)) {123 Services.DOMRequest.fireError(request, "INVALID_MANIFEST");124 } else {125 let receipts = (aParams && aParams.receipts && Array.isArray(aParams.receipts)) ? aParams.receipts : [];126 let categories = (aParams && aParams.categories && Array.isArray(aParams.categories)) ? aParams.categories : [];127 cpmm.sendAsyncMessage("Webapps:Install", { app: { installOrigin: installOrigin,128 origin: this._getOrigin(aURL),129 manifestURL: aURL,130 manifest: manifest,131 receipts: receipts,132 categories: categories },133 from: installURL,134 oid: this._id,135 requestID: requestID });136 }137 } catch(e) {138 Services.DOMRequest.fireError(request, "MANIFEST_PARSE_ERROR");139 }140 }141 else {142 Services.DOMRequest.fireError(request, "MANIFEST_URL_ERROR");143 } 144 }).bind(this), false);145 xhr.addEventListener("error", (function() {146 Services.DOMRequest.fireError(request, "NETWORK_ERROR");147 }).bind(this), false);148 xhr.send(null);149 return request;150 },151 getSelf: function() {152 let request = this.createRequest();153 cpmm.sendAsyncMessage("Webapps:GetSelf", { origin: this._getOrigin(this._window.location.href),154 oid: this._id,155 requestID: this.getRequestId(request) });156 return request;157 },158 getInstalled: function() {159 let request = this.createRequest();160 cpmm.sendAsyncMessage("Webapps:GetInstalled", { origin: this._getOrigin(this._window.location.href),161 oid: this._id,162 requestID: this.getRequestId(request) });163 return request;164 },165 get mgmt() {166 if (!this._mgmt)167 this._mgmt = new WebappsApplicationMgmt(this._window);168 return this._mgmt;169 },170 uninit: function() {171 this._mgmt = null;172 },173 // mozIDOMApplicationRegistry2 implementation174 installPackage: function(aPackageURL, aParams) {175 this._validateScheme(aPackageURL);176 let request = this.createRequest();177 let requestID = this.getRequestId(request);178 let receipts = (aParams && aParams.receipts &&179 Array.isArray(aParams.receipts)) ? aParams.receipts : [];180 let categories = (aParams && aParams.categories &&181 Array.isArray(aParams.categories)) ? aParams.categories : [];182 cpmm.sendAsyncMessage("Webapps:InstallPackage", { url: aPackageURL,183 receipts: receipts,184 categories: categories,185 requestID: requestID,186 oid: this._id,187 from: this._window.location.href,188 installOrigin: this._getOrigin(this._window.location.href) });189 return request;190 },191 // nsIDOMGlobalPropertyInitializer implementation192 init: function(aWindow) {193 this.initHelper(aWindow, ["Webapps:Install:Return:OK", "Webapps:Install:Return:KO",194 "Webapps:GetInstalled:Return:OK",195 "Webapps:GetSelf:Return:OK", "Webapps:GetSelf:Return:KO"]);196 let util = this._window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);197 this._id = util.outerWindowID;198 },199 200 classID: Components.ID("{fff440b3-fae2-45c1-bf03-3b5a2e432270}"),201 QueryInterface: XPCOMUtils.generateQI([Ci.mozIDOMApplicationRegistry,202#ifdef MOZ_PHOENIX203# Firefox Desktop: installPackage not implemented204#elifdef ANDROID205#ifndef MOZ_WIDGET_GONK206# Firefox Android (Fennec): installPackage not implemented207#else208# B2G Gonk: installPackage implemented209 Ci.mozIDOMApplicationRegistry2,210#endif211#else212# B2G Desktop and others: installPackage implementation status varies213 Ci.mozIDOMApplicationRegistry2,214#endif215 Ci.nsIDOMGlobalPropertyInitializer]),216 217 classInfo: XPCOMUtils.generateCI({classID: Components.ID("{fff440b3-fae2-45c1-bf03-3b5a2e432270}"),218 contractID: "@mozilla.org/webapps;1",219 interfaces: [Ci.mozIDOMApplicationRegistry,220#ifdef MOZ_PHOENIX221# Firefox Desktop: installPackage not implemented222#elifdef ANDROID223#ifndef MOZ_WIDGET_GONK224# Firefox Android (Fennec): installPackage not implemented225#else226# B2G Gonk: installPackage implemented227 Ci.mozIDOMApplicationRegistry2,228#endif229#else230# B2G Desktop and others: installPackage implementation status varies231 Ci.mozIDOMApplicationRegistry2,232#endif233 ],234 flags: Ci.nsIClassInfo.DOM_OBJECT,235 classDescription: "Webapps Registry"})236}237/**238 * mozIDOMApplication object239 */240function createApplicationObject(aWindow, aOrigin, aManifest, aManifestURL, aReceipts, aInstallOrigin, aInstallTime) {241 let app = Cc["@mozilla.org/webapps/application;1"].createInstance(Ci.mozIDOMApplication);242 app.wrappedJSObject.init(aWindow, aOrigin, aManifest, aManifestURL, aReceipts, aInstallOrigin, aInstallTime);243 return app;244}245function WebappsApplication() {246 this.wrappedJSObject = this;247}248WebappsApplication.prototype = {249 __proto__: DOMRequestIpcHelper.prototype,250 __exposedProps__: {251 origin: 'r',252 manifest: 'r',253 manifestURL: 'r',254 installOrigin: 'r',255 installTime: 'r',256 status: 'r',257 progress: 'r',258 onprogress: 'rw',259 launch: 'r',260 receipts: 'r',261 uninstall: 'r'262 },263 init: function(aWindow, aOrigin, aManifest, aManifestURL, aReceipts, aInstallOrigin, aInstallTime) {264 this.origin = aOrigin;265 this.manifest = ObjectWrapper.wrap(aManifest, aWindow);266 this.manifestURL = aManifestURL;267 this.receipts = aReceipts;268 this.installOrigin = aInstallOrigin;269 this.installTime = aInstallTime;270 this.status = "installed";271 this.progress = NaN;272 this._onprogress = null;273 this.initHelper(aWindow, ["Webapps:Uninstall:Return:OK", "Webapps:Uninstall:Return:KO", "Webapps:OfflineCache"]);274 },275 set onprogress(aCallback) {276 this._onprogress = aCallback;277 },278 get onprogress() {279 return this._onprogress;280 },281 launch: function(aStartPoint) {282 let request = this.createRequest();283 cpmm.sendAsyncMessage("Webapps:Launch", { origin: this.origin,284 startPoint: aStartPoint || "",285 oid: this._id,286 requestID: this.getRequestId(request) });287 return request;288 },289 uninstall: function() {290 let request = this.createRequest();291 cpmm.sendAsyncMessage("Webapps:Uninstall", { origin: this.origin,292 oid: this._id,293 requestID: this.getRequestId(request) });294 return request;295 },296 uninit: function() {297 this._onprogress = null;298 },299 receiveMessage: function(aMessage) {300 var msg = aMessage.json;301 let req = this.takeRequest(msg.requestID);302 if ((msg.oid != this._id || !req) && aMessage.name !== "Webapps:OfflineCache")303 return;304 switch (aMessage.name) {305 case "Webapps:Uninstall:Return:OK":306 Services.DOMRequest.fireSuccess(req, msg.origin);307 break;308 case "Webapps:Uninstall:Return:KO":309 Services.DOMRequest.fireError(req, "NOT_INSTALLED");310 break;311 case "Webapps:OfflineCache":312 if (msg.manifest != this.manifestURL)313 return;314 315 this.status = msg.status;316 if (this._onprogress) {317 let event = new this._window.MozApplicationEvent("applicationinstall", { application: this });318 this._onprogress.handleEvent(event);319 }320 break;321 }322 },323 classID: Components.ID("{723ed303-7757-4fb0-b261-4f78b1f6bd22}"),324 QueryInterface: XPCOMUtils.generateQI([Ci.mozIDOMApplication]),325 classInfo: XPCOMUtils.generateCI({classID: Components.ID("{723ed303-7757-4fb0-b261-4f78b1f6bd22}"),326 contractID: "@mozilla.org/webapps/application;1",327 interfaces: [Ci.mozIDOMApplication],328 flags: Ci.nsIClassInfo.DOM_OBJECT,329 classDescription: "Webapps Application"})330}331/**332 * mozIDOMApplicationMgmt object333 */334function WebappsApplicationMgmt(aWindow) {335 let principal = aWindow.document.nodePrincipal;336 let secMan = Cc["@mozilla.org/scriptsecuritymanager;1"].getService(Ci.nsIScriptSecurityManager);337 let perm = principal == secMan.getSystemPrincipal()338 ? Ci.nsIPermissionManager.ALLOW_ACTION339 : Services.perms.testExactPermissionFromPrincipal(principal, "webapps-manage");340 //only pages with perm set can use some functions341 this.hasPrivileges = perm == Ci.nsIPermissionManager.ALLOW_ACTION;342 this.initHelper(aWindow, ["Webapps:GetAll:Return:OK", "Webapps:GetAll:Return:KO",343 "Webapps:Install:Return:OK", "Webapps:Uninstall:Return:OK",344 "Webapps:GetNotInstalled:Return:OK"]);345 this._oninstall = null;346 this._onuninstall = null;347}348WebappsApplicationMgmt.prototype = {349 __proto__: DOMRequestIpcHelper.prototype,350 __exposedProps__: {351 getAll: 'r',352 getNotInstalled: 'r',353 oninstall: 'rw',354 onuninstall: 'rw'355 },356 uninit: function() {357 this._oninstall = null;358 this._onuninstall = null;359 },360 getAll: function() {361 let request = this.createRequest();362 cpmm.sendAsyncMessage("Webapps:GetAll", { oid: this._id,363 requestID: this.getRequestId(request),364 hasPrivileges: this.hasPrivileges });365 return request;366 },367 getNotInstalled: function() {368 let request = this.createRequest();369 cpmm.sendAsyncMessage("Webapps:GetNotInstalled", { oid: this._id,370 requestID: this.getRequestId(request) });371 return request;372 },373 get oninstall() {374 return this._oninstall;375 },376 get onuninstall() {377 return this._onuninstall;378 },379 set oninstall(aCallback) {380 if (this.hasPrivileges)381 this._oninstall = aCallback;382 else383 throw new Components.Exception("Denied", Cr.NS_ERROR_FAILURE);384 },385 set onuninstall(aCallback) {386 if (this.hasPrivileges)387 this._onuninstall = aCallback;388 else389 throw new Components.Exception("Denied", Cr.NS_ERROR_FAILURE);390 },391 receiveMessage: function(aMessage) {392 var msg = aMessage.json;393 let req = this.getRequest(msg.requestID);394 // We want Webapps:Install:Return:OK and Webapps:Uninstall:Return:OK to be boradcasted395 // to all instances of mozApps.mgmt396 if (!((msg.oid == this._id && req) 397 || aMessage.name == "Webapps:Install:Return:OK" || aMessage.name == "Webapps:Uninstall:Return:OK"))398 return;399 switch (aMessage.name) {400 case "Webapps:GetAll:Return:OK":401 Services.DOMRequest.fireSuccess(req, convertAppsArray(msg.apps, this._window));402 break;403 case "Webapps:GetAll:Return:KO":404 Services.DOMRequest.fireError(req, "DENIED");405 break;406 case "Webapps:GetNotInstalled:Return:OK":407 Services.DOMRequest.fireSuccess(req, convertAppsArray(msg.apps, this._window));408 break;409 case "Webapps:Install:Return:OK":410 if (this._oninstall) {411 let app = msg.app;412 let event = new this._window.MozApplicationEvent("applicationinstall", 413 { application : createApplicationObject(this._window, app.origin, app.manifest, app.manifestURL, app.receipts,414 app.installOrigin, app.installTime) });415 this._oninstall.handleEvent(event);416 }417 break;418 case "Webapps:Uninstall:Return:OK":419 if (this._onuninstall) {420 let event = new this._window.MozApplicationEvent("applicationuninstall", 421 { application : createApplicationObject(this._window, msg.origin, null, null, null, null, 0) });422 this._onuninstall.handleEvent(event);423 }424 break;425 }426 this.removeRequest(msg.requestID);427 },428 classID: Components.ID("{8c1bca96-266f-493a-8d57-ec7a95098c15}"),429 QueryInterface: XPCOMUtils.generateQI([Ci.mozIDOMApplicationMgmt]),430 classInfo: XPCOMUtils.generateCI({classID: Components.ID("{8c1bca96-266f-493a-8d57-ec7a95098c15}"),431 contractID: "@mozilla.org/webapps/application-mgmt;1",432 interfaces: [Ci.mozIDOMApplicationMgmt],433 flags: Ci.nsIClassInfo.DOM_OBJECT,434 classDescription: "Webapps Application Mgmt"})435}...

Full Screen

Full Screen

npm.js

Source:npm.js Github

copy

Full Screen

1/* eslint-disable no-console */2const spawn = require('cross-spawn');3const semver = require('semver');4const tmp = require('tmp');5const fs = require('fs-extra');6const { unpack } = require('tar-pack');7const { createHash } = require('crypto');8const escape = require('escape-string-regexp');9const dns = require('dns');10const path = require('path');11const { execSync } = require('child_process');12const checkNpmCanReadCwd = () => {13 const cwd = process.cwd();14 let childOutput = null;15 try {16 childOutput = spawn.sync('npm', ['config', 'list']).output.join('');17 } catch (err) {18 return true;19 }20 if (typeof childOutput !== 'string') {21 return true;22 }23 const lines = childOutput.split('\n');24 const prefix = '; cwd = ';25 const line = lines.find((item) => item.startsWith(prefix));26 if (typeof line !== 'string') {27 return true;28 }29 const npmCWD = line.substring(prefix.length);30 if (npmCWD === cwd) {31 return true;32 }33 console.error(34 chalk.red(35 `Could not start an npm process in the right directory.\n\n` +36 `The current directory is: ${chalk.bold(cwd)}\n` +37 `However, a newly started npm process runs in: ${chalk.bold(38 npmCWD39 )}\n\n` +40 `This is probably caused by a misconfigured system terminal shell.`41 )42 );43 if (process.platform === 'win32') {44 console.error(45 `${chalk.red(46 `On Windows, this can usually be fixed by running:\n\n`47 )} ${chalk.cyan(48 'reg'49 )} delete "HKCU\\Software\\Microsoft\\Command Processor" /v AutoRun /f\n` +50 ` ${chalk.cyan(51 'reg'52 )} delete "HKLM\\Software\\Microsoft\\Command Processor" /v AutoRun /f\n\n${chalk.red(53 `Try to run the above two lines in the terminal.\n`54 )}${chalk.red(55 `To learn more about this problem, read: https://blogs.msdn.microsoft.com/oldnewthing/20071121-00/?p=24433/`56 )}`57 );58 }59 return false;60};61const checkNpmVersion = () => {62 let hasMinNpm = false;63 let npmVersion = null;64 try {65 npmVersion = execSync('npm --version').toString().trim();66 hasMinNpm = semver.gte(npmVersion, '6.0.0');67 } catch (err) {68 console.error(chalk.red(err));69 }70 return {71 hasMinNpm,72 npmVersion,73 };74};75const checkYarnVersion = () => {76 const minYarnPnp = '1.12.0';77 const maxYarnPnp = '2.0.0';78 let hasMinYarnPnp = false;79 let hasMaxYarnPnp = false;80 let yarnVersion = null;81 try {82 yarnVersion = execSync('yarnpkg --version').toString().trim();83 if (semver.valid(yarnVersion)) {84 hasMinYarnPnp = semver.gte(yarnVersion, minYarnPnp);85 hasMaxYarnPnp = semver.lt(yarnVersion, maxYarnPnp);86 } else {87 const trimmedYarnVersionMatch = /^(.+?)[-+].+$/.exec(yarnVersion);88 if (trimmedYarnVersionMatch) {89 const trimmedYarnVersion = trimmedYarnVersionMatch.pop();90 hasMinYarnPnp = semver.gte(trimmedYarnVersion, minYarnPnp);91 hasMaxYarnPnp = semver.lt(trimmedYarnVersion, maxYarnPnp);92 }93 }94 } catch (err) {95 console.error(chalk.red(err));96 }97 return {98 hasMinYarnPnp,99 hasMaxYarnPnp,100 yarnVersion,101 };102};103const getTemporaryDirectory = () =>104 new Promise((resolve, reject) => {105 tmp.dir({ unsafeCleanup: true }, (err, tmpdir, callback) => {106 if (err) {107 reject(err);108 } else {109 resolve({110 tmpdir,111 cleanup: () => {112 try {113 callback();114 } catch (ignored) {115 // Callback might throw and fail, since it's a temp directory the116 // OS will clean it up eventually...117 }118 },119 });120 }121 });122 });123const extractStream = (stream, dest) =>124 new Promise((resolve, reject) => {125 stream.pipe(126 unpack(dest, (err) => {127 if (err) reject(err);128 else resolve(dest);129 })130 );131 });132const getPackageInfo = async (installPackage) => {133 if (installPackage.match(/^.+\.(tgz|tar\.gz)$/)) {134 try {135 const { tmpdir, cleanup } = await getTemporaryDirectory();136 let stream;137 if (/^http/.test(installPackage)) {138 stream = hyperquest(installPackage);139 } else {140 stream = fs.createReadStream(installPackage);141 }142 await extractStream(stream, tmpdir);143 const { name, version } = require(path.join(tmpdir, 'package.json'));144 cleanup();145 return { name, version };146 } catch (err) {147 console.log(148 `Could not extract the package name from the archive: ${err.toString()}`149 );150 const assumedProjectName = installPackage.match(151 /^.+\/(.+?)(?:-\d+.+)?\.(tgz|tar\.gz)$/152 )[1];153 console.log(154 `Based on the filename, assuming it is "${chalk.cyan(155 assumedProjectName156 )}"`157 );158 return { name: assumedProjectName };159 }160 }161 if (installPackage.startsWith('git+'))162 return {163 name: installPackage.match(/([^/]+)\.git(#.*)?$/)[1],164 };165 if (installPackage.match(/.+@/))166 return {167 name: installPackage.charAt(0) + installPackage.substr(1).split('@')[0],168 version: installPackage.split('@')[1],169 };170 if (installPackage.match(/^file:/)) {171 const installPackagePath = installPackage.match(/^file:(.*)?$/)[1];172 const { name, version } = require(path.join(173 installPackagePath,174 'package.json'175 ));176 return { name, version };177 }178 return { name: installPackage };179};180const getProxy = () => {181 let httpsProxy;182 if (process.env.https_proxy) httpsProxy = process.env.https_proxy;183 else {184 try {185 const npmProxy = execSync('npm config get https-proxy');186 npmProxy && (httpsProxy = npmProxy.toString().trim());187 } catch (e) {188 //189 }190 }191 return httpsProxy;192};193const checkIfOnline = (useYarn) =>194 new Promise((resolve) => {195 if (!useYarn) resolve(true);196 dns.lookup('registry.yarnpkg.com', (err) => {197 let proxy;198 if (err !== null && (proxy = getProxy())) {199 dns.lookup(new URL(proxy).hostname, (proxyErr) => {200 resolve(proxyErr == null);201 });202 } else resolve(err == null);203 });204 });205const install = ({ root, useYarn, usePnp, dependencies, verbose, isOnline }) =>206 new Promise((resolve, reject) => {207 let command;208 let args;209 if (useYarn) {210 command = 'yarnpkg';211 args = ['add', '--exact'];212 !isOnline && args.push('--offline');213 usePnp && args.push('--enable-pnp');214 args.push(...dependencies);215 args.push('--cwd');216 args.push(root);217 if (!isOnline) {218 console.log(chalk.yellow('You appear to be offline.'));219 console.log(chalk.yellow('Falling back to the local Yarn cache.'));220 console.log();221 }222 } else {223 command = 'npm';224 args = [225 'install',226 '--no-audit',227 '--save',228 '--save-exact',229 '--loglevel',230 'error',231 ...dependencies,232 ];233 if (usePnp) {234 console.log(chalk.yellow("NPM doesn't support PnP."));235 console.log(chalk.yellow('Falling back to the regular installs.'));236 console.log();237 }238 }239 verbose && args.push('--verbose');240 spawn(command, args, { stdio: 'inherit' }).on('close', (code) => {241 if (code !== 0) {242 reject({243 command: `${command} ${args.join(' ')}`,244 });245 return;246 }247 resolve();248 });249 });250const checkNodeVersion = (packageName, root) => {251 const packageJsonPath = path.resolve(252 root || process.cwd(),253 'node_modules',254 packageName,255 'package.json'256 );257 if (!fs.existsSync(packageJsonPath)) return;258 const { engines } = require(packageJsonPath);259 if (!engines || !engines.node) return;260 if (!semver.satisfies(process.version, engines.node)) {261 console.error(262 chalk.red(263 `You are running Node %s.\n 264 ${packageName} requires Node %s or higher. \n265 Please update your version of Node.`266 ),267 process.version,268 engines.node269 );270 process.exit(1);271 }272};273const getCacheIdentifier = (environment, packages) => {274 let cacheIdentifier = environment == null ? '' : environment.toString();275 for (const packageName of packages) {276 cacheIdentifier += `:${packageName}@`;277 try {278 cacheIdentifier += require(`${packageName}/package.json`).version;279 } catch (_) {280 // ignored281 }282 }283 return cacheIdentifier;284};285const createEnvironmentHash = (env) => {286 const hash = createHash('md5');287 hash.update(JSON.stringify(env));288 return hash.digest('hex');289};290const ignoredFiles = (appSrc) =>291 new RegExp(292 `^(?!${escape(293 path.normalize(`${appSrc}/`).replace(/[\\]+/g, '/')294 )}).+/node_modules/`,295 'g'296 );297module.exports = {298 checkNpmCanReadCwd,299 checkNpmVersion,300 checkYarnVersion,301 extractStream,302 getPackageInfo,303 getProxy,304 checkIfOnline,305 install,306 checkNodeVersion,307 getCacheIdentifier,308 createEnvironmentHash,309 ignoredFiles,...

Full Screen

Full Screen

installPackage.spec.js

Source:installPackage.spec.js Github

copy

Full Screen

...12var events = require('../../../lib/events');13var InvalidPackageError = require('../../../lib/errors').InvalidPackageError;14chai.use(chaiAsPromised);15chai.use(sinonChai);16describe('api.installPackage()', function() {17 var installPackage;18 var MockApi;19 var mockApi;20 var mockNpmCommands;21 before(function() {22 MockApi = mockApiFactory();23 mockApi = new MockApi('/project');24 mockNpmCommands = mockNpmCommandsFactory();25 installPackage = rewire('../../../lib/api/installPackage');26 installPackage.__set__('npmCommands', mockNpmCommands);27 installPackage = installPackage.bind(mockApi);28 });29 var unmockFiles = null;30 afterEach(function() {31 if (unmockFiles) {32 unmockFiles();33 unmockFiles = null;34 }35 MockApi.reset();36 mockApi.reset();37 mockNpmCommands.reset();38 });39 it('should throw an error if no package is specified', function() {40 var pkg = {};41 var config = {};42 var files = {43 '/project/package.json': JSON.stringify(pkg),44 '/project/.skivvyrc': JSON.stringify(config)45 };46 unmockFiles = mockFiles(files);47 var expected, actual;48 expected = InvalidPackageError;49 actual = [50 installPackage({ path: '/project' }),51 installPackage({ path: '/project', package: undefined }),52 installPackage({ path: '/project', package: null }),53 installPackage({ path: '/project', package: false }),54 installPackage({ path: '/project', package: '' })55 ];56 return Promise.all(actual.map(function(actual) {57 return expect(actual).to.be.rejectedWith(expected);58 }));59 });60 it('should run npm install [package] in the specified directory', function() {61 var pkg = {};62 var config = {};63 var files = {64 '/project/package.json': JSON.stringify(pkg),65 '/project/.skivvyrc': JSON.stringify(config)66 };67 unmockFiles = mockFiles(files);68 var expected, actual;69 return installPackage({70 package: 'package'71 })72 .then(function(returnValue) {73 expected = '1.2.3';74 actual = returnValue;75 expect(actual).to.equal(expected);76 var npmOptions = {77 'save-dev': true78 };79 expect(mockNpmCommands.install).to.have.been.calledWith('@skivvy/skivvy-package-package', npmOptions, '/project');80 });81 });82 it('should add a package namespace to the config file if none exists', function() {83 var pkg = {};84 var config = {};85 var files = {86 '/project/package.json': JSON.stringify(pkg),87 '/project/.skivvyrc': JSON.stringify(config)88 };89 unmockFiles = mockFiles(files);90 var expected, actual;91 return installPackage({92 package: 'package'93 })94 .then(function(returnValue) {95 expected = {96 packages: {97 'package': {98 config: {},99 tasks: {}100 }101 }102 };103 actual = JSON.parse(fs.readFileSync('/project/.skivvyrc', 'utf8'));104 expect(actual).to.eql(expected);105 });106 });107 it('should add a packages section to the config file if none exists', function() {108 var pkg = {};109 var config = {};110 var files = {111 '/project/package.json': JSON.stringify(pkg),112 '/project/.skivvyrc': JSON.stringify(config)113 };114 unmockFiles = mockFiles(files);115 var expected, actual;116 return installPackage({117 package: 'package'118 })119 .then(function(returnValue) {120 expected = {121 packages: {122 'package': {123 config: {},124 tasks: {}125 }126 }127 };128 actual = JSON.parse(fs.readFileSync('/project/.skivvyrc', 'utf8'));129 expect(actual).to.eql(expected);130 });131 });132 it('should not modify the config file if the package namespace already exists', function() {133 var pkg = {};134 var config = {135 packages: {136 'package': {137 config: {138 message: 'Hello, world!'139 },140 tasks: {}141 }142 }143 };144 var files = {145 '/project/package.json': JSON.stringify(pkg),146 '/project/.skivvyrc': JSON.stringify(config)147 };148 unmockFiles = mockFiles(files);149 var expected, actual;150 return installPackage({151 package: 'package'152 })153 .then(function(returnValue) {154 expected = config;155 actual = JSON.parse(fs.readFileSync('/project/.skivvyrc', 'utf8'));156 expect(actual).to.eql(expected);157 });158 });159 it('should not conflict with existing modules', function() {160 var pkg = {};161 var config = {162 packages: {163 'hello-world': {164 config: {165 message: 'Hello, world!'166 },167 tasks: {}168 }169 }170 };171 var files = {172 '/project/package.json': JSON.stringify(pkg),173 '/project/.skivvyrc': JSON.stringify(config),174 '/project/node_modules/@skivvy/skivvy-package-hello-world/package.json': '{ "name": "skivvy-package-hello-world", "version": "1.2.3" }',175 '/project/node_modules/@skivvy/skivvy-package-hello-world/index.js': 'exports.tasks = {}; exports.description = \'Hello World package\';'176 };177 unmockFiles = mockFiles(files);178 var expected, actual;179 return installPackage({180 package: 'package'181 })182 .then(function(returnValue) {183 expected = '1.2.3';184 actual = returnValue;185 expect(actual).to.equal(expected);186 var npmOptions = {187 'save-dev': true188 };189 expect(mockNpmCommands.install).to.have.been.calledWith('@skivvy/skivvy-package-package', npmOptions, '/project');190 expected = {191 packages: {192 'hello-world': {193 config: {194 message: 'Hello, world!'195 },196 tasks: {}197 },198 'package': {199 config: {},200 tasks: {}201 }202 }203 };204 actual = JSON.parse(fs.readFileSync('/project/.skivvyrc', 'utf8'));205 expect(actual).to.eql(expected);206 });207 });208 it('should handle scoped packages correctly', function() {209 var pkg = {};210 var config = {211 packages: {212 'hello-world': {213 config: {214 message: 'Hello, world!'215 },216 tasks: {}217 }218 }219 };220 var files = {221 '/project/package.json': JSON.stringify(pkg),222 '/project/.skivvyrc': JSON.stringify(config),223 '/project/node_modules/@skivvy/skivvy-package-hello-world/package.json': '{ "name": "skivvy-package-hello-world", "version": "1.2.3" }',224 '/project/node_modules/@skivvy/skivvy-package-hello-world/index.js': 'exports.tasks = {}; exports.description = \'Hello World package\';'225 };226 unmockFiles = mockFiles(files);227 var expected, actual;228 return installPackage({229 package: '@my-packages/package'230 })231 .then(function(returnValue) {232 expected = '1.2.3';233 actual = returnValue;234 expect(actual).to.equal(expected);235 var npmOptions = {236 'save-dev': true237 };238 expect(mockNpmCommands.install).to.have.been.calledWith('@my-packages/skivvy-package-package', npmOptions, '/project');239 expected = {240 packages: {241 'hello-world': {242 config: {243 message: 'Hello, world!'244 },245 tasks: {}246 },247 '@my-packages/package': {248 config: {},249 tasks: {}250 }251 }252 };253 actual = JSON.parse(fs.readFileSync('/project/.skivvyrc', 'utf8'));254 expect(actual).to.eql(expected);255 });256 });257 it('should have tests for events', function() {258 var pkg = {};259 var config = {260 packages: {}261 };262 var files = {263 '/project/package.json': JSON.stringify(pkg),264 '/project/.skivvyrc': JSON.stringify(config)265 };266 unmockFiles = mockFiles(files);267 var expected, actual;268 expected = [269 {270 event: events.INSTALL_PACKAGE_STARTED,271 package: 'package',272 path: '/project'273 },274 {275 event: events.INSTALL_PACKAGE_COMPLETED,276 version: '1.2.3',277 package: 'package',278 path: '/project'279 }280 ];281 actual = [];282 mockApi.on(events.INSTALL_PACKAGE_STARTED, onStarted);283 mockApi.on(events.INSTALL_PACKAGE_COMPLETED, onCompleted);284 mockApi.on(events.INSTALL_PACKAGE_FAILED, onFailed);285 function onStarted(data) {286 actual.push({287 event: events.INSTALL_PACKAGE_STARTED,288 package: data.package,289 path: data.path290 });291 }292 function onCompleted(data) {293 actual.push({294 event: events.INSTALL_PACKAGE_COMPLETED,295 version: data.version,296 package: data.package,297 path: data.path298 });299 }300 function onFailed(data) {301 actual.push({302 event: events.INSTALL_PACKAGE_FAILED,303 error: data.error,304 package: data.package,305 path: data.path306 });307 }308 return installPackage({309 package: 'package',310 path: '/project'311 })312 .then(function() {313 return expect(actual).to.eql(expected);314 });315 });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const splitTextIntoArr = require('./utils/splitText');2const dependenciesGraph = new Map();3const installPackages = new Set();4const checkCyclic = (currentPackage, dependentPackage) => {5 if(dependenciesGraph.has(dependentPackage)) {6 const dependentGraphObj = dependenciesGraph.get(dependentPackage);7 if(dependentGraphObj.dependencies.has(currentPackage)) {8 return true;9 }10 return false;11 };12 return false;13}14const removeCyclicPackages = (currentPackage, dependentPackages) => {15 const nonCyclicPackages = new Set();16 const cyclicPackages = new Set();17 dependentPackages.forEach((packageName) => {18 if(!checkCyclic(currentPackage, packageName)) {19 nonCyclicPackages.add(packageName);20 } else {21 cyclicPackages.add(packageName);22 }23 });24 return { cyclic: cyclicPackages, nonCyclic: nonCyclicPackages };25}26const dependCommand = (commands) => {27 let result = '';28 29 const dependentUpon = commands[1];30 const dependentList = commands.slice(2, commands.length);31 const filterCyclic = removeCyclicPackages(dependentUpon, dependentList);32 const { cyclic, nonCyclic } = filterCyclic;33 if(dependenciesGraph.has(dependentUpon)) {34 const graphObj = dependenciesGraph.get(dependentUpon);35 graphObj.dependencies = new Set([...nonCyclic, ...graphObj.dependencies]);36 dependenciesGraph.set(dependentUpon, graphObj);37 } else {38 const innerObj = {39 dependencies: new Set([...nonCyclic]),40 parent: true,41 dependentUpon: new Set()42 }43 dependenciesGraph.set(dependentUpon, innerObj);44 };45 cyclic.forEach((packageName) => {46 result += `${packageName} depends upon on ${dependentUpon}, ignoring command`;47 result += '\n';48 });49 nonCyclic.forEach((packageName) => {50 if(dependenciesGraph.has(packageName)) {51 const graphObj = dependenciesGraph.get(packageName);52 graphObj.dependentUpon = new Set([dependentUpon, ...graphObj.dependentUpon]);53 dependenciesGraph.set(packageName, graphObj);54 } else {55 const innerObj = {56 dependencies: new Set(),57 parent: false,58 dependentUpon: new Set([dependentUpon])59 }60 dependenciesGraph.set(packageName, innerObj);61 }62 });63 return result;64};65const installCommand = (commands) => {66 const installPackage = commands[1];67 const installNodes = new Set();68 let result = '';69 const installPackagesDFS = (installPackage, check) => {70 if(!installNodes.has(installPackage)) {71 installNodes.add(installPackage);72 if(installPackages.has(installPackage)) {73 if(!check) {74 result += `${installPackage} is already installed`;75 result += '\n';76 }77 78 } else {79 80 if(dependenciesGraph.has(installPackage)) {81 const packageInfo = dependenciesGraph.get(installPackage);82 packageInfo.dependencies.forEach((package) => {83 installPackagesDFS(package, true);84 });85 } 86 87 installPackages.add(installPackage);88 result += `Installing ${installPackage}`;89 result += '\n';90 91 }92 }93 };94 installPackagesDFS(installPackage);95 return result;96}97const ListCommand = () => {98 let result = '';99 installPackages.forEach((installPackage) => {100 result += `${installPackage}`;101 result += '\n';102 });103 return result;104};105const removeCommand = (packageName) => {106 let result = '';107 const visitedNodes = new Set();108 const dfsRemove = (package, check) => {109 if(!visitedNodes.has(package)) {110 visitedNodes.add(package);111 if(installPackages.has(package)) {112 const graphObj = dependenciesGraph.get(package);113 114 if(graphObj.dependentUpon.size > 0) {115 if(!check) {116 result += `${package} is still needed`;117 result += '\n';118 }119 } else {120 121 removeDependentObj(package);122 dependenciesGraph.delete(package);123 installPackages.delete(package);124 if(check) {125 // result += `${package} is no longer needed`;126 // result += '\n';127 }128 result += `Removing ${package}`;129 result += '\n';130 if(!check) {131 graphObj.dependencies.forEach((eachDependencies) => {132 dfsRemove(eachDependencies, true);133 });134 }135 136 137 }138 } else {139 result += `${package} is not installed`;140 result += '\n';141 }142 }143 };144 dfsRemove(packageName);145 return result;146}147const removeDependentObj = (packageName) => {148 const graphObj = dependenciesGraph.get(packageName);149 if(graphObj.dependencies.size > 0) {150 graphObj.dependencies.forEach((package) => {151 const currentGraphObj = dependenciesGraph.get(package);152 currentGraphObj.dependentUpon.delete(packageName);153 });154 }155}156const functionData = (input) => {157 let result = '';158 const commands = splitTextIntoArr(input);159 for(let i = 1; i < commands.length; i++) {160 const currentCommands = commands[i];161 const currentOperation = currentCommands[0];162 result += `${currentCommands.join(' ')}`;163 if(currentOperation !== 'END') {164 result += '\n';165 }166 167 if(currentOperation === 'DEPEND') {168 result += dependCommand(currentCommands);169 }170 if(currentOperation == 'INSTALL') {171 result += installCommand(currentCommands);172 }173 if(currentOperation == 'LIST') {174 result += ListCommand();175 }176 if(currentOperation == 'REMOVE') {177 const packageName = currentCommands[1];178 result += removeCommand(packageName);179 } 180 }181 return result;182};183// let input = "22\n" +184// "DEPEND TELNET TCPIP NETCARD\n" +185// "DEPEND TCPIP NETCARD\n" +186// "DEPEND DNS TCPIP NETCARD\n" +187// "DEPEND BROWSER TCPIP HTML\n" +188// "INSTALL NETCARD\n" +189// "INSTALL TELNET\n" +190// "INSTALL foo\n" +191// "REMOVE NETCARD\n" +192// "INSTALL BROWSER\n" +193// "INSTALL DNS\n" +194// "LIST\n" +195// "REMOVE TELNET\n" +196// "REMOVE NETCARD\n" +197// "REMOVE DNS\n" +198// "REMOVE NETCARD\n" +199// "INSTALL NETCARD\n" +200// "REMOVE TCPIP\n" +201// "LIST\n" +202// "REMOVE BROWSER\n" +203// "REMOVE TCPIP\n" +204// "LIST\n" +205// "END"206let input = "22\n" +207"DEPEND TELNET TCPIP NETCARD\n" +208"DEPEND TCPIP NETCARD\n" +209"DEPEND NETCARD TCPIP\n" +210"DEPEND DNS TCPIP NETCARD\n" +211"DEPEND BROWSER TCPIP HTML\n" +212"INSTALL NETCARD\n" +213"INSTALL TELNET\n" +214"INSTALL foo\n" +215"REMOVE NETCARD\n" +216"INSTALL BROWSER\n" +217"INSTALL DNS\n" +218"LIST\n" +219"REMOVE TELNET\n" +220"REMOVE NETCARD\n" +221"REMOVE DNS\n" +222"REMOVE NETCARD\n" +223"INSTALL NETCARD\n" +224"REMOVE TCPIP\n" +225"REMOVE BROWSER\n" +226"REMOVE TCPIP\n" +227"LIST\n" +228"END"229const finalResult = functionData(input);...

Full Screen

Full Screen

packageTransformations.js

Source:packageTransformations.js Github

copy

Full Screen

1module.exports = {2 "NoRedInk/elm-decode-pipeline": [3 {4 action: "installPackage",5 packageName: "NoRedInk/elm-json-decode-pipeline",6 todos: [7 "Changes uses of Json.Decode.Pipeline.decode to Json.Decode.succeed"8 ]9 }10 ],11 "elm-community/elm-test": [12 { action: "installPackage", packageName: "elm-explorations/test" }13 ],14 "elm-lang/animation-frame": [15 {16 action: "installPackage",17 packageName: "elm/browser",18 todos: [19 "Change code using AnimationFrame.* to use Browser.Events.onAnimationFrame*"20 ]21 }22 ],23 "elm-lang/core": [24 {25 action: "installPackage",26 packageName: "elm/core",27 todos: [28 "Replace uses of toString with String.fromInt, String.fromFloat, or Debug.toString as appropriate"29 ]30 },31 {32 action: "match",33 condition: {34 type: "usesModule",35 modules: ["Json.Decode", "Json.Encode"]36 },37 ifMet: [{ action: "installPackage", packageName: "elm/json" }]38 },39 {40 action: "match",41 condition: {42 type: "usesModule",43 modules: ["Random"]44 },45 ifMet: [{ action: "installPackage", packageName: "elm/random" }]46 },47 {48 action: "match",49 condition: {50 type: "usesModule",51 modules: ["Time", "Date"]52 },53 ifMet: [54 {55 action: "installPackage",56 packageName: "elm/time",57 todos: [58 "Read the new documentation here: https://package.elm-lang.org/packages/elm/time/latest/",59 "Replace uses of Date and Time with Time.Posix"60 ]61 }62 ]63 },64 {65 action: "match",66 condition: {67 type: "usesModule",68 modules: ["Regex"]69 },70 ifMet: [{ action: "installPackage", packageName: "elm/regex" }]71 }72 ],73 "elm-lang/html": [74 {75 action: "installPackage",76 packageName: "elm/html",77 todos: [78 "If you used Html.program*, install elm/browser and switch to Browser.element or Browser.document",79 "If you used Html.beginnerProgram, install elm/browser and switch Browser.sandbox"80 ]81 }82 ],83 "elm-lang/http": [{ action: "installPackage", packageName: "elm/http" }],84 "elm-lang/navigation": [85 {86 action: "installPackage",87 packageName: "elm/browser",88 todos: [89 "Change code using Navigation.program* to use Browser.application",90 "Use the Browser.Key passed to your init function in any calls to Browser.Navigation.pushUrl/replaceUrl/back/forward"91 ]92 },93 {94 action: "installPackage",95 packageName: "elm/url",96 todos: ["Changes uses of Navigation.Location to Url.Url"]97 }98 ],99 "elm-lang/svg": [{ action: "installPackage", packageName: "elm/svg" }],100 "elm-lang/window": [101 {102 action: "installPackage",103 packageName: "elm/browser",104 todos: ["Change code using Window.* to use Browser.Events.onResize"]105 }106 ],107 "elm-lang/virtual-dom": [108 { action: "installPackage", packageName: "elm/virtual-dom" }109 ],110 "elm-tools/parser": [{ action: "installPackage", packageName: "elm/parser" }],111 "evancz/elm-markdown": [112 { action: "installPackage", packageName: "elm-explorations/markdown" }113 ],114 "evancz/url-parser": [115 {116 action: "installPackage",117 packageName: "elm/url",118 todos: ["Change code using UrlParser.* to use Url.Parser.*"]119 }120 ],121 "mgold/elm-random-pcg": [122 {123 action: "installPackage",124 packageName: "elm/random",125 todos: ["Change references to Random.Pcg.* to Random.*"]126 }127 ],128 "ohanhi/keyboard-extra": [129 { action: "installPackage", packageName: "ohanhi/keyboard" }130 ],131 "thebritican/elm-autocomplete": [132 { action: "installPackage", packageName: "ContaSystemer/elm-menu" }133 ],134 "elm-community/linear-algebra": [135 { action: "installPackage", packageName: "elm-explorations/linear-algebra" }136 ],137 "elm-community/webgl": [138 { action: "installPackage", packageName: "elm-explorations/webgl" }139 ],140 "elm-lang/keyboard": [141 { action: "installPackage", packageName: "elm/browser" }142 ],143 "elm-lang/dom": [{ action: "installPackage", packageName: "elm/browser" }],144 "mpizenberg/elm-mouse-events": [145 {146 action: "installPackage",147 packageName: "mpizenberg/elm-pointer-events",148 todos: [149 "Read the upgrade instructions here: https://github.com/mpizenberg/elm-pointer-events/blob/master/upgrade.md"150 ]151 }152 ],153 "mpizenberg/elm-touch-events": [154 {155 action: "installPackage",156 packageName: "mpizenberg/elm-pointer-events",157 todos: [158 "Read the upgrade instructions here: https://github.com/mpizenberg/elm-pointer-events/blob/master/upgrade.md"159 ]160 }161 ],162 "ryannhg/elm-date-format": [163 { action: "installPackage", packageName: "ryannhg/date-format" }164 ],165 "rtfeldman/hex": [166 { action: "installPackage", packageName: "rtfeldman/elm-hex" }167 ],168 "elm-lang/mouse": [{ action: "installPackage", packageName: "elm/browser" }],169 "avh4/elm-transducers": [170 {171 action: "installPackage",172 packageName: "avh4-experimental/elm-transducers"173 }174 ],175 "dillonkearns/graphqelm": [176 {177 action: "installPackage",178 packageName: "dillonkearns/elm-graphql",179 todos: ["Changes references to Graphqelm.* to Graphql.*"]180 }181 ],182 "BrianHicks/elm-benchmark": [183 { action: "installPackage", packageName: "elm-explorations/benchmark" }184 ]...

Full Screen

Full Screen

ApplicationPackageManager.js

Source:ApplicationPackageManager.js Github

copy

Full Screen

1Java.perform(function() {2 var cn = "android.app.ApplicationPackageManager";3 var appPackageManager = Java.use(cn);4 if (appPackageManager) {5 //hook setComponentEnableSetting6 appPackageManager.setComponentEnabledSetting.implementation = function() {7 send("call " + cn + "->setComponentEnabledSetting");8 return this.setComponentEnabledSetting.apply(this, arguments);9 };10 //hook installPackage11 appPackageManager.installPackage.overloads[0].implementation = function() {12 send("call " + cn + "->installPackage");13 return this.installPackage.overloads[0].apply(this, arguments);14 };15 appPackageManager.installPackage.overloads[1].implementation = function() {16 send("call " + cn + "->installPackage");17 return this.installPackage.overloads[1].apply(this, arguments);18 };19 //hook getInstalledPackages20 appPackageManager.getInstalledPackages.overloads[0].implementation = function() {21 send("call " + cn + "->getInstalledPackages");22 return this.getInstalledPackages.overloads[0].apply(this, arguments);23 };24 appPackageManager.getInstalledPackages.overloads[1].implementation = function() {25 send("call " + cn + "->getInstalledPackages");26 return this.getInstalledPackages.overloads[1].apply(this, arguments);27 };28 //hook getInstalledApplications29 appPackageManager.getInstalledApplications.implementation = function() {30 send("call " + cn + "->getInstalledApplications");31 return this.getInstalledApplications.apply(this, arguments);32 };33 //hook deletePackage34 appPackageManager.deletePackage.implementation = function() {35 send("call " + cn + "->deletePackage");36 return this.deletePackage.apply(this, arguments);37 };38 };...

Full Screen

Full Screen

installationService.js

Source:installationService.js Github

copy

Full Screen

...11 let formData = new FormData();12 formData.append("POSTFILE", file);13 sf.postfile("ParsePackage", formData, callback, errorCallback);14 }15 installPackage(file, legacyType, isPortalPackage, callback) {16 const sf = this.getServiceFramework("Extensions");17 let formData = new FormData();18 formData.append("POSTFILE", file);19 if (legacyType && isPortalPackage) {20 sf.postfile("InstallPackage?legacySkin=" + legacyType + "&isPortalPackage=" + isPortalPackage, formData, callback, util.utilities.notifyError);21 }22 else if (legacyType) {23 sf.postfile("InstallPackage?legacySkin=" + legacyType, formData, callback, util.utilities.notifyError);24 } 25 else if (isPortalPackage) {26 sf.postfile("InstallPackage?isPortalPackage=" + isPortalPackage, formData, callback, util.utilities.notifyError);27 }28 else {29 sf.postfile("InstallPackage", formData, callback, util.utilities.notifyError);...

Full Screen

Full Screen

ConfigManager.js

Source:ConfigManager.js Github

copy

Full Screen

1import PackageUtil from './PackageUtil';2/**3 * get package menu config4 *5 * @return {Object} structure : {6 * "host": "package host",7 * "id": "package id",8 * "packageId": "package id",9 * "packageName": "package name",10 * "description": "package description",11 * "icon": "icon file name",12 * "directory": "directory name",13 * "options": [14 * {15 * "id": "package option id"16 * "name": "package option name"17 * "uri": "html file path (relative direction)",18 * },19 * ...20 * ]21 * }22 */23function getSidebarMenuConfig() {24 let installPackages = PackageUtil.getInstalledPackages();25 for (let installPackage of installPackages) {26 installPackage.id = installPackage.packageFrom + "-" + installPackage.packageId;27 installPackage.options.map((option, index) => Object.assign(option, {id: installPackage.id + "-" + index}));28 }29 return installPackages;30}31export default {32 getSidebarMenuConfig...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var karma = require('karma');2var server = new karma.Server({3}, function(exitCode) {4 console.log('Karma has exited with ' + exitCode);5 process.exit(exitCode);6});7server.start();8module.exports = function(config) {9 config.set({

Full Screen

Using AI Code Generation

copy

Full Screen

1var karma = require('karma');2var server = new karma.Server({3}, function(exitCode) {4 console.log('Karma has exited with ' + exitCode);5 process.exit(exitCode);6});7server.start();

Full Screen

Using AI Code Generation

copy

Full Screen

1var KarmaServer = require('karma').Server;2var server = new KarmaServer({3}, function(exitCode) {4 console.log('Karma has exited with ' + exitCode);5 process.exit(exitCode);6});7server.start();

Full Screen

Using AI Code Generation

copy

Full Screen

1var karma = require('karma').server;2karma.start({3}, function(exitCode) {4 console.log('Karma has exited with ' + exitCode);5 process.exit(exitCode);6});

Full Screen

Using AI Code Generation

copy

Full Screen

1var karma = require('karma').server;2karma.start({3});4[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!5[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!6[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!7[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!8[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!9[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!10[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!11[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!12[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!13[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!14[1021/092733:ERROR:nacl_helper_linux.cc(308)] NaCl helper process running without a sandbox!

Full Screen

Using AI Code Generation

copy

Full Screen

1const Karma = require('karma').Server;2const karma = new Karma({}, function () { });3karma.start();4karma.installPackage('karma-jasmine');5const webpack = require('webpack');6const compiler = webpack({ entry: './src/index.js' });7compiler.installPackage('babel-loader');8const express = require('express');9const app = express();10app.installPackage('cookie-parser');11const browserify = require('browserify');12const b = browserify();13b.installPackage('babelify');14const Mocha = require('mocha');15const mocha = new Mocha();16mocha.installPackage('mocha-junit-reporter');17const grunt = require('grunt');18grunt.installPackage('grunt-contrib-watch');19const gulp = require('gulp');20gulp.installPackage('gulp-uglify');21const npm = require('npm');22npm.installPackage('npm-install-package');23const yarn = require('yarn');24yarn.installPackage('yarn-install-package');25const bower = require('bower');26bower.installPackage('bower-install-package');27const babel = require('babel');28babel.installPackage('babel-plugin-transform-es2015-arrow-functions');29const eslint = require('eslint');30eslint.installPackage('eslint-plugin-react');31const typescript = require('typescript');32typescript.installPackage('typescript-plugin-css-modules');33const prettier = require('prettier');34prettier.installPackage('prettier-plugin-package');35const flow = require('flow');36flow.installPackage('flow-plugin-foo');37const webpack = require('webpack');38const compiler = webpack({ entry: './src/index.js' });39compiler.installPackage('babel-loader');

Full Screen

Using AI Code Generation

copy

Full Screen

1karma.installPackage('chai', function (err, result) {2 if (err) {3 console.log(err);4 }5 if (result) {6 console.log(result);7 }8});9### karma.uninstallPackage(packageName, callback)10karma.uninstallPackage('chai', function (err, result) {11 if (err) {12 console.log(err);13 }14 if (result) {15 console.log(result);16 }17});18### karma.start(callback)19karma.start(function (err, result) {20 if (err) {21 console.log(err);22 }23 if (result) {24 console.log(result);25 }26});27### karma.stop(callback)28karma.stop(function (err, result) {29 if (err) {30 console.log(err);31 }32 if (result) {33 console.log(result);34 }35});36### karma.restart(callback)

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Karma automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful