Bug 1326334 - Fix more errors in devtools/shared. r=jryans

MozReview-Commit-ID: 2MOe5hEyqYo
This commit is contained in:
Tim Nguyen 2017-01-03 23:47:28 +01:00
parent 56683af3e7
commit 1f91986edf
33 changed files with 550 additions and 559 deletions

View file

@ -116,16 +116,9 @@ devtools/server/tests/browser/**
!devtools/server/tests/browser/browser_webextension_inspected_window.js
devtools/server/tests/mochitest/**
devtools/server/tests/unit/**
devtools/shared/apps/**
devtools/shared/gcli/**
!devtools/shared/gcli/templater.js
devtools/shared/heapsnapshot/**
devtools/shared/transport/**
!devtools/shared/transport/transport.js
!devtools/shared/transport/websocket-transport.js
devtools/shared/transport/tests/unit/**
devtools/shared/webconsole/test/**
devtools/shared/worker/**
!devtools/shared/worker/worker.js
# Ignore devtools pre-processed files
devtools/client/framework/toolbox-process-window.js
@ -136,7 +129,7 @@ devtools/client/preferences/**
# Ignore devtools third-party libs
devtools/shared/jsbeautify/*
devtools/shared/acorn/*
devtools/client/sourceeditor/tern/*
devtools/shared/gcli/source/*
devtools/shared/node-properties/*
devtools/shared/pretty-fast/*
devtools/shared/sourcemap/*
@ -147,6 +140,7 @@ devtools/client/shared/demangle.js
devtools/client/shared/vendor/*
devtools/client/sourceeditor/codemirror/*.js
devtools/client/sourceeditor/codemirror/**/*.js
devtools/client/sourceeditor/tern/*
devtools/client/sourceeditor/test/cm_mode_ruby.js
devtools/client/sourceeditor/test/codemirror/*
devtools/client/inspector/markup/test/lib_*

View file

@ -273,7 +273,7 @@ module.exports = {
// Disallow declaring the same variable more than once (we use let anyway).
"no-redeclare": "error",
// Disallow multiple spaces in a regular expression literal.
"no-regex-spaces": "error",
"no-regex-spaces": "off",
// Allow reserved words being used as object literal keys.
"no-reserved-keys": "off",
// Don't restrict usage of specified node modules (not a node environment).

View file

@ -6,6 +6,8 @@
Components.utils.import("resource://devtools/shared/event-emitter.js");
/* exported EXPORTED_SYMBOLS */
const EXPORTED_SYMBOLS = ["Devices"];
var addonInstalled = false;

View file

@ -37,8 +37,7 @@ function addDirToZip(writer, dir, basePath) {
if (file.isHidden() ||
file.isSpecial() ||
file.equals(writer.file))
{
file.equals(writer.file)) {
continue;
}
@ -62,12 +61,15 @@ function addDirToZip(writer, dir, basePath) {
*/
function getResultText(code) {
let regexp =
/^\[Exception... "(.*)" nsresult: "0x[0-9a-fA-F]* \((.*)\)" location: ".*" data: .*\]$/;
let ex = Cc["@mozilla.org/js/xpc/Exception;1"].
createInstance(Ci.nsIXPCException);
/^\[Exception... "(.*)" nsresult: "0x[0-9a-fA-F]* \((.*)\)" location: ".*" data: .*\]$/; // eslint-disable-line
let ex = Cc["@mozilla.org/js/xpc/Exception;1"]
.createInstance(Ci.nsIXPCException);
ex.initialize(null, code, null, null, null, null);
let [, message, name] = regexp.exec(ex.toString());
return { name: name, message: message };
return {
name,
message
};
}
function zipDirectory(zipFile, dirToArchive) {
@ -75,7 +77,7 @@ function zipDirectory(zipFile, dirToArchive) {
let writer = Cc["@mozilla.org/zipwriter;1"].createInstance(Ci.nsIZipWriter);
writer.open(zipFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
this.addDirToZip(writer, dirToArchive, "");
addDirToZip(writer, dirToArchive, "");
writer.processQueue({
onStartRequest: function onStartRequest(request, context) {},
@ -83,8 +85,7 @@ function zipDirectory(zipFile, dirToArchive) {
if (status == Cr.NS_OK) {
writer.close();
deferred.resolve(zipFile);
}
else {
} else {
let { name, message } = getResultText(status);
deferred.reject(name + ": " + message);
}
@ -97,9 +98,8 @@ function zipDirectory(zipFile, dirToArchive) {
function uploadPackage(client, webappsActor, packageFile, progressCallback) {
if (client.traits.bulk) {
return uploadPackageBulk(client, webappsActor, packageFile, progressCallback);
} else {
return uploadPackageJSON(client, webappsActor, packageFile, progressCallback);
}
return uploadPackageJSON(client, webappsActor, packageFile, progressCallback);
}
function uploadPackageJSON(client, webappsActor, packageFile, progressCallback) {
@ -125,32 +125,29 @@ function uploadPackageJSON(client, webappsActor, packageFile, progressCallback)
function openFile(actor) {
let openedFile;
OS.File.open(packageFile.path)
.then(file => {
OS.File.open(packageFile.path).then(file => {
openedFile = file;
return openedFile.stat();
})
.then(fileInfo => {
}).then(fileInfo => {
fileSize = fileInfo.size;
emitProgress();
uploadChunk(actor, openedFile);
});
}
function uploadChunk(actor, file) {
file.read(CHUNK_SIZE)
.then(function (bytes) {
file.read(CHUNK_SIZE).then(function (bytes) {
bytesRead += bytes.length;
emitProgress();
// To work around the fact that JSON.stringify translates the typed
// array to object, we are encoding the typed array here into a string
let chunk = String.fromCharCode.apply(null, bytes);
let request = {
let chunkRequest = {
to: actor,
type: "chunk",
chunk: chunk
chunk,
};
client.request(request, (res) => {
client.request(chunkRequest, (res) => {
if (bytes.length == CHUNK_SIZE) {
uploadChunk(actor, file);
} else {
@ -162,11 +159,11 @@ function uploadPackageJSON(client, webappsActor, packageFile, progressCallback)
});
}
function endsUpload(actor) {
let request = {
let doneRequest = {
to: actor,
type: "done"
};
client.request(request, (res) => {
client.request(doneRequest, (res) => {
deferred.resolve(actor);
});
}
@ -190,13 +187,13 @@ function uploadPackageBulk(client, webappsActor, packageFile, progressCallback)
let fileSize = packageFile.fileSize;
console.log("File size: " + fileSize);
let request = client.startBulkRequest({
let streamRequest = client.startBulkRequest({
actor: actor,
type: "stream",
length: fileSize
});
request.on("bulk-send-ready", ({copyFrom}) => {
streamRequest.on("bulk-send-ready", ({copyFrom}) => {
NetUtil.asyncFetch({
uri: NetUtil.newURI(packageFile),
loadUsingSystemPrincipal: true
@ -245,8 +242,7 @@ function installPackaged(client, webappsActor, packagePath, appId, progressCallb
packagePromise = promise.resolve(file);
}
packagePromise.then((zipFile) => {
uploadPackage(client, webappsActor, zipFile, progressCallback)
.then((fileActor) => {
uploadPackage(client, webappsActor, zipFile, progressCallback).then((fileActor) => {
let request = {
to: webappsActor,
type: "install",
@ -260,15 +256,17 @@ function installPackaged(client, webappsActor, packagePath, appId, progressCallb
if (res.error) {
deferred.reject(res);
}
if ("error" in res)
if ("error" in res) {
deferred.reject({error: res.error, message: res.message});
else
} else {
deferred.resolve({appId: res.appId});
}
});
// Ensure deleting the temporary package file, but only if that a temporary
// package created when we pass a directory as `packagePath`
if (zipFile != file)
if (zipFile != file) {
zipFile.remove(false);
}
// In case of success or error, ensure deleting the temporary package file
// also created on the device, but only once install request is done
deferred.promise.then(
@ -293,10 +291,11 @@ function installHosted(client, webappsActor, appId, metadata, manifest) {
if (res.error) {
deferred.reject(res);
}
if ("error" in res)
if ("error" in res) {
deferred.reject({error: res.error, message: res.message});
else
} else {
deferred.resolve({appId: res.appId});
}
});
return deferred.promise;
}
@ -307,8 +306,9 @@ function getTargetForApp(client, webappsActor, manifestURL) {
// of the same app in order to show only one toolbox per app and
// avoid re-creating lot of objects twice.
let existingTarget = appTargets.get(manifestURL);
if (existingTarget)
if (existingTarget) {
return promise.resolve(existingTarget);
}
let deferred = defer();
let request = {
@ -343,10 +343,9 @@ function getTargetForApp(client, webappsActor, manifestURL) {
exports.getTargetForApp = getTargetForApp;
function reloadApp(client, webappsActor, manifestURL) {
return getTargetForApp(client,
webappsActor,
manifestURL).
then((target) => {
return getTargetForApp(
client, webappsActor, manifestURL
).then((target) => {
// Request the ContentActor to reload the app
let request = {
to: target.form.actor,
@ -354,7 +353,7 @@ function reloadApp(client, webappsActor, manifestURL) {
options: {
force: true
},
manifestURL: manifestURL
manifestURL,
};
return client.request(request);
}, () => {
@ -423,9 +422,9 @@ App.prototype = {
type: "getAppActor",
manifestURL: this.manifest.manifestURL
};
return this.client.request(request)
.then(res => {
return this._form = res.actor;
return this.client.request(request).then(res => {
this._form = res.actor;
return this._form;
});
},
@ -433,14 +432,15 @@ App.prototype = {
if (this._target) {
return promise.resolve(this._target);
}
return this.getForm().
then((form) => getTarget(this.client, form)).
then((target) => {
return this.getForm().then(
(form) => getTarget(this.client, form)
).then((target) => {
target.on("close", () => {
delete this._form;
delete this._target;
});
return this._target = target;
this._target = target;
return this._target;
});
},
@ -487,7 +487,6 @@ App.prototype = {
}
};
/**
* `AppActorFront` is a client for the webapps actor.
*/
@ -537,15 +536,14 @@ AppActorFront.prototype = {
let app = this._apps ? this._apps.get(manifestURL) : null;
if (app) {
return promise.resolve(app);
} else {
}
let request = {
to: this.actor,
type: "getApp",
manifestURL: manifestURL
manifestURL,
};
return this.client.request(request)
.then(res => {
let app = new App(this.client, this.actor, res.app);
return this.client.request(request).then(res => {
app = new App(this.client, this.actor, res.app);
if (this._apps) {
this._apps.set(manifestURL, app);
}
@ -553,7 +551,6 @@ AppActorFront.prototype = {
}, e => {
console.error("Unable to retrieve app", manifestURL, e);
});
}
},
/**
@ -583,47 +580,42 @@ AppActorFront.prototype = {
to: this.actor,
type: "getAll"
};
return this._loadingPromise = this.client.request(request)
.then(res => {
this._loadingPromise = this.client.request(request).then(res => {
delete this._loadingPromise;
this._apps = new Map();
for (let a of res.apps) {
let app = new App(this.client, this.actor, a);
this._apps.set(a.manifestURL, app);
}
})
.then(() => {
}).then(() => {
// Then retrieve all running apps in order to flag them as running
let request = {
let listRequest = {
to: this.actor,
type: "listRunningApps"
};
return this.client.request(request)
.then(res => res.apps);
})
.then(apps => {
return this.client.request(listRequest).then(res => res.apps);
}).then(apps => {
let promises = apps.map(manifestURL => {
// _getApp creates `App` instance and register it to AppActorFront
return this._getApp(manifestURL)
.then(app => {
return this._getApp(manifestURL).then(app => {
app.running = true;
// Fake appOpen event for all already opened
this._notifyListeners("appOpen", app);
});
});
return promise.all(promises);
})
.then(() => {
}).then(() => {
// Finally ask to receive all app events
return this._listenAppEvents(listener);
});
return this._loadingPromise;
},
fetchIcons: function () {
// On demand, retrieve apps icons in order to be able
// to synchronously retrieve it on `App` objects
let promises = [];
for (let [manifestURL, app] of this._apps) {
for (let [, app] of this._apps) {
promises.push(app.getIcon());
}
@ -708,8 +700,7 @@ AppActorFront.prototype = {
to: this.actor,
type: "listRunningApps"
};
this.client.request(request)
.then(res => {
this.client.request(request).then(res => {
if (res.apps.indexOf(manifestURL) !== -1) {
app.running = true;
this._notifyListeners("appInstall", app);
@ -796,10 +787,8 @@ AppActorFront.prototype = {
}
}
};
this._listenAppEvents(listener)
// Execute the request
.then(request)
.then(response => {
this._listenAppEvents(listener).then(request).then(response => {
finalAppId = response.appId;
manifestURL = response.manifestURL;
@ -811,7 +800,6 @@ AppActorFront.prototype = {
}, deferred.reject);
return deferred.promise;
},
/*
@ -826,9 +814,9 @@ AppActorFront.prototype = {
let manifestURL = metadata.manifestURL ||
metadata.origin + "/manifest.webapp";
let request = () => {
return installHosted(this.client, this.actor, appId, metadata,
manifest)
.then(response => ({
return installHosted(
this.client, this.actor, appId, metadata, manifest
).then(response => ({
appId: response.appId,
manifestURL: manifestURL
}));

View file

@ -15,8 +15,7 @@ function getAddonManager() {
AddonManager: require("resource://gre/modules/AddonManager.jsm").AddonManager,
addonManagerActive: true
};
}
catch (ex) {
} catch (ex) {
// Fake up an AddonManager just enough to let the file load
return {
AddonManager: {
@ -28,15 +27,9 @@ function getAddonManager() {
}
}
const { Cc, Ci, Cu } = require("chrome");
const { AddonManager, addonManagerActive } = getAddonManager();
const l10n = require("gcli/l10n");
const BRAND_SHORT_NAME = Cc["@mozilla.org/intl/stringbundle;1"]
.getService(Ci.nsIStringBundleService)
.createBundle("chrome://branding/locale/brand.properties")
.GetStringFromName("brandShortName");
/**
* Takes a function that uses a callback as its last parameter, and returns a
* new function that returns a promise instead.
@ -50,7 +43,7 @@ const promiseify = function(scope, functionWithLastParamCallback) {
});
functionWithLastParamCallback.apply(scope, args);
});
}
};
};
// Convert callback based functions to promise based ones
@ -82,8 +75,12 @@ var items = [
constructor: function () {
// Tell GCLI to clear the cache of addons when one is added or removed
let listener = {
onInstalled: addon => { this.clearCache(); },
onUninstalled: addon => { this.clearCache(); },
onInstalled: addon => {
this.clearCache();
},
onUninstalled: addon => {
this.clearCache();
},
};
AddonManager.addAddonListener(listener);
},

View file

@ -49,8 +49,7 @@ exports.items = [
let name = "<anonymous>";
if (frame.callee.name) {
name = frame.callee.name;
}
else {
} else {
let desc = frame.callee.getOwnPropertyDescriptor("displayName");
if (desc && desc.value && typeof desc.value == "string") {
name = desc.value;
@ -136,8 +135,7 @@ exports.items = [
}
} else {
let chromeWin = context.environment.chromeDocument.defaultView;
let sandbox = new Cu.Sandbox(chromeWin,
{
let sandbox = new Cu.Sandbox(chromeWin, {
sandboxPrototype: chromeWin,
wantXrays: false,
sandboxName: "gcli-cmd-calllog-chrome"
@ -178,8 +176,9 @@ exports.items = [
},
valueToString: function (value) {
if (typeof value !== "object" || value === null)
if (typeof value !== "object" || value === null) {
return uneval(value);
}
return "[object " + value.class + "]";
},

View file

@ -5,14 +5,15 @@
"use strict";
const { Cc, Ci, Cu } = require("chrome");
const { OS, TextDecoder } = Cu.import("resource://gre/modules/osfile.jsm", {});
const { Task } = require("devtools/shared/task");
const { OS } = Cu.import("resource://gre/modules/osfile.jsm", {});
const { TextEncoder, TextDecoder } = Cu.import('resource://gre/modules/commonjs/toolkit/loader.js', {});
const gcli = require("gcli/index");
const l10n = require("gcli/l10n");
loader.lazyGetter(this, "prefBranch", function () {
let prefService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService);
let prefService = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService);
return prefService.getBranch(null).QueryInterface(Ci.nsIPrefBranch2);
});
@ -66,30 +67,32 @@ function loadItemsFromMozDir() {
// We need to return (a promise of) an array of items from the *.mozcmd
// files in dirName (which we can assume to be a valid directory now)
return statPromise.then(() => {
return Task.async(function* () {
yield statPromise;
let itemPromises = [];
let iterator = new OS.File.DirectoryIterator(dirName);
let iterPromise = iterator.forEach(entry => {
try {
yield iterator.forEach(entry => {
if (entry.name.match(/.*\.mozcmd$/) && !entry.isDir) {
itemPromises.push(loadCommandFile(entry));
}
});
return iterPromise.then(() => {
iterator.close();
return Promise.all(itemPromises).then((itemsArray) => {
let itemsArray = yield Promise.all(itemPromises);
return itemsArray.reduce((prev, curr) => {
return prev.concat(curr);
}, []);
});
}, reason => { iterator.close(); throw reason; });
} catch (e) {
iterator.close();
throw e;
}
});
}
exports.mozDirLoader = function (name) {
return loadItemsFromMozDir().then(items => {
return { items: items };
return { items };
});
};
@ -100,10 +103,10 @@ exports.mozDirLoader = function(name) {
*/
function loadCommandFile(entry) {
let readPromise = OS.File.read(entry.path);
return readPromise = readPromise.then(array => {
readPromise = readPromise.then(array => {
let decoder = new TextDecoder();
let source = decoder.decode(array);
var principal = Cc["@mozilla.org/systemprincipal;1"]
let principal = Cc["@mozilla.org/systemprincipal;1"]
.createInstance(Ci.nsIPrincipal);
let sandbox = new Cu.Sandbox(principal, {
@ -113,11 +116,12 @@ function loadCommandFile(entry) {
if (!Array.isArray(data)) {
console.error("Command file '" + entry.name + "' does not have top level array.");
return;
return null;
}
return data;
});
return readPromise;
}
exports.items = [
@ -164,7 +168,8 @@ exports.items = [
],
returnType: "string",
get hidden() {
return true; // !prefBranch.prefHasUserValue(PREF_DIR);
// !prefBranch.prefHasUserValue(PREF_DIR);
return true;
},
exec: function (args, context) {
supportsString.data = args.directory;

View file

@ -52,9 +52,9 @@ function translateExpires(expires) {
return l10n.lookup("cookieListOutSession");
}
let expires_msec = expires * 1000;
let expiresMsec = expires * 1000;
return (new Date(expires_msec)).toLocaleString();
return (new Date(expiresMsec)).toLocaleString();
}
/**
@ -94,9 +94,8 @@ exports.items = [
let host = new URL(context.environment.target.url).host;
let contentWindow = context.environment.window;
host = sanitizeHost(host);
let enm = cookieMgr.getCookiesFromHost(host, contentWindow.document.
nodePrincipal.
originAttributes);
let { originAttributes } = contentWindow.document.nodePrincipal;
let enm = cookieMgr.getCookiesFromHost(host, originAttributes);
let cookies = [];
while (enm.hasMoreElements()) {
@ -139,9 +138,8 @@ exports.items = [
let host = new URL(context.environment.target.url).host;
let contentWindow = context.environment.window;
host = sanitizeHost(host);
let enm = cookieMgr.getCookiesFromHost(host, contentWindow.document.
nodePrincipal.
originAttributes);
let { originAttributes } = contentWindow.document.nodePrincipal;
let enm = cookieMgr.getCookiesFromHost(host, originAttributes);
while (enm.hasMoreElements()) {
let cookie = enm.getNext().QueryInterface(Ci.nsICookie);
@ -292,9 +290,7 @@ exports.items = [
args.httpOnly,
args.session,
time,
contentWindow.document.
nodePrincipal.
originAttributes);
contentWindow.document.nodePrincipal.originAttributes);
}
}
];

View file

@ -4,8 +4,6 @@
"use strict";
const { Cc, Ci } = require("chrome");
const domtemplate = require("gcli/util/domtemplate");
const csscoverage = require("devtools/shared/fronts/csscoverage");
const l10n = csscoverage.l10n;
@ -92,7 +90,9 @@ exports.items = [
},
onChange: function (target, handler) {
csscoverage.getUsage(target).then(usage => {
this.handler = ev => { handler("state-change", ev); };
this.handler = ev => {
handler("state-change", ev);
};
usage.on("state-change", this.handler);
});
},
@ -185,7 +185,8 @@ exports.items = [
// Create a new chart.
let container = host.querySelector(".csscoverage-report-chart");
let chart = Chart.PieTable(panel._panelDoc, {
diameter: 200, // px
// px
diameter: 200,
title: "CSS Usage",
data: [
{ size: data.summary.preload, label: "Used Preload" },

View file

@ -4,25 +4,24 @@
"use strict";
const { Cc, Ci, Cu, CC } = require("chrome");
const { Cc, Ci, CC } = require("chrome");
const Services = require("Services");
const l10n = require("gcli/l10n");
const dirService = Cc["@mozilla.org/file/directory_service;1"]
.getService(Ci.nsIProperties);
function showFolder(aPath) {
let nsLocalFile = CC("@mozilla.org/file/local;1", "nsILocalFile",
function showFolder(path) {
let NSLocalFile = CC("@mozilla.org/file/local;1", "nsILocalFile",
"initWithPath");
try {
let file = new nsLocalFile(aPath);
let file = new NSLocalFile(path);
if (file.exists()) {
file.reveal();
return l10n.lookupFormat("folderOpenDirResult", [aPath]);
} else {
return l10n.lookup("folderInvalidPath");
return l10n.lookupFormat("folderOpenDirResult", [path]);
}
return l10n.lookup("folderInvalidPath");
} catch (e) {
return l10n.lookup("folderInvalidPath");
}

View file

@ -4,7 +4,7 @@
"use strict";
const { Cc, Ci, Cu } = require("chrome");
const { Cc } = require("chrome");
const l10n = require("gcli/l10n");
const XMLHttpRequest = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"];
@ -92,6 +92,7 @@ exports.items = [
}
],
exec: function (args, context) {
/* eslint-disable camelcase */
let opts = {
indent_size: args.indentSize,
indent_char: args.indentChar,
@ -103,7 +104,7 @@ exports.items = [
space_before_conditional: !args.noSpaceBeforeConditional,
unescape_strings: args.unescapeStrings
};
/* eslint-enable camelcase */
let xhr = new XMLHttpRequest();
let deferred = context.defer();
@ -120,8 +121,8 @@ exports.items = [
deferred.reject("Unable to load page to beautify: " + args.url + " " +
xhr.status + " " + xhr.statusText);
}
};
}
};
try {
xhr.open("GET", args.url, true);
xhr.send(null);

View file

@ -69,7 +69,7 @@ exports.items = [
},
],
exec: function (args, context) {
var listener = debuggerServer.createListener();
let listener = debuggerServer.createListener();
if (!listener) {
throw new Error(l10n.lookup("listenDisabledOutput"));
}

View file

@ -99,8 +99,8 @@ exports.items = [
// window is refreshed or closed with the measuring tool shown.
events.once(highlighter, "destroy", () => {
if (highlighters.has(document)) {
let { environment } = highlighters.get(document);
environment.destroy();
let { environment: toDestroy } = highlighters.get(document);
toDestroy.destroy();
highlighters.delete(document);
}
});

View file

@ -4,7 +4,7 @@
"use strict";
const { Cc, Ci, Cu } = require("chrome");
const { Cc, Ci } = require("chrome");
const l10n = require("gcli/l10n");
exports.items = [
@ -37,7 +37,7 @@ exports.items = [
name: "selector",
type: "string",
description: l10n.lookup("pagemodReplaceSelectorDesc"),
defaultValue: "*:not(script):not(style):not(embed):not(object):not(frame):not(iframe):not(frameset)",
defaultValue: "*:not(script):not(style):not(embed):not(object):not(frame):not(iframe):not(frameset)", // eslint-disable-line
},
{
name: "root",
@ -63,8 +63,8 @@ exports.items = [
},
],
// Make a given string safe to use in a regular expression.
escapeRegex: function(aString) {
return aString.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
escapeRegex: function (string) {
return string.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
},
exec: function (args, context) {
let searchTextNodes = !args.attrOnly;
@ -221,7 +221,7 @@ exports.items = [
continue;
}
var attrs = Array.prototype.slice.call(element.attributes);
let attrs = Array.prototype.slice.call(element.attributes);
for (let y = 0; y < attrs.length; y++) {
let attr = attrs[y];
if (attributeRegex.test(attr.name)) {
@ -265,12 +265,12 @@ exports.items = [
let clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"]
.getService(Ci.nsIClipboardHelper);
clipboard.copyString(url);
return '';
return "";
}
let url = "data:text/plain;charset=utf8," + encodeURIComponent(html);
context.environment.window.open(url);
return '';
return "";
}
}
];

View file

@ -4,7 +4,7 @@
"use strict";
const { Cc, Ci, Cu } = require("chrome");
const { Cc, Ci } = require("chrome");
const l10n = require("gcli/l10n");
const Services = require("Services");

View file

@ -97,8 +97,8 @@ exports.items = [
// window is refreshed or closed with the rulers shown.
events.once(highlighter, "destroy", () => {
if (highlighters.has(document)) {
let { environment } = highlighters.get(document);
environment.destroy();
let { environment: toDestroy } = highlighters.get(document);
toDestroy.destroy();
highlighters.delete(document);
}
});

View file

@ -9,7 +9,6 @@ const l10n = require("gcli/l10n");
const Services = require("Services");
const { NetUtil } = require("resource://gre/modules/NetUtil.jsm");
const { getRect } = require("devtools/shared/layout/utils");
const promise = require("promise");
const defer = require("devtools/shared/defer");
const { Task } = require("devtools/shared/task");
@ -19,11 +18,6 @@ loader.lazyImporter(this, "FileUtils", "resource://gre/modules/FileUtils.jsm");
loader.lazyImporter(this, "PrivateBrowsingUtils",
"resource://gre/modules/PrivateBrowsingUtils.jsm");
const BRAND_SHORT_NAME = Cc["@mozilla.org/intl/stringbundle;1"]
.getService(Ci.nsIStringBundleService)
.createBundle("chrome://branding/locale/brand.properties")
.GetStringFromName("brandShortName");
// String used as an indication to generate default file name in the following
// format: "Screen Shot yyyy-mm-dd at HH.MM.SS.png"
const FILENAME_DEFAULT_VALUE = " ";
@ -142,7 +136,8 @@ exports.items = [
// Add the thumbnail image
if (imageSummary.data != null) {
const image = context.document.createElement("div");
const previewHeight = parseInt(256 * imageSummary.height / imageSummary.width);
const previewHeight = parseInt(256 * imageSummary.height / imageSummary.width,
10);
const style = "" +
"width: 256px;" +
"height: " + previewHeight + "px;" +
@ -240,10 +235,8 @@ function captureScreenshot(args, document) {
}, args.delay * 1000);
});
}
else {
return createScreenshotData(document, args);
}
}
/**
* There are several possible destinations for the screenshot, SKIP is used
@ -287,11 +280,9 @@ function createScreenshotData(document, args) {
width = window.innerWidth + window.scrollMaxX - window.scrollMinX;
height = window.innerHeight + window.scrollMaxY - window.scrollMinY;
filename = filename.replace(".png", "-fullpage.png");
}
else if (args.selector) {
} else if (args.selector) {
({ top, left, width, height } = getRect(window, args.selector, window));
}
else {
} else {
left = window.scrollX;
top = window.scrollY;
width = window.innerWidth;
@ -399,8 +390,7 @@ function saveToClipboard(context, reply) {
clip.setData(trans, null, Ci.nsIClipboard.kGlobalClipboard);
reply.destinations.push(l10n.lookup("screenshotCopied"));
}
catch (ex) {
} catch (ex) {
console.error(ex);
reply.destinations.push(l10n.lookup("screenshotErrorCopying"));
}
@ -422,7 +412,8 @@ function uploadToImgur(reply) {
fd.append("title", reply.filename);
const postURL = Services.prefs.getCharPref("devtools.gcli.imgurUploadURL");
const clientID = "Client-ID " + Services.prefs.getCharPref("devtools.gcli.imgurClientID");
const clientID = "Client-ID " +
Services.prefs.getCharPref("devtools.gcli.imgurClientID");
xhr.open("POST", postURL);
xhr.setRequestHeader("Authorization", clientID);

View file

@ -13,17 +13,15 @@
"use strict";
const { Cc, Ci, Cu, CC } = require("chrome");
const { Ci } = require("chrome");
const l10n = require("gcli/l10n");
const CSP = Cc["@mozilla.org/cspcontext;1"].getService(Ci.nsIContentSecurityPolicy);
const GOOD_IMG_SRC = "chrome://browser/content/gcli_sec_good.svg";
const MOD_IMG_SRC = "chrome://browser/content/gcli_sec_moderate.svg";
const BAD_IMG_SRC = "chrome://browser/content/gcli_sec_bad.svg";
// special handling within policy
const POLICY_REPORT_ONLY = "report-only"
const POLICY_REPORT_ONLY = "report-only";
// special handling of directives
const DIR_UPGRADE_INSECURE = "upgrade-insecure-requests";
@ -42,7 +40,11 @@ const CONTENT_SECURITY_POLICY_REPORT_ONLY_MSG = l10n.lookup("securityCSPROHeader
const NEXT_URI_HEADER = l10n.lookup("securityReferrerNextURI");
const CALCULATED_REFERRER_HEADER = l10n.lookup("securityReferrerCalculatedReferrer");
/* The official names from the W3C Referrer Policy Draft http://www.w3.org/TR/referrer-policy/ */
const REFERRER_POLICY_NAMES = [ "None When Downgrade (default)", "None", "Origin Only", "Origin When Cross-Origin", "Unsafe URL" ];
const REFERRER_POLICY_NAMES = [
"None When Downgrade (default)",
"None", "Origin Only",
"Origin When Cross-Origin", "Unsafe URL"
];
exports.items = [
{
@ -60,23 +62,22 @@ exports.items = [
manual: l10n.lookup("securityCSPManual"),
returnType: "securityCSPInfo",
exec: function (args, context) {
let cspJSON = context.environment.document.nodePrincipal.cspJSON;
let cspOBJ = JSON.parse(cspJSON);
var cspJSON = context.environment.document.nodePrincipal.cspJSON;
var cspOBJ = JSON.parse(cspJSON);
let outPolicies = [];
var outPolicies = [];
var policies = cspOBJ["csp-policies"];
let policies = cspOBJ["csp-policies"];
// loop over all the different policies
for (var csp in policies) {
var curPolicy = policies[csp];
for (let csp in policies) {
let curPolicy = policies[csp];
// loop over all the directive-values within that policy
var outDirectives = [];
var outHeader = CONTENT_SECURITY_POLICY_MSG;
for (var dir in curPolicy) {
var curDir = curPolicy[dir];
let outDirectives = [];
let outHeader = CONTENT_SECURITY_POLICY_MSG;
for (let dir in curPolicy) {
let curDir = curPolicy[dir];
// when iterating properties within the obj we might also
// encounter the 'report-only' flag, which is not a csp directive.
@ -88,7 +89,7 @@ exports.items = [
}
// loop over all the directive-sources within that directive
var outSrcs = [];
let outSrcs = [];
// special case handling for the directives
// upgrade-insecure-requests and block-all-mixed-content
@ -97,17 +98,19 @@ exports.items = [
dir === DIR_BLOCK_ALL_MIXED_CONTENT) {
outSrcs.push({
icon: GOOD_IMG_SRC,
src: "", // no src
desc: "" // no description
// no src
src: "",
// no description
desc: ""
});
}
for (var src in curDir) {
var curSrc = curDir[src];
for (let src in curDir) {
let curSrc = curDir[src];
// the default icon and descritpion of the directive-src
var outIcon = GOOD_IMG_SRC;
var outDesc = "";
let outIcon = GOOD_IMG_SRC;
let outDesc = "";
if (curSrc.indexOf("*") > -1) {
outIcon = MOD_IMG_SRC;
@ -143,7 +146,7 @@ exports.items = [
from: "securityCSPInfo",
to: "view",
exec: function (cspInfo, context) {
var url = context.environment.target.url;
const url = context.environment.target.url;
if (cspInfo.length == 0) {
return context.createView({
@ -156,6 +159,7 @@ exports.items = [
"</table>"});
}
/* eslint-disable max-len */
return context.createView({
html:
"<table class='gcli-csp-detail' cellspacing='10' valign='top'>" +
@ -185,6 +189,7 @@ exports.items = [
cspinfo: cspInfo,
}
});
/* eslint-enable max-len */
}
},
{
@ -196,16 +201,16 @@ exports.items = [
manual: l10n.lookup("securityReferrerPolicyManual"),
returnType: "securityReferrerPolicyInfo",
exec: function (args, context) {
var doc = context.environment.document;
let doc = context.environment.document;
var referrerPolicy = doc.referrerPolicy;
let { referrerPolicy } = doc;
var pageURI = doc.documentURIObject;
var sameDomainReferrer = "";
var otherDomainReferrer = "";
var downgradeReferrer = "";
var otherDowngradeReferrer = "";
var origin = pageURI.prePath;
let pageURI = doc.documentURIObject;
let sameDomainReferrer = "";
let otherDomainReferrer = "";
let downgradeReferrer = "";
let otherDowngradeReferrer = "";
let origin = pageURI.prePath;
switch (referrerPolicy) {
case Ci.nsIHttpChannel.REFERRER_POLICY_NO_REFERRER:
@ -255,28 +260,28 @@ exports.items = [
break;
}
var sameDomainUri = origin + "/*";
let sameDomainUri = origin + "/*";
var referrerUrls = [
let referrerUrls = [
// add the referrer uri 'referrer' we would send when visiting 'uri'
{
uri: pageURI.scheme+'://example.com/',
uri: pageURI.scheme + "://example.com/",
referrer: otherDomainReferrer,
description: l10n.lookup('securityReferrerPolicyOtherDomain')},
description: l10n.lookup("securityReferrerPolicyOtherDomain")},
{
uri: sameDomainUri,
referrer: sameDomainReferrer,
description: l10n.lookup('securityReferrerPolicySameDomain')}
description: l10n.lookup("securityReferrerPolicySameDomain")}
];
if (pageURI.schemeIs('https')) {
if (pageURI.schemeIs("https")) {
// add the referrer we would send on downgrading http->https
if (sameDomainReferrer != downgradeReferrer) {
referrerUrls.push({
uri: "http://" + pageURI.hostPort + "/*",
referrer: downgradeReferrer,
description:
l10n.lookup('securityReferrerPolicySameDomainDowngrade')
l10n.lookup("securityReferrerPolicySameDomainDowngrade")
});
}
if (otherDomainReferrer != otherDowngradeReferrer) {
@ -284,7 +289,7 @@ exports.items = [
uri: "http://example.com/",
referrer: otherDowngradeReferrer,
description:
l10n.lookup('securityReferrerPolicyOtherDomainDowngrade')
l10n.lookup("securityReferrerPolicyOtherDomainDowngrade")
});
}
}
@ -294,7 +299,7 @@ exports.items = [
[pageURI.spec]),
policyName: REFERRER_POLICY_NAMES[referrerPolicy],
urls: referrerUrls
}
};
}
},
{

View file

@ -24,12 +24,11 @@
* Called to clean up at the end of use
*/
const { Cc, Ci, Cu } = require("chrome");
const { Cc, Ci } = require("chrome");
const DevToolsUtils = require("devtools/shared/DevToolsUtils");
const { dumpn, dumpv } = DevToolsUtils;
const flags = require("devtools/shared/flags");
const StreamUtils = require("devtools/shared/transport/stream-utils");
const promise = require("promise");
const defer = require("devtools/shared/defer");
DevToolsUtils.defineLazyGetter(this, "unicodeConverter", () => {
@ -136,7 +135,9 @@ Object.defineProperty(JSONPacket.prototype, "object", {
/**
* Gets the object (not the serialized string) being read or written.
*/
get: function () { return this._object; },
get: function () {
return this._object;
},
/**
* Sets the object to be sent when write() is called.
@ -200,7 +201,9 @@ JSONPacket.prototype.write = function (stream) {
};
Object.defineProperty(JSONPacket.prototype, "done", {
get: function () { return this._done; }
get: function () {
return this._done;
}
});
JSONPacket.prototype.toString = function () {
@ -369,10 +372,11 @@ Object.defineProperty(BulkPacket.prototype, "header", {
});
Object.defineProperty(BulkPacket.prototype, "done", {
get: function () { return this._done; },
get: function () {
return this._done;
},
});
BulkPacket.prototype.toString = function () {
return "Bulk: " + JSON.stringify(this.header, null, 2);
};
@ -408,7 +412,9 @@ RawPacket.prototype.write = function (stream) {
};
Object.defineProperty(RawPacket.prototype, "done", {
get: function () { return this._done; }
get: function () {
return this._done;
}
});
exports.RawPacket = RawPacket;

View file

@ -4,12 +4,11 @@
"use strict";
const { Ci, Cc, Cu, Cr, CC } = require("chrome");
const { Ci, Cc, Cr, CC } = require("chrome");
const Services = require("Services");
const DevToolsUtils = require("devtools/shared/DevToolsUtils");
const { dumpv } = DevToolsUtils;
const EventEmitter = require("devtools/shared/event-emitter");
const promise = require("promise");
const defer = require("devtools/shared/defer");
DevToolsUtils.defineLazyGetter(this, "IOUtil", () => {
@ -70,8 +69,8 @@ function StreamCopier(input, output, length) {
if (IOUtil.outputStreamIsBuffered(output)) {
this.output = output;
} else {
this.output = Cc["@mozilla.org/network/buffered-output-stream;1"].
createInstance(Ci.nsIBufferedOutputStream);
this.output = Cc["@mozilla.org/network/buffered-output-stream;1"]
.createInstance(Ci.nsIBufferedOutputStream);
this.output.init(output, BUFFER_SIZE);
}
this._length = length;
@ -124,9 +123,8 @@ StreamCopier.prototype = {
this._debug("Waiting for output stream");
this.baseAsyncOutput.asyncWait(this, 0, 0, Services.tm.currentThread);
return;
} else {
throw e;
}
throw e;
}
this._amountLeft -= bytesCopied;
@ -162,9 +160,8 @@ StreamCopier.prototype = {
this._debug("Waiting for output stream");
this.baseAsyncOutput.asyncWait(this, 0, 0, Services.tm.currentThread);
return;
} else {
throw e;
}
throw e;
}
this._deferred.resolve();
},

View file

@ -1,9 +1,12 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function (root, factory) {
/* eslint-env amd */
"use strict";
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(factory);
} else if (typeof exports === "object") {
@ -12,8 +15,6 @@
root.workerHelper = factory();
}
}(this, function () {
"use strict";
/**
* This file is to only be included by ChromeWorkers. This exposes
* a `createTask` function to workers to register tasks for communication
@ -81,23 +82,20 @@
}
try {
let results;
handleResponse(taskFn(data));
} catch (e) {
handleError(e);
} catch (ex) {
handleError(ex);
}
function handleResponse(response) {
// If a promise
if (response && typeof response.then === "function") {
response.then(val => self.postMessage({ id, response: val }), handleError);
}
} else if (response instanceof Error) {
// If an error object
else if (response instanceof Error) {
handleError(response);
}
} else {
// If anything else
else {
self.postMessage({ id, response });
}
}
@ -106,21 +104,23 @@
try {
// First, try and structured clone the error across directly.
self.postMessage({ id, error });
} catch (_) {
} catch (x) {
// We could not clone whatever error value was given. Do our best to
// stringify it.
let errorString = `Error while performing task "${task}": `;
try {
errorString += error.toString();
} catch (_) {
} catch (ex) {
errorString += "<could not stringify error>";
}
if ("stack" in error) {
try {
errorString += "\n" + error.stack;
} catch (_) { }
} catch (err) {
// Do nothing
}
}
self.postMessage({ id, error: errorString });
@ -130,4 +130,4 @@
}
return { createTask: createTask };
}.bind(this)));
}));

View file

@ -4,6 +4,8 @@
"use strict";
/* global worker */
// A CommonJS module loader that is designed to run inside a worker debugger.
// We can't simply use the SDK module loader, because it relies heavily on
// Components, which isn't available in workers.
@ -60,7 +62,7 @@ function normalizeId(id) {
// An id consists of an optional root and a path. A root consists of either
// a scheme name followed by 2 or 3 slashes, or a single slash. Slashes in the
// root are not used as separators, so only normalize the path.
let [_, root, path] = id.match(/^(\w+:\/\/\/?|\/)?(.*)/);
let [, root, path] = id.match(/^(\w+:\/\/\/?|\/)?(.*)/);
let stack = [];
path.split("/").forEach(function (component) {
@ -75,13 +77,11 @@ function normalizeId(id) {
} else {
stack.push("..");
}
} else {
if (stack[stack.length - 1] == "..") {
} else if (stack[stack.length - 1] == "..") {
stack.push("..");
} else {
stack.pop();
}
}
break;
default:
stack.push(component);
@ -336,7 +336,8 @@ var loader = {
Object.defineProperty(object, name, {
get: function () {
delete object[name];
return object[name] = lambda.apply(object);
object[name] = lambda.apply(object);
return object[name];
},
configurable: true,
enumerable: true
@ -361,6 +362,7 @@ var loader = {
// object to implement them. On worker threads, we use the APIs provided by
// the worker debugger.
/* eslint-disable no-shadow */
var {
Debugger,
URL,
@ -372,13 +374,12 @@ var {
setImmediate,
xpcInspector,
} = (function () {
if (typeof Components === "object") { // Main thread
// Main thread
if (typeof Components === "object") {
let {
Constructor: CC,
classes: Cc,
manager: Cm,
interfaces: Ci,
results: Cr,
utils: Cu
} = Components;
@ -406,8 +407,8 @@ var {
let rpc = undefined;
let subScriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].
getService(Ci.mozIJSSubScriptLoader);
let subScriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader);
let loadSubScript = function (url, sandbox) {
subScriptLoader.loadSubScript(url, sandbox, "UTF-8");
@ -421,8 +422,8 @@ var {
Timer.setTimeout(callback, 0);
};
let xpcInspector = Cc["@mozilla.org/jsinspector;1"].
getService(Ci.nsIJSInspector);
let xpcInspector = Cc["@mozilla.org/jsinspector;1"]
.getService(Ci.nsIJSInspector);
return {
Debugger,
@ -435,7 +436,8 @@ var {
setImmediate,
xpcInspector
};
} else { // Worker thread
}
// Worker thread
let requestors = [];
let scope = this;
@ -473,8 +475,8 @@ var {
setImmediate: this.setImmediate,
xpcInspector: xpcInspector
};
}
}).call(this);
/* eslint-enable no-shadow */
// Create the default instance of the worker loader, using the APIs we defined
// above.

View file

@ -1,6 +1,8 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Tests that the devtools/shared/worker communicates properly
// as both CommonJS module and as a JSM.
@ -37,7 +39,7 @@ function* testWorker(context, workerFactory) {
ok(results.plottedData.length,
`worker should have returned an object with array properties in ${context}`);
let fn = workerify(function (x) { return x * x; });
let fn = workerify(x => x * x);
is((yield fn(5)), 25, `workerify works in ${context}`);
fn.destroy();

View file

@ -1,6 +1,8 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Tests errors are handled properly by the DevToolsWorker.
const { DevToolsWorker } = require("devtools/shared/worker/worker");
@ -9,7 +11,7 @@ const WORKER_URL =
add_task(function* () {
try {
let workerNotFound = new DevToolsWorker("resource://i/dont/exist.js");
new DevToolsWorker("resource://i/dont/exist.js");
ok(false, "Creating a DevToolsWorker with an invalid URL throws");
} catch (e) {
ok(true, "Creating a DevToolsWorker with an invalid URL throws");
@ -19,14 +21,16 @@ add_task(function* () {
try {
// plotTimestampsGraph requires timestamp, interval an duration props on the object
// passed in so there should be an error thrown in the worker
let results = yield worker.performTask("plotTimestampsGraph", {});
ok(false, "DevToolsWorker returns a rejected promise when an error occurs in the worker");
yield worker.performTask("plotTimestampsGraph", {});
ok(false,
"DevToolsWorker returns a rejected promise when an error occurs in the worker");
} catch (e) {
ok(true, "DevToolsWorker returns a rejected promise when an error occurs in the worker");
ok(true,
"DevToolsWorker returns a rejected promise when an error occurs in the worker");
}
try {
let results = yield worker.performTask("not a real task");
yield worker.performTask("not a real task");
ok(false, "DevToolsWorker returns a rejected promise when task does not exist");
} catch (e) {
ok(true, "DevToolsWorker returns a rejected promise when task does not exist");
@ -34,7 +38,7 @@ add_task(function* () {
worker.destroy();
try {
let results = yield worker.performTask("plotTimestampsGraph", {
yield worker.performTask("plotTimestampsGraph", {
timestamps: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
interval: 1,
duration: 1

View file

@ -1,12 +1,14 @@
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
"use strict";
// Tests that the devtools/shared/worker can handle:
// returned primitives (or promise or Error)
//
// And tests `workerify` by doing so.
const { DevToolsWorker, workerify } = require("devtools/shared/worker/worker");
const { workerify } = require("devtools/shared/worker/worker");
function square(x) {
return x * x;
}