Bug 1209470 - Remove use of expression closure from Add-on SDK. r=mossop

This commit is contained in:
Tooru Fujisawa 2015-09-29 20:34:48 +09:00
parent a7cc76647e
commit a92f111d4a
93 changed files with 658 additions and 409 deletions

View File

@ -51,4 +51,6 @@ exports.send = send;
* Implement internal structured cloning algorithm in the future?
* http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#internal-structured-cloning-algorithm
*/
function clone (obj) JSON.parse(JSON.stringify(obj || {}))
function clone (obj) {
return JSON.parse(JSON.stringify(obj || {}));
}

View File

@ -62,31 +62,33 @@ function definePseudo(loader, id, exports) {
loader.modules[uri] = { exports: exports };
}
function startup(reason, options) Startup.onceInitialized.then(() => {
// Inject globals ASAP in order to have console API working ASAP
Object.defineProperties(options.loader.globals, descriptor(globals));
function startup(reason, options) {
return Startup.onceInitialized.then(() => {
// Inject globals ASAP in order to have console API working ASAP
Object.defineProperties(options.loader.globals, descriptor(globals));
// NOTE: Module is intentionally required only now because it relies
// on existence of hidden window, which does not exists until startup.
let { ready } = require('../addon/window');
// Load localization manifest and .properties files.
// Run the addon even in case of error (best effort approach)
require('../l10n/loader').
load(rootURI).
then(null, function failure(error) {
if (!isNative)
console.info("Error while loading localization: " + error.message);
}).
then(function onLocalizationReady(data) {
// Exports data to a pseudo module so that api-utils/l10n/core
// can get access to it
definePseudo(options.loader, '@l10n/data', data ? data : null);
return ready;
}).then(function() {
run(options);
}).then(null, console.exception);
// NOTE: Module is intentionally required only now because it relies
// on existence of hidden window, which does not exists until startup.
let { ready } = require('../addon/window');
// Load localization manifest and .properties files.
// Run the addon even in case of error (best effort approach)
require('../l10n/loader').
load(rootURI).
then(null, function failure(error) {
if (!isNative)
console.info("Error while loading localization: " + error.message);
}).
then(function onLocalizationReady(data) {
// Exports data to a pseudo module so that api-utils/l10n/core
// can get access to it
definePseudo(options.loader, '@l10n/data', data ? data : null);
return ready;
}).then(function() {
run(options);
}).then(null, console.exception);
return void 0; // otherwise we raise a warning, see bug 910304
});
});
}
function run(options) {
try {

View File

@ -17,4 +17,4 @@ const { isBrowser } = require("../window/utils");
// implementation for `isBrowser`. Either way it's not really needed yet
// neither window tracker provides this event.
exports.events = filter(events, function({target}) isBrowser(target));
exports.events = filter(events, ({target}) => isBrowser(target));

View File

@ -138,7 +138,7 @@ CONTEXTS.PageContext = Class({
// If the clicked node or any of its ancestors is one of the blocked
// NON_PAGE_CONTEXT_ELTS then this context does not match
while (!(popupNode instanceof Ci.nsIDOMDocument)) {
if (NON_PAGE_CONTEXT_ELTS.some(function(type) popupNode instanceof type))
if (NON_PAGE_CONTEXT_ELTS.some(type => popupNode instanceof type))
return false;
popupNode = popupNode.parentNode;

View File

@ -49,9 +49,9 @@ var opened = windows(null, { includePrivate: true });
var state = merge(opened.map(streamEventsFrom));
var futureReady = filter(windowEvents, function({type})
var futureReady = filter(windowEvents, ({type}) =>
type === "DOMContentLoaded");
var futureWindows = map(futureReady, function({target}) target);
var futureWindows = map(futureReady, ({target}) => target);
var futureState = expand(futureWindows, streamEventsFrom);
exports.events = merge([insert, create, state, futureState]);

View File

@ -63,14 +63,22 @@ exports.validationAttributes = valid;
* @param {Object} validation
* validation rule passed to `api-utils`
*/
function validate(suspect, validation) validateOptions(
{ $: suspect },
{ $: validation }
).$
function validate(suspect, validation) {
return validateOptions(
{ $: suspect },
{ $: validation }
).$;
}
function Allow(script) ({
get script() script,
set script(value) script = !!value
})
function Allow(script) {
return {
get script() {
return script;
},
set script(value) {
script = !!value;
}
};
}
exports.contract = contract(valid);

View File

@ -162,9 +162,15 @@ const WorkerSandbox = Class({
let parent = window.parent === window ? content : content.parent;
merge(content, {
// We need 'this === window === top' to be true in toplevel scope:
get window() content,
get top() top,
get parent() parent
get window() {
return content;
},
get top() {
return top;
},
get parent() {
return parent;
}
});
// Use the Greasemonkey naming convention to provide access to the

View File

@ -160,7 +160,7 @@ var URLContext = Class({
patterns = Array.isArray(patterns) ? patterns : [patterns];
try {
internal(this).patterns = patterns.map(function (p) new MatchPattern(p));
internal(this).patterns = patterns.map(p => new MatchPattern(p));
}
catch (err) {
throw new Error("Patterns must be a string, regexp or an array of " +
@ -169,7 +169,7 @@ var URLContext = Class({
},
isCurrent: function isCurrent(url) {
return internal(this).patterns.some(function (p) p.test(url));
return internal(this).patterns.some(p => p.test(url));
},
serialize: function() {
@ -212,11 +212,13 @@ var PredicateContext = Class({
exports.PredicateContext = PredicateContext;
function removeItemFromArray(array, item) {
return array.filter(function(i) i !== item);
return array.filter(i => i !== item);
}
// Converts anything that isn't false, null or undefined into a string
function stringOrNull(val) val ? String(val) : val;
function stringOrNull(val) {
return val ? String(val) : val;
}
// Shared option validation rules for Item, Menu, and Separator
var baseItemRules = {
@ -235,7 +237,7 @@ var baseItemRules = {
if (!v)
return true;
let arr = Array.isArray(v) ? v : [v];
return arr.every(function (o) o instanceof Context);
return arr.every(o => o instanceof Context);
},
msg: "The 'context' option must be a Context object or an array of " +
"Context objects."
@ -251,7 +253,7 @@ var labelledItemRules = mix(baseItemRules, {
label: {
map: stringOrNull,
is: ["string"],
ok: function (v) !!v,
ok: v => !!v,
msg: "The item must have a non-empty string label."
},
accesskey: {

View File

@ -32,14 +32,16 @@ var promised = (function() {
// Utility function that does following:
// execute([ f, self, args...]) => f.apply(self, args)
function execute (args) call.apply(call, args)
function execute (args) {
return call.apply(call, args);
}
// Utility function that takes promise of `a` array and maybe promise `b`
// as arguments and returns promise for `a.concat(b)`.
function promisedConcat(promises, unknown) {
return promises.then(function (values) {
return resolve(unknown)
.then(function (value) values.concat([value]));
.then(value => values.concat([value]));
});
}

View File

@ -54,7 +54,9 @@ const TestRunner = function TestRunner(options) {
};
TestRunner.prototype = {
toString: function toString() "[object TestRunner]",
toString: function toString() {
return "[object TestRunner]";
},
DEFAULT_PAUSE_TIMEOUT: (cfxArgs.parseable ? 300000 : 15000), //Five minutes (5*60*1000ms)
PAUSE_DELAY: 500,

View File

@ -21,7 +21,9 @@ const appShellService = Cc['@mozilla.org/appshell/appShellService;1'].
getService(Ci.nsIAppShellService);
// Bug 834961: ignore private windows when they are not supported
function getWindows() windows(null, { includePrivate: isPrivateBrowsingSupported });
function getWindows() {
return windows(null, { includePrivate: isPrivateBrowsingSupported });
}
/**
* An iterator for XUL windows currently in the application.

View File

@ -48,7 +48,7 @@ FrameOptions.validator = {
ok: function(v) {
if (getTypeOf(v) === "array") {
// make sure every item is a function
return v.every(function (item) typeof(item) === "function")
return v.every(item => typeof(item) === "function")
}
return true;
}
@ -112,4 +112,4 @@ function removeHiddenFrame(frame) {
}
exports.remove = removeHiddenFrame;
unload(function() fromIterator(cache).forEach(removeHiddenFrame));
unload(() => fromIterator(cache).forEach(removeHiddenFrame));

View File

@ -95,6 +95,7 @@ function create(target, options) {
}
exports.create = create;
function swapFrameLoaders(from, to)
from.QueryInterface(Ci.nsIFrameLoaderOwner).swapFrameLoaders(to)
function swapFrameLoaders(from, to) {
return from.QueryInterface(Ci.nsIFrameLoaderOwner).swapFrameLoaders(to);
}
exports.swapFrameLoaders = swapFrameLoaders;

View File

@ -323,7 +323,9 @@ Object.defineProperties(Buffer.prototype, {
['readUInt8', 'getUint8'],
['readInt8', 'getInt8']].forEach(([alias, name, littleEndian]) => {
Object.defineProperty(Buffer.prototype, alias, {
value: function(offset) this.view[name](offset, littleEndian)
value: function(offset) {
return this.view[name](offset, littleEndian);
}
});
});
@ -342,6 +344,8 @@ Object.defineProperties(Buffer.prototype, {
['writeUInt8', 'setUint8'],
['writeInt8', 'setInt8']].forEach(([alias, name, littleEndian]) => {
Object.defineProperty(Buffer.prototype, alias, {
value: function(value, offset) this.view[name](offset, value, littleEndian)
value: function(value, offset) {
return this.view[name](offset, value, littleEndian);
}
});
});

View File

@ -82,11 +82,19 @@ var nsIBinaryOutputStream = accessor();
// needs to be read.
const ALL = new String("Read all of the file");
function isWritable(mode) !!(mode & PR_WRONLY || mode & PR_RDWR)
function isReadable(mode) !!(mode & PR_RDONLY || mode & PR_RDWR)
function isWritable(mode) {
return !!(mode & PR_WRONLY || mode & PR_RDWR);
}
function isReadable(mode) {
return !!(mode & PR_RDONLY || mode & PR_RDWR);
}
function isString(value) typeof(value) === "string"
function isFunction(value) typeof(value) === "function"
function isString(value) {
return typeof(value) === "string";
}
function isFunction(value) {
return typeof(value) === "function";
}
function toArray(enumerator) {
let value = [];
@ -95,7 +103,9 @@ function toArray(enumerator) {
return value
}
function getFileName(file) file.QueryInterface(Ci.nsIFile).leafName
function getFileName(file) {
return file.QueryInterface(Ci.nsIFile).leafName;
}
function remove(path, recursive) {
@ -249,33 +259,67 @@ const Stats = Class({
if (!file.exists()) throw FSError("stat", "ENOENT", 34, path);
nsIFile(this, file);
},
isDirectory: function() nsIFile(this).isDirectory(),
isFile: function() nsIFile(this).isFile(),
isSymbolicLink: function() nsIFile(this).isSymlink(),
get mode() nsIFile(this).permissions,
get size() nsIFile(this).fileSize,
get mtime() nsIFile(this).lastModifiedTime,
isBlockDevice: function() nsIFile(this).isSpecial(),
isCharacterDevice: function() nsIFile(this).isSpecial(),
isFIFO: function() nsIFile(this).isSpecial(),
isSocket: function() nsIFile(this).isSpecial(),
isDirectory: function() {
return nsIFile(this).isDirectory();
},
isFile: function() {
return nsIFile(this).isFile();
},
isSymbolicLink: function() {
return nsIFile(this).isSymlink();
},
get mode() {
return nsIFile(this).permissions;
},
get size() {
return nsIFile(this).fileSize;
},
get mtime() {
return nsIFile(this).lastModifiedTime;
},
isBlockDevice: function() {
return nsIFile(this).isSpecial();
},
isCharacterDevice: function() {
return nsIFile(this).isSpecial();
},
isFIFO: function() {
return nsIFile(this).isSpecial();
},
isSocket: function() {
return nsIFile(this).isSpecial();
},
// non standard
get exists() nsIFile(this).exists(),
get hidden() nsIFile(this).isHidden(),
get writable() nsIFile(this).isWritable(),
get readable() nsIFile(this).isReadable()
get exists() {
return nsIFile(this).exists();
},
get hidden() {
return nsIFile(this).isHidden();
},
get writable() {
return nsIFile(this).isWritable();
},
get readable() {
return nsIFile(this).isReadable();
}
});
exports.Stats = Stats;
const LStats = Class({
extends: Stats,
get size() this.isSymbolicLink() ? nsIFile(this).fileSizeOfLink :
nsIFile(this).fileSize,
get mtime() this.isSymbolicLink() ? nsIFile(this).lastModifiedTimeOfLink :
nsIFile(this).lastModifiedTime,
get size() {
return this.isSymbolicLink() ? nsIFile(this).fileSizeOfLink :
nsIFile(this).fileSize;
},
get mtime() {
return this.isSymbolicLink() ? nsIFile(this).lastModifiedTimeOfLink :
nsIFile(this).lastModifiedTime;
},
// non standard
get permissions() this.isSymbolicLink() ? nsIFile(this).permissionsOfLink :
nsIFile(this).permissions
get permissions() {
return this.isSymbolicLink() ? nsIFile(this).permissionsOfLink :
nsIFile(this).permissions;
}
});
const FStat = Class({

View File

@ -181,7 +181,9 @@ const InputStream = Class({
this.inputStreamPump = inputStreamPump;
this.binaryInputStream = binaryInputStream;
},
get status() nsIInputStreamPump(this).status,
get status() {
return nsIInputStreamPump(this).status;
},
read: function() {
nsIInputStreamPump(this).asyncRead(nsIStreamListener(this), null);
},

View File

@ -185,8 +185,12 @@ const LOCALES_TO_RULES = {
};
// Utility functions for plural rules methods
function isIn(n, list) list.indexOf(n) !== -1;
function isBetween(n, start, end) start <= n && n <= end;
function isIn(n, list) {
return list.indexOf(n) !== -1;
}
function isBetween(n, start, end) {
return start <= n && n <= end;
}
// List of all plural rules methods, that maps an integer to the plural form name to use
const RULES = {

View File

@ -80,4 +80,4 @@ function get(key, n, locales) {
return undefined;
}
exports.get = function(k, n) get(k, n, Array.slice(preferedLocales));
exports.get = (k, n) => get(k, n, Array.slice(preferedLocales));

View File

@ -70,7 +70,7 @@ exports.notify = function notifications_notify(options) {
function notifyUsingConsole(iconURL, title, text) {
title = title ? "[" + title + "]" : "";
text = text || "";
let str = [title, text].filter(function (s) s).join(" ");
let str = [title, text].filter(s => s).join(" ");
console.log(str);
}

View File

@ -39,10 +39,18 @@ const readyEventNames = [
'load'
];
function workerFor(page) workers.get(page)
function pageFor(view) pages.get(view)
function viewFor(page) views.get(page)
function isDisposed (page) !views.get(page, false)
function workerFor(page) {
return workers.get(page);
}
function pageFor(view) {
return pages.get(view);
}
function viewFor(page) {
return views.get(page);
}
function isDisposed (page) {
return !views.get(page, false);
}
var pageContract = contract(merge({
allow: {
@ -82,7 +90,9 @@ function injectWorker ({page}) {
attach(worker, view.contentWindow);
}
function isValidURL(page, url) !page.rules || page.rules.matchesAny(url)
function isValidURL(page, url) {
return !page.rules || page.rules.matchesAny(url);
}
const Page = Class({
implements: [

View File

@ -95,7 +95,9 @@ function setScriptState(panel, value) {
view.setAttribute("sdkscriptenabled", "" + value);
}
function isDisposed(panel) !views.has(panel);
function isDisposed(panel) {
return !views.has(panel);
}
var panels = new WeakMap();
var models = new WeakMap();
@ -201,27 +203,43 @@ const Panel = Class({
views.delete(this);
},
/* Public API: Panel.width */
get width() modelFor(this).width,
set width(value) this.resize(value, this.height),
get width() {
return modelFor(this).width;
},
set width(value) {
this.resize(value, this.height);
},
/* Public API: Panel.height */
get height() modelFor(this).height,
set height(value) this.resize(this.width, value),
get height() {
return modelFor(this).height;
},
set height(value) {
this.resize(this.width, value);
},
/* Public API: Panel.focus */
get focus() modelFor(this).focus,
get focus() {
return modelFor(this).focus;
},
/* Public API: Panel.position */
get position() modelFor(this).position,
get position() {
return modelFor(this).position;
},
/* Public API: Panel.contextMenu */
get contextMenu() modelFor(this).contextMenu,
get contextMenu() {
return modelFor(this).contextMenu;
},
set contextMenu(allow) {
let model = modelFor(this);
model.contextMenu = panelContract({ contextMenu: allow }).contextMenu;
domPanel.allowContextMenu(viewFor(this), model.contextMenu);
},
get contentURL() modelFor(this).contentURL,
get contentURL() {
return modelFor(this).contentURL;
},
set contentURL(value) {
let model = modelFor(this);
model.contentURL = panelContract({ contentURL: value }).contentURL;
@ -238,7 +256,9 @@ const Panel = Class({
},
/* Public API: Panel.isShowing */
get isShowing() !isDisposed(this) && domPanel.isOpen(viewFor(this)),
get isShowing() {
return !isDisposed(this) && domPanel.isOpen(viewFor(this));
},
/* Public API: Panel.show */
show: function show(options={}, anchor) {

View File

@ -16,11 +16,12 @@ const { emit } = require("../event/core");
var channel = {};
function forward({ subject, type, data })
emit(channel, "data", { target: subject, type: type, data: data });
function forward({ subject, type, data }) {
return emit(channel, "data", { target: subject, type: type, data: data });
}
["popupshowing", "popuphiding", "popupshown", "popuphidden",
"document-element-inserted", "DOMContentLoaded", "load"
].forEach(function(type) events.on(type, forward));
].forEach(type => events.on(type, forward));
exports.events = channel;

View File

@ -429,7 +429,9 @@ var getContentFrame = panel =>
panel.backgroundFrame
exports.getContentFrame = getContentFrame;
function getContentDocument(panel) getContentFrame(panel).contentDocument
function getContentDocument(panel) {
return getContentFrame(panel).contentDocument;
}
exports.getContentDocument = getContentDocument;
function setURL(panel, url) {

View File

@ -16,8 +16,9 @@ const { URL: parseURL } = require("../url");
const LoginInfo = CC("@mozilla.org/login-manager/loginInfo;1",
"nsILoginInfo", "init");
function filterMatchingLogins(loginInfo)
Object.keys(this).every(function(key) loginInfo[key] === this[key], this);
function filterMatchingLogins(loginInfo) {
return Object.keys(this).every(key => loginInfo[key] === this[key], this);
}
/**
* Removes `user`, `password` and `path` fields from the given `url` if it's
@ -70,7 +71,9 @@ Login.prototype.toLoginInfo = function toLoginInfo() {
usernameField, passwordField);
};
function loginToJSON(value) Login(value).toJSON()
function loginToJSON(value) {
return Login(value).toJSON();
}
/**
* Returns array of `nsILoginInfo` objects that are stored in the login manager

View File

@ -62,7 +62,7 @@ const Bookmark = Class({
merge(this, bookmarkContract(extend(defaults, options)));
},
type: 'bookmark',
toString: function () '[object Bookmark]'
toString: () => '[object Bookmark]'
});
exports.Bookmark = Bookmark;
@ -78,7 +78,7 @@ const Group = Class({
merge(this, groupContract(extend(defaults, options)));
},
type: 'group',
toString: function () '[object Group]'
toString: () => '[object Group]'
});
exports.Group = Group;
@ -90,7 +90,7 @@ const Separator = Class({
merge(this, separatorContract(extend(defaults, options)));
},
type: 'separator',
toString: function () '[object Separator]'
toString: () => '[object Separator]'
});
exports.Separator = Separator;

View File

@ -29,7 +29,7 @@ const validItem = {
},
index: {
is: ['undefined', 'null', 'number'],
map: function (value) value == null ? -1 : value,
map: value => value == null ? -1 : value,
msg: 'The `index` property must be a number.'
},
updated: {
@ -55,7 +55,7 @@ const validURL = {
const validTags = {
tags: {
is: ['object'],
ok: function (tags) tags instanceof Set,
ok: tags => tags instanceof Set,
map: function (tags) {
if (Array.isArray(tags))
return new Set(tags);

View File

@ -63,8 +63,9 @@ function typeMap (type) {
}
}
function getBookmarkLastUpdated ({id})
resolve(bmsrv.getItemLastModified(id))
function getBookmarkLastUpdated ({id}) {
return resolve(bmsrv.getItemLastModified(id));
}
exports.getBookmarkLastUpdated;
function createBookmarkItem (data) {

View File

@ -155,7 +155,7 @@ function normalize (historyObj) {
* Hook into host
*/
var reqStream = filter(request, function (data) /sdk-places-query/.test(data.event));
var reqStream = filter(request, data => /sdk-places-query/.test(data.event));
on(reqStream, 'data', function (e) {
if (EVENT_MAP[e.event]) EVENT_MAP[e.event](e);
});

View File

@ -60,7 +60,7 @@ function getURLsByTag (message) {
};
resData.data = taggingService
.getURIsForTag(data.tag).map(function (uri) uri.spec);
.getURIsForTag(data.tag).map(uri => uri.spec);
respond(resData);
}

View File

@ -44,7 +44,7 @@ var TreeNode = Class({
},
get: method(get),
walk: method(walk),
toString: function () '[object TreeNode]'
toString: () => '[object TreeNode]'
});
exports.TreeNode = TreeNode;
@ -103,8 +103,9 @@ exports.constructTree = constructTree;
* Shortcut for converting an id, or an object with an id, into
* an object with corresponding bookmark data
*/
function fetchItem (item)
send('sdk-places-bookmarks-get', { id: item.id || item })
function fetchItem (item) {
return send('sdk-places-bookmarks-get', { id: item.id || item });
}
exports.fetchItem = fetchItem;
/*

View File

@ -21,8 +21,8 @@ const { uuid } = require('../util/uuid');
const Unknown = new function() {
function hasInterface(component, iid) {
return component && component.interfaces &&
( component.interfaces.some(function(id) iid.equals(Ci[id])) ||
component.implements.some(function($) hasInterface($, iid)) ||
( component.interfaces.some(id => iid.equals(Ci[id])) ||
component.implements.some($ => hasInterface($, iid)) ||
hasInterface(Object.getPrototypeOf(component), iid));
}
@ -85,7 +85,9 @@ const Factory = Class({
* This method is required by `nsIFactory` interfaces, but as in most
* implementations it does nothing interesting.
*/
lockFactory: function lockFactory(lock) undefined,
lockFactory: function lockFactory(lock) {
return undefined;
},
/**
* If property is `true` XPCOM service / factory will be registered
* automatically on creation.
@ -131,7 +133,9 @@ const Factory = Class({
throw error instanceof Ci.nsIException ? error : Cr.NS_ERROR_FAILURE;
}
},
create: function create() this.Component()
create: function create() {
return this.Component();
}
});
exports.Factory = Factory;
@ -148,11 +152,15 @@ const Service = Class({
/**
* Creates an instance of the class associated with this factory.
*/
create: function create() this.component
create: function create() {
return this.component;
}
});
exports.Service = Service;
function isRegistered({ id }) isCIDRegistered(id)
function isRegistered({ id }) {
return isCIDRegistered(id);
}
exports.isRegistered = isRegistered;
/**
@ -216,7 +224,9 @@ exports.autoRegister = autoRegister;
/**
* Returns registered factory that has a given `id` or `null` if not found.
*/
function factoryByID(id) classesByID[id] || null
function factoryByID(id) {
return classesByID[id] || null;
}
exports.factoryByID = factoryByID;
/**
@ -225,5 +235,7 @@ exports.factoryByID = factoryByID;
* with a given `contract` this will return a factory currently associated
* with a `contract`.
*/
function factoryByContract(contract) factoryByID(Cm.contractIDToCID(contract))
function factoryByContract(contract) {
return factoryByID(Cm.contractIDToCID(contract));
}
exports.factoryByContract = factoryByContract;

View File

@ -26,27 +26,27 @@ const request = ns();
const { validateOptions, validateSingleOption } = new OptionsValidator({
url: {
// Also converts a URL instance to string, bug 857902
map: function (url) url.toString(),
map: url => url.toString(),
ok: isValidURI
},
headers: {
map: function (v) v || {},
map: v => v || {},
is: ["object"],
},
content: {
map: function (v) v || null,
map: v => v || null,
is: ["string", "object", "null"],
},
contentType: {
map: function (v) v || "application/x-www-form-urlencoded",
map: v => v || "application/x-www-form-urlencoded",
is: ["string"],
},
overrideMimeType: {
map: function(v) v || null,
map: v => v || null,
is: ["string", "null"],
},
anonymous: {
map: function(v) v || false,
map: v => v || false,
is: ["boolean", "null"],
}
});
@ -165,14 +165,22 @@ const Response = Class({
response(this).request = request;
},
// more about responseURL: https://bugzilla.mozilla.org/show_bug.cgi?id=998076
get url() response(this).request.responseURL,
get text() response(this).request.responseText,
get url() {
return response(this).request.responseURL;
},
get text() {
return response(this).request.responseText;
},
get xml() {
throw new Error("Sorry, the 'xml' property is no longer available. " +
"see bug 611042 for more information.");
},
get status() response(this).request.status,
get statusText() response(this).request.statusText,
get status() {
return response(this).request.status;
},
get statusText() {
return response(this).request.statusText;
},
get json() {
try {
return JSON.parse(this.text);
@ -212,7 +220,9 @@ const Response = Class({
});
return headers;
},
get anonymous() response(this).request.mozAnon
get anonymous() {
return response(this).request.mozAnon;
}
});
// apiUtils.validateOptions doesn't give the ability to easily validate single

View File

@ -80,7 +80,7 @@ const Selection = Class({
const selectionListener = {
notifySelectionChanged: function (document, selection, reason) {
if (!["SELECTALL", "KEYPRESS", "MOUSEUP"].some(function(type) reason &
if (!["SELECTALL", "KEYPRESS", "MOUSEUP"].some(type => reason &
Ci.nsISelectionListener[type + "_REASON"]) || selection.toString() == "")
return;

View File

@ -15,16 +15,18 @@ const { get, set, exists } = Cc['@mozilla.org/process/environment;1'].
exports.env = Proxy.create({
// XPCOM does not provides a way to enumerate environment variables, so we
// just don't support enumeration.
getPropertyNames: function() [],
getOwnPropertyNames: function() [],
enumerate: function() [],
keys: function() [],
getPropertyNames: () => [],
getOwnPropertyNames: () => [],
enumerate: () => [],
keys: () => [],
// We do not support freezing, cause it would make it impossible to set new
// environment variables.
fix: function() undefined,
fix: () => undefined,
// We present all environment variables as own properties of this object,
// so we just delegate this call to `getOwnPropertyDescriptor`.
getPropertyDescriptor: function(name) this.getOwnPropertyDescriptor(name),
getPropertyDescriptor: function(name) {
return this.getOwnPropertyDescriptor(name);
},
// If environment variable with this name is defined, we generate proprety
// descriptor for it, otherwise fall back to `undefined` so that for consumer
// this property does not exists.
@ -39,22 +41,24 @@ exports.env = Proxy.create({
// New environment variables can be defined just by defining properties
// on this object.
defineProperty: function(name, { value }) set(name, value),
defineProperty: (name, { value }) => set(name, value),
delete: function(name) {
set(name, null);
return true;
},
// We present all properties as own, there for we just delegate to `hasOwn`.
has: function(name) this.hasOwn(name),
has: function(name) {
return this.hasOwn(name);
},
// We do support checks for existence of an environment variable, via `in`
// operator on this object.
hasOwn: function(name) exists(name),
hasOwn: name => exists(name),
// On property get / set we do read / write appropriate environment variables,
// please note though, that variables with names of standard object properties
// intentionally (so that this behaves as normal object) can not be
// read / set.
get: function(proxy, name) Object.prototype[name] || get(name) || undefined,
set: function(proxy, name, value) Object.prototype[name] || set(name, value)
get: (proxy, name) => Object.prototype[name] || get(name) || undefined,
set: (proxy, name, value) => Object.prototype[name] || set(name, value)
});

View File

@ -35,14 +35,14 @@ function tabEventsFor(window) {
// Map supported event types to a streams of those events on the given
// `window` and than merge these streams into single form stream off
// all events.
let channels = TYPES.map(function(type) open(window, type));
let channels = TYPES.map(type => open(window, type));
return merge(channels);
}
// Filter DOMContentLoaded events from all the browser events.
var readyEvents = filter(events, function(e) e.type === "DOMContentLoaded");
var readyEvents = filter(events, e => e.type === "DOMContentLoaded");
// Map DOMContentLoaded events to it's target browser windows.
var futureWindows = map(readyEvents, function(e) e.target);
var futureWindows = map(readyEvents, e => e.target);
// Expand all browsers that will become interactive to supported tab events
// on these windows. Result will be a tab events from all tabs of all windows
// that will become interactive.

View File

@ -58,8 +58,12 @@ const Tab = Class({
* Changing this property changes an actual title.
* @type {String}
*/
get title() getTabTitle(tabNS(this).tab),
set title(title) setTabTitle(tabNS(this).tab, title),
get title() {
return getTabTitle(tabNS(this).tab);
},
set title(title) {
setTabTitle(tabNS(this).tab, title);
},
/**
* Location of the page currently loaded in this tab.
@ -69,7 +73,9 @@ const Tab = Class({
get url() {
return tabNS(this).closed ? undefined : getTabURL(tabNS(this).tab);
},
set url(url) setTabURL(tabNS(this).tab, url),
set url(url) {
setTabURL(tabNS(this).tab, url);
},
getThumbnail: function() {
// TODO: implement!
@ -131,7 +137,9 @@ const Tab = Class({
* rendered as.
* @type {String}
*/
get contentType() getTabContentType(tabNS(this).tab),
get contentType() {
return getTabContentType(tabNS(this).tab);
},
/**
* Create a worker for this tab, first argument is options given to Worker.

View File

@ -17,7 +17,9 @@ const { windows, isBrowser } = require('../window/utils');
const { isPrivateBrowsingSupported } = require('../self');
// Bug 834961: ignore private windows when they are not supported
function getWindows() windows(null, { includePrivate: isPrivateBrowsingSupported });
function getWindows() {
return windows(null, { includePrivate: isPrivateBrowsingSupported });
}
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
@ -91,7 +93,7 @@ function getTabs(window) {
return window.BrowserApp.tabs;
// firefox - default
return Array.filter(getTabContainer(window).children, function(t) !t.closing);
return Array.filter(getTabContainer(window).children, t => !t.closing);
}
exports.getTabs = getTabs;
@ -321,7 +323,9 @@ function unpin(tab) {
}
exports.unpin = unpin;
function isPinned(tab) !!tab.pinned
function isPinned(tab) {
return !!tab.pinned;
}
exports.isPinned = isPinned;
function reload(tab) {

View File

@ -327,7 +327,9 @@ function getPotentialLeaks() {
principal: details[1],
location: details[2] ? details[2].replace(/\\/g, "/") : undefined,
source: details[3] ? details[3].split(" -> ").reverse() : undefined,
toString: function() this.location
toString: function() {
return this.location;
}
};
if (!isPossibleLeak(item))
@ -351,7 +353,9 @@ function getPotentialLeaks() {
path: matches[1],
location: details[1].replace(/\\/g, "/"),
source: [details[1].replace(/\\/g, "/")],
toString: function() this.location
toString: function() {
return this.location;
}
};
if (!isPossibleLeak(item))
@ -631,7 +635,7 @@ var runTests = exports.runTests = function runTests(options) {
fileName: { value: e.fileName, writable: true, configurable: true },
lineNumber: { value: e.lineNumber, writable: true, configurable: true },
stack: { value: stack, writable: true, configurable: true },
toString: { value: function() String(e), writable: true, configurable: true },
toString: { value: () => String(e), writable: true, configurable: true },
});
print("Error: " + error + " \n " + format(error));

View File

@ -71,7 +71,9 @@ const ActionButton = Class({
unregister(this);
},
get id() this.state().id,
get id() {
return this.state().id;
},
click: function click() { view.click(toWidgetId(this.id)) }
});

View File

@ -72,9 +72,13 @@ const ToggleButton = Class({
unregister(this);
},
get id() this.state().id,
get id() {
return this.state().id;
},
click: function click() view.click(toWidgetId(this.id))
click: function click() {
return view.click(toWidgetId(this.id));
}
});
exports.ToggleButton = ToggleButton;

View File

@ -212,8 +212,12 @@ const Sidebar = Class({
add(sidebars, this);
},
get id() (modelFor(this) || {}).id,
get title() (modelFor(this) || {}).title,
get id() {
return (modelFor(this) || {}).id;
},
get title() {
return (modelFor(this) || {}).title;
},
set title(v) {
// destroyed?
if (!modelFor(this))
@ -226,7 +230,9 @@ const Sidebar = Class({
updateTitle(this, v);
return modelFor(this).title = v;
},
get url() (modelFor(this) || {}).url,
get url() {
return (modelFor(this) || {}).url;
},
set url(v) {
// destroyed?
if (!modelFor(this))
@ -242,8 +248,12 @@ const Sidebar = Class({
updateURL(this, v);
modelFor(this).url = v;
},
show: function(window) showSidebar(viewFor(window), this),
hide: function(window) hideSidebar(viewFor(window), this),
show: function(window) {
return showSidebar(viewFor(window), this);
},
hide: function(window) {
return hideSidebar(viewFor(window), this);
},
dispose: function() {
const internals = sidebarNS(this);

View File

@ -21,7 +21,7 @@ exports.contract = contract({
url: {
is: [ 'string' ],
ok: v => isLocalURL(v),
map: function(v) v.toString(),
map: v => v.toString(),
msg: 'The option "url" must be a valid local URI.'
}
});

View File

@ -7,5 +7,9 @@ const models = exports.models = new WeakMap();
const views = exports.views = new WeakMap();
exports.buttons = new WeakMap();
exports.viewsFor = function viewsFor(sidebar) views.get(sidebar);
exports.modelFor = function modelFor(sidebar) models.get(sidebar);
exports.viewsFor = function viewsFor(sidebar) {
return views.get(sidebar);
};
exports.modelFor = function modelFor(sidebar) {
return models.get(sidebar);
};

View File

@ -137,18 +137,18 @@ function URL(url, base) {
let search = uri.path.substr(queryPos, queryLen);
search = search ? "?" + search : "";
this.__defineGetter__("scheme", function() uri.scheme);
this.__defineGetter__("userPass", function() userPass);
this.__defineGetter__("host", function() host);
this.__defineGetter__("hostname", function() host);
this.__defineGetter__("port", function() port);
this.__defineGetter__("path", function() uri.path);
this.__defineGetter__("pathname", function() pathname);
this.__defineGetter__("hash", function() hash);
this.__defineGetter__("href", function() uri.spec);
this.__defineGetter__("origin", function() uri.prePath);
this.__defineGetter__("protocol", function() uri.scheme + ":");
this.__defineGetter__("search", function() search);
this.__defineGetter__("scheme", () => uri.scheme);
this.__defineGetter__("userPass", () => userPass);
this.__defineGetter__("host", () => host);
this.__defineGetter__("hostname", () => host);
this.__defineGetter__("port", () => port);
this.__defineGetter__("path", () => uri.path);
this.__defineGetter__("pathname", () => pathname);
this.__defineGetter__("hash", () => hash);
this.__defineGetter__("href", () => uri.spec);
this.__defineGetter__("origin", () => uri.prePath);
this.__defineGetter__("protocol", () => uri.scheme + ":");
this.__defineGetter__("search", () => search);
Object.defineProperties(this, {
toString: {

View File

@ -22,7 +22,7 @@ function newURI (uri) {
exports.newURI = newURI;
var getURL = method('sdk/url:getURL');
getURL.define(String, function (url) url);
getURL.define(String, url => url);
getURL.define(function (object) {
return null;
});

View File

@ -27,12 +27,16 @@ const listOptions = {
* Number of elements in this list.
* @type {Number}
*/
get length() listNS(this).keyValueMap.length,
get length() {
return listNS(this).keyValueMap.length;
},
/**
* Returns a string representing this list.
* @returns {String}
*/
toString: function toString() 'List(' + listNS(this).keyValueMap + ')',
toString: function toString() {
return 'List(' + listNS(this).keyValueMap + ')';
},
/**
* Custom iterator providing `List`s enumeration behavior.
* We cant reuse `_iterator` that is defined by `Iterable` since it provides

View File

@ -107,7 +107,7 @@ MatchPattern.prototype = {
return false;
},
toString: function () '[object MatchPattern]'
toString: () => '[object MatchPattern]'
};
exports.MatchPattern = MatchPattern;

View File

@ -56,7 +56,9 @@ function extend(source) {
}
exports.extend = extend;
function has(obj, key) obj.hasOwnProperty(key);
function has(obj, key) {
return obj.hasOwnProperty(key);
}
exports.has = has;
function each(obj, fn) {

View File

@ -19,22 +19,28 @@ const Rules = Class({
EventTarget,
List
],
add: function(...rules) [].concat(rules).forEach(function onAdd(rule) {
addListItem(this, rule);
emit(this, 'add', rule);
}, this),
remove: function(...rules) [].concat(rules).forEach(function onRemove(rule) {
removeListItem(this, rule);
emit(this, 'remove', rule);
}, this),
add: function(...rules) {
return [].concat(rules).forEach(function onAdd(rule) {
addListItem(this, rule);
emit(this, 'add', rule);
}, this);
},
remove: function(...rules) {
return [].concat(rules).forEach(function onRemove(rule) {
removeListItem(this, rule);
emit(this, 'remove', rule);
}, this);
},
get: function(rule) {
let found = false;
for (let i in this) if (this[i] === rule) found = true;
return found;
},
// Returns true if uri matches atleast one stored rule
matchesAny: function(uri) !!filterMatches(this, uri).length,
toString: function() '[object Rules]'
matchesAny: function(uri) {
return !!filterMatches(this, uri).length;
},
toString: () => '[object Rules]'
});
exports.Rules = Rules;

View File

@ -14,4 +14,6 @@ const { generateUUID } = Cc['@mozilla.org/uuid-generator;1'].
// Returns `uuid`. If `id` is passed then it's parsed to `uuid` and returned
// if not then new one is generated.
exports.uuid = function uuid(id) id ? parseUUID(id) : generateUUID()
exports.uuid = function uuid(id) {
return id ? parseUUID(id) : generateUUID();
};

View File

@ -29,12 +29,18 @@ const BrowserWindow = Class({
throw new Error(ERR_FENNEC_MSG);
return null;
},
get title() getWindowTitle(windowNS(this).window),
get title() {
return getWindowTitle(windowNS(this).window);
},
// NOTE: Fennec only has one window, which is assumed below
// TODO: remove assumption below
// NOTE: tabs requires windows
get tabs() require('../tabs'),
get activeTab() require('../tabs').activeTab,
get tabs() {
return require('../tabs');
},
get activeTab() {
return require('../tabs').activeTab;
},
on: method(on),
removeListener: method(off),
once: method(once)

View File

@ -19,7 +19,7 @@ function eventsFor(window) {
let interactive = open(window, "DOMContentLoaded", { capture: true });
let complete = open(window, "load", { capture: true });
let states = merge([interactive, complete]);
let changes = filter(states, function({target}) target === window.document);
let changes = filter(states, ({target}) => target === window.document);
return map(changes, function({type, target}) {
return { type: type, target: target.defaultView }
});
@ -39,7 +39,7 @@ rename.domwindowclosed = "close";
var openEvents = map(observe("domwindowopened"), rename);
var closeEvents = map(observe("domwindowclosed"), rename);
var futureEvents = expand(openEvents, function({target}) eventsFor(target));
var futureEvents = expand(openEvents, ({target}) => eventsFor(target));
var channel = merge([currentEvents, futureEvents,
openEvents, closeEvents]);

View File

@ -142,7 +142,9 @@ function getToplevelWindow(window) {
}
exports.getToplevelWindow = getToplevelWindow;
function getWindowDocShell(window) window.gBrowser.docShell;
function getWindowDocShell(window) {
return window.gBrowser.docShell;
}
exports.getWindowDocShell = getWindowDocShell;
function getWindowLoadingContext(window) {

View File

@ -135,10 +135,10 @@ function onTabOpen(event) {
tabNS(tab).opened = true;
tab.on('ready', function() emit(gTabs, 'ready', tab));
tab.on('ready', () => emit(gTabs, 'ready', tab));
tab.once('close', onTabClose);
tab.on('pageshow', function(_tab, persisted)
tab.on('pageshow', (_tab, persisted) =>
emit(gTabs, 'pageshow', tab, persisted));
emit(tab, 'open', tab);

View File

@ -363,7 +363,7 @@ const load = iced(function load(loader, module) {
fileName: { value: fileName, writable: true, configurable: true },
lineNumber: { value: lineNumber, writable: true, configurable: true },
stack: { value: serializeStack(frames), writable: true, configurable: true },
toString: { value: function() toString, writable: true, configurable: true },
toString: { value: () => toString, writable: true, configurable: true },
});
}

View File

@ -152,8 +152,12 @@ print """/* This Source Code Form is subject to the terms of the Mozilla Public
const LOCALES_TO_RULES = %s;
// Utility functions for plural rules methods
function isIn(n, list) list.indexOf(n) !== -1;
function isBetween(n, start, end) start <= n && n <= end;
function isIn(n, list) {
return list.indexOf(n) !== -1;
}
function isBetween(n, start, end) {
return start <= n && n <= end;
}
// List of all plural rules methods, that maps an integer to the plural form name to use
const RULES = {

View File

@ -634,8 +634,12 @@ exports["test Prototype Inheritance"] = createProxyTest("", function (helper) {
exports["test Functions"] = createProxyTest("", function (helper) {
helper.rawWindow.callFunction = function callFunction(f) f();
helper.rawWindow.isEqual = function isEqual(a, b) a == b;
helper.rawWindow.callFunction = function callFunction(f) {
return f();
};
helper.rawWindow.isEqual = function isEqual(a, b) {
return a == b;
};
// bug 784116: workaround in order to allow proxy code to cache proxies on
// these functions:
helper.rawWindow.callFunction.__exposedProps__ = {__proxy: 'rw'};

View File

@ -66,9 +66,9 @@ exports.testUnwrappedDOM = function(assert, done) {
let page = Page({
allow: { script: true },
contentURL: "data:text/html;charset=utf-8,<script>document.getElementById=3;window.scrollTo=3;</script>",
contentScript: "window.addEventListener('load', function () " +
"self.postMessage([typeof(unsafeWindow.document.getElementById), " +
"typeof(unsafeWindow.scrollTo)]), true)",
contentScript: "window.addEventListener('load', function () { " +
"return self.postMessage([typeof(unsafeWindow.document.getElementById), " +
"typeof(unsafeWindow.scrollTo)]); }, true)",
onMessage: function (message) {
assert.equal(message[0],
"number",
@ -93,7 +93,7 @@ exports.testPageProperties = function(assert) {
assert.ok(prop in page, prop + " property is defined on page.");
}
assert.ok(function () page.postMessage("foo") || true,
assert.ok(() => page.postMessage("foo") || true,
"postMessage doesn't throw exception on page.");
}
@ -149,13 +149,13 @@ exports.testAutoDestructor = function(assert, done) {
exports.testValidateOptions = function(assert) {
assert.throws(
function () Page({ contentURL: 'home' }),
() => Page({ contentURL: 'home' }),
/The `contentURL` option must be a valid URL\./,
"Validation correctly denied a non-URL contentURL"
);
assert.throws(
function () Page({ onMessage: "This is not a function."}),
() => Page({ onMessage: "This is not a function."}),
/The option "onMessage" must be one of the following types: function/,
"Validation correctly denied a non-function onMessage."
);
@ -321,7 +321,7 @@ exports.testAllowScript = function(assert, done) {
exports.testPingPong = function(assert, done) {
let page = Page({
contentURL: 'data:text/html;charset=utf-8,ping-pong',
contentScript: 'self.on("message", function(message) self.postMessage("pong"));'
contentScript: 'self.on("message", function(message) { return self.postMessage("pong"); });'
+ 'self.postMessage("ready");',
onMessage: function(message) {
if ('ready' == message) {

View File

@ -30,6 +30,6 @@ setTimeout(function() {
// main didn't start, fail..
require("sdk/test/runner").runTestsFromModule({exports: {
testFail: function(assert) assert.fail('Main did not start..')
testFail: assert => assert.fail('Main did not start..')
}});
}, 500);

View File

@ -799,7 +799,9 @@ exports.testCaching = function (assert, done) {
off(stream, 'data', handle);
}).then(done).catch(assert.fail);
function handle ({data}) count++
function handle ({data}) {
return count++;
}
};
/*

View File

@ -95,7 +95,7 @@ exports.testSearchTimeRange = function (assert, done) {
]).then(searchP).then(results => {
firstTime = results[0].time;
var deferred = defer();
setTimeout(function () deferred.resolve(), 1000);
setTimeout(() => deferred.resolve(), 1000);
return deferred.promise;
}).then(() => {
return addVisits(['http://newvisit.org', 'http://newvisit.org/whoawhoa.html']);

View File

@ -13,38 +13,40 @@ const { isPrivate } = require('sdk/private-browsing');
const { isTabPBSupported, isWindowPBSupported } = require('sdk/private-browsing/utils');
const { cleanUI } = require('sdk/test/utils');
function openWebpage(url, enablePrivate) new Promise((resolve, reject) => {
if (xulApp.is("Fennec")) {
let chromeWindow = getMostRecentBrowserWindow();
let rawTab = openTab(chromeWindow, url, {
isPrivate: enablePrivate
});
function openWebpage(url, enablePrivate) {
return new Promise((resolve, reject) => {
if (xulApp.is("Fennec")) {
let chromeWindow = getMostRecentBrowserWindow();
let rawTab = openTab(chromeWindow, url, {
isPrivate: enablePrivate
});
resolve(() => new Promise(resolve => {
closeTab(rawTab);
resolve();
}));
}
else {
windowHelpers.open("", {
features: {
toolbar: true,
private: enablePrivate
}
}).
then((chromeWindow) => {
if (isPrivate(chromeWindow) !== !!enablePrivate) {
reject(new Error("Window should have Private set to " + !!enablePrivate));
}
resolve(() => new Promise(resolve => {
closeTab(rawTab);
resolve();
}));
}
else {
windowHelpers.open("", {
features: {
toolbar: true,
private: enablePrivate
}
}).
then((chromeWindow) => {
if (isPrivate(chromeWindow) !== !!enablePrivate) {
reject(new Error("Window should have Private set to " + !!enablePrivate));
}
let tab = getActiveTab(chromeWindow);
setTabURL(tab, url);
let tab = getActiveTab(chromeWindow);
setTabURL(tab, url);
resolve(() => windowHelpers.close(chromeWindow));
}).
catch(reject);
}
})
resolve(() => windowHelpers.close(chromeWindow));
}).
catch(reject);
}
});
}
exports["test page-mod on private tab"] = function*(assert) {
// Only set private mode when explicitely supported.

View File

@ -218,7 +218,7 @@ exports["test PWPB Selection Listener"] = function(assert, done) {
selection.once("select", function() {
assert.equal(browserWindows.length, 2, "there should be only two windows open.");
assert.equal(getTabs().length, 2, "there should be only two tabs open: '" +
getTabs().map(function(tab) getTabTitle(tab)).join("', '") +
getTabs().map(tab => getTabTitle(tab)).join("', '") +
"'."
);
@ -252,7 +252,7 @@ exports["test PWPB Textarea OnSelect Listener"] = function(assert, done) {
selection.once("select", function() {
assert.equal(browserWindows.length, 2, "there should be only two windows open.");
assert.equal(getTabs().length, 2, "there should be only two tabs open: '" +
getTabs().map(function(tab) getTabTitle(tab)).join("', '") +
getTabs().map(tab => getTabTitle(tab)).join("', '") +
"'."
);

View File

@ -90,7 +90,7 @@ exports.testSettingActiveWindowDoesNotIgnorePrivateWindow = function(assert, don
makeEmptyBrowserWindow({
private: true
}).then(function(window) {
let continueAfterFocus = function(window) onFocus(window).then(nextTest);
let continueAfterFocus = window => onFocus(window).then(nextTest);
// PWPB case
if (isWindowPBSupported) {

View File

@ -272,7 +272,9 @@ TestHelper.prototype = {
}
else {
this.delayedEventListener(this.contextMenuPopup, "popuphidden",
function () closeBrowserWindow.call(this),
function () {
return closeBrowserWindow.call(this);
},
false);
this.contextMenuPopup.hidePopup();
}

View File

@ -63,7 +63,7 @@ function scenario(setup) {
unit(input, function(output, events, expected, message) {
let result = setup(output, expected, actual);
events.forEach(function(event) emit(input, "data", event));
events.forEach(event => emit(input, "data", event));
assert.deepEqual(actual, result, message);
});
@ -72,13 +72,17 @@ function scenario(setup) {
}
exports.emits = scenario(function(output, expected, actual) {
on(output, "data", function(data) actual.push(this, data));
on(output, "data", function(data) {
return actual.push(this, data);
});
return expected.reduce(function($$, $) $$.concat(output, $), []);
return expected.reduce(($$, $) => $$.concat(output, $), []);
});
exports.registerOnce = scenario(function(output, expected, actual) {
function listener(data) actual.push(data);
function listener(data) {
return actual.push(data);
}
on(output, "data", listener);
on(output, "data", listener);
on(output, "data", listener);
@ -94,13 +98,13 @@ exports.ignoreNew = scenario(function(output, expected, actual) {
});
});
return expected.map(function($) $ + "#1");
return expected.map($ => $ + "#1");
});
exports.FIFO = scenario(function(target, expected, actual) {
on(target, "data", function($) actual.push($ + "#1"));
on(target, "data", function($) actual.push($ + "#2"));
on(target, "data", function($) actual.push($ + "#3"));
on(target, "data", $ => actual.push($ + "#1"));
on(target, "data", $ => actual.push($ + "#2"));
on(target, "data", $ => actual.push($ + "#3"));
return expected.reduce(function(result, value) {
return result.concat(value + "#1", value + "#2", value + "#3");

View File

@ -2,4 +2,4 @@
* 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/. */
self.on("context", function () true);
self.on("context", () => true);

View File

@ -48,7 +48,7 @@ function testPageMod(assert, done, testURL, pageModOptions,
setTimeout(testCallback, timeout,
b.contentWindow.wrappedJSObject, // TODO: remove this CPOW
function () {
pageMods.forEach(function(mod) mod.destroy());
pageMods.forEach(mod => mod.destroy());
// XXX leaks reported if we don't close the tab?
closeTab(newTab);
loader.unload();

View File

@ -75,7 +75,7 @@ exports.testIsPrivateOnWindowOpenFromPrivate = function(assert, done) {
url: 'about:blank',
onOpen: function(w) {
assert.equal(isPrivate(w), false, 'new test window is not private');
w.close(function() resolve(window));
w.close(() => resolve(window));
}
});

View File

@ -129,8 +129,8 @@ exports.testTabsIteratorAndLength = function(assert, done) {
assert.equal(startCount, tabs.length, "length property is correct");
let url = "data:text/html;charset=utf-8,testTabsIteratorAndLength";
tabs.open({url: url, onOpen: function(tab) newTabs.push(tab)});
tabs.open({url: url, onOpen: function(tab) newTabs.push(tab)});
tabs.open({url: url, onOpen: tab => newTabs.push(tab)});
tabs.open({url: url, onOpen: tab => newTabs.push(tab)});
tabs.open({
url: url,
onOpen: function(tab) {
@ -140,7 +140,7 @@ exports.testTabsIteratorAndLength = function(assert, done) {
assert.equal(startCount + 3, tabs.length, "iterated tab count matches length property");
let newTabsLength = newTabs.length;
newTabs.forEach(function(t) t.close(function() {
newTabs.forEach(t => t.close(function() {
if (--newTabsLength > 0) return;
tab.close(done);
@ -195,7 +195,7 @@ exports.testTabMove = function(assert, done) {
JSON.stringify([ERR_FENNEC_MSG]),
"setting tab.index logs error");
// end test
tab1.close(function() tab.close(function() {
tab1.close(() => tab.close(function() {
loader.unload();
done();
}));
@ -408,19 +408,19 @@ exports.testTabsEvent_onCloseWindow = function(assert, done) {
tabs.open({
url: "data:text/html;charset=utf-8,tab2",
onOpen: testCasePossiblyLoaded,
onClose: function() individualCloseCount++
onClose: () => individualCloseCount++
});
tabs.open({
url: "data:text/html;charset=utf-8,tab3",
onOpen: testCasePossiblyLoaded,
onClose: function() individualCloseCount++
onClose: () => individualCloseCount++
});
tabs.open({
url: "data:text/html;charset=utf-8,tab4",
onOpen: testCasePossiblyLoaded,
onClose: function() individualCloseCount++
onClose: () => individualCloseCount++
});
};

View File

@ -334,7 +334,7 @@ exports.testTabClose = function(assert, done) {
let secondOnCloseCalled = false;
// Bug 699450: Multiple calls to tab.close should not throw
tab.close(function() secondOnCloseCalled = true);
tab.close(() => secondOnCloseCalled = true);
try {
tab.close(function () {
assert.notEqual(tabs.activeTab.url, url, "tab is no longer the active tab");
@ -803,7 +803,7 @@ exports.testAttachOnMultipleDocuments = function (assert, done) {
if (onReadyCount == 1) {
worker1 = tab.attach({
contentScript: 'self.on("message", ' +
' function () self.postMessage(document.location.href)' +
' function () { return self.postMessage(document.location.href); }' +
');',
onMessage: function (msg) {
assert.equal(msg, firstLocation,
@ -827,7 +827,7 @@ exports.testAttachOnMultipleDocuments = function (assert, done) {
worker2 = tab.attach({
contentScript: 'self.on("message", ' +
' function () self.postMessage(document.location.href)' +
' function () { return self.postMessage(document.location.href); }' +
');',
onMessage: function (msg) {
assert.equal(msg, secondLocation,

View File

@ -31,8 +31,8 @@ exports.testValidateOptionsNonempty = function (assert) {
exports.testValidateOptionsMap = function (assert) {
let val = apiUtils.validateOptions({ foo: 3, bar: 2 }, {
foo: { map: function (v) v * v },
bar: { map: function (v) undefined }
foo: { map: v => v * v },
bar: { map: v => undefined }
});
assert.deepEqual(val, { foo: 9, bar: undefined });
};
@ -46,21 +46,21 @@ exports.testValidateOptionsMapException = function (assert) {
exports.testValidateOptionsOk = function (assert) {
let val = apiUtils.validateOptions({ foo: 3, bar: 2, baz: 1 }, {
foo: { ok: function (v) v },
bar: { ok: function (v) v }
foo: { ok: v => v },
bar: { ok: v => v }
});
assert.deepEqual(val, { foo: 3, bar: 2 });
assert.throws(
function () apiUtils.validateOptions({ foo: 2, bar: 2 }, {
bar: { ok: function (v) v > 2 }
() => apiUtils.validateOptions({ foo: 2, bar: 2 }, {
bar: { ok: v => v > 2 }
}),
/^The option "bar" is invalid/,
"ok should raise exception on invalid option"
);
assert.throws(
function () apiUtils.validateOptions(null, { foo: { ok: function (v) v }}),
() => apiUtils.validateOptions(null, { foo: { ok: v => v }}),
/^The option "foo" is invalid/,
"ok should raise exception on invalid option"
);
@ -92,7 +92,7 @@ exports.testValidateOptionsIs = function (assert) {
assert.deepEqual(val, opts);
assert.throws(
function () apiUtils.validateOptions(null, {
() => apiUtils.validateOptions(null, {
foo: { is: ["object", "number"] }
}),
/^The option "foo" must be one of the following types: object, number/,
@ -223,9 +223,9 @@ exports.testValidateOptionsMapIsOk = function (assert) {
let [map, is, ok] = [false, false, false];
let val = apiUtils.validateOptions({ foo: 1337 }, {
foo: {
map: function (v) v.toString(),
map: v => v.toString(),
is: ["string"],
ok: function (v) v.length > 0
ok: v => v.length > 0
}
});
assert.deepEqual(val, { foo: "1337" });
@ -233,11 +233,11 @@ exports.testValidateOptionsMapIsOk = function (assert) {
let requirements = {
foo: {
is: ["object"],
ok: function () assert.fail("is should have caused us to throw by now")
ok: () => assert.fail("is should have caused us to throw by now")
}
};
assert.throws(
function () apiUtils.validateOptions(null, requirements),
() => apiUtils.validateOptions(null, requirements),
/^The option "foo" must be one of the following types: object/,
"is should be used before ok is called"
);
@ -245,8 +245,8 @@ exports.testValidateOptionsMapIsOk = function (assert) {
exports.testValidateOptionsErrorMsg = function (assert) {
assert.throws(
function () apiUtils.validateOptions(null, {
foo: { ok: function (v) v, msg: "foo!" }
() => apiUtils.validateOptions(null, {
foo: { ok: v => v, msg: "foo!" }
}),
/^foo!/,
"ok should raise exception with customized message"
@ -256,14 +256,14 @@ exports.testValidateOptionsErrorMsg = function (assert) {
exports.testValidateMapWithMissingKey = function (assert) {
let val = apiUtils.validateOptions({ }, {
foo: {
map: function (v) v || "bar"
map: v => v || "bar"
}
});
assert.deepEqual(val, { foo: "bar" });
val = apiUtils.validateOptions({ }, {
foo: {
map: function (v) { throw "bar" }
map: v => { throw "bar" }
}
});
assert.deepEqual(val, { });
@ -275,7 +275,7 @@ exports.testValidateMapWithMissingKeyAndThrown = function (assert) {
map: function(v) { throw "bar" }
},
baz: {
map: function(v) "foo"
map: v => "foo"
}
});
assert.deepEqual(val, { baz: "foo" });

View File

@ -57,7 +57,9 @@ exports["test browser events ignore other wins"] = function(assert, done) {
let actualBrowser = [];
let actualWindow = [];
function browserEventHandler(e) actualBrowser.push(e)
function browserEventHandler(e) {
return actualBrowser.push(e);
}
on(browserEvents, "data", browserEventHandler);
on(windowEvents, "data", function handler(e) {
actualWindow.push(e);

View File

@ -22,7 +22,7 @@ exports.testWriteRead = function (assert) {
stream.write(str);
stream.close();
assert.ok(stream.closed, "Stream should be closed after stream.close");
assert.throws(function () stream.write("This shouldn't be written!"),
assert.throws(() => stream.write("This shouldn't be written!"),
STREAM_CLOSED_ERROR,
"stream.write after close should raise error");
@ -34,7 +34,7 @@ exports.testWriteRead = function (assert) {
"stream.read at EOS should return empty string");
stream.close();
assert.ok(stream.closed, "Stream should be closed after stream.close");
assert.throws(function () stream.read(),
assert.throws(() => stream.read(),
STREAM_CLOSED_ERROR,
"stream.read after close should raise error");

View File

@ -32,10 +32,10 @@ var when = curry(function(options, tab) {
return promise;
});
var use = function(value) function() value;
var use = use = value => () => value;
var open = curry(function(url, window) openTab(window, url));
var open = curry((url, window) => openTab(window, url));
var close = function(tab) {
let promise = when("pagehide", tab);
closeTab(tab);

View File

@ -634,8 +634,12 @@ exports["test Prototype Inheritance"] = createProxyTest("", function (helper) {
exports["test Functions"] = createProxyTest("", function (helper) {
helper.rawWindow.callFunction = function callFunction(f) f();
helper.rawWindow.isEqual = function isEqual(a, b) a == b;
helper.rawWindow.callFunction = function callFunction(f) {
return f();
};
helper.rawWindow.isEqual = function isEqual(a, b) {
return a == b;
};
// bug 784116: workaround in order to allow proxy code to cache proxies on
// these functions:
helper.rawWindow.callFunction.__exposedProps__ = {__proxy: 'rw'};

View File

@ -441,7 +441,7 @@ exports.testPageReload = function (assert, done) {
let item = loader.cm.Item({
label: "Item",
contentScript: "var doc = document; self.on('context', function(node) doc.body.getAttribute('showItem') == 'true');"
contentScript: "var doc = document; self.on('context', node => doc.body.getAttribute('showItem') == 'true');"
});
test.withTestDoc(function (window, doc) {
@ -525,7 +525,7 @@ exports.testContentContextMatch = function (assert, done) {
let item = new loader.cm.Item({
label: "item",
contentScript: 'self.on("context", function () true);'
contentScript: 'self.on("context", () => true);'
});
test.showMenu(null, function (popup) {
@ -543,7 +543,7 @@ exports.testContentContextNoMatch = function (assert, done) {
let item = new loader.cm.Item({
label: "item",
contentScript: 'self.on("context", function () false);'
contentScript: 'self.on("context", () => false);'
});
test.showMenu(null, function (popup) {
@ -579,7 +579,7 @@ exports.testContentContextEmptyString = function (assert, done) {
let item = new loader.cm.Item({
label: "item",
contentScript: 'self.on("context", function () "");'
contentScript: 'self.on("context", () => "");'
});
test.showMenu(null, function (popup) {
@ -598,8 +598,8 @@ exports.testMultipleContentContextMatch1 = function (assert, done) {
let item = new loader.cm.Item({
label: "item",
contentScript: 'self.on("context", function () true); ' +
'self.on("context", function () false);',
contentScript: 'self.on("context", () => true); ' +
'self.on("context", () => false);',
onMessage: function() {
test.fail("Should not have called the second context listener");
}
@ -620,8 +620,8 @@ exports.testMultipleContentContextMatch2 = function (assert, done) {
let item = new loader.cm.Item({
label: "item",
contentScript: 'self.on("context", function () false); ' +
'self.on("context", function () true);'
contentScript: 'self.on("context", () => false); ' +
'self.on("context", () => true);'
});
test.showMenu(null, function (popup) {
@ -639,8 +639,8 @@ exports.testMultipleContentContextString1 = function (assert, done) {
let item = new loader.cm.Item({
label: "item",
contentScript: 'self.on("context", function () "new label"); ' +
'self.on("context", function () false);'
contentScript: 'self.on("context", () => "new label"); ' +
'self.on("context", () => false);'
});
test.showMenu(null, function (popup) {
@ -659,8 +659,8 @@ exports.testMultipleContentContextString2 = function (assert, done) {
let item = new loader.cm.Item({
label: "item",
contentScript: 'self.on("context", function () false); ' +
'self.on("context", function () "new label");'
contentScript: 'self.on("context", () => false); ' +
'self.on("context", () => "new label");'
});
test.showMenu(null, function (popup) {
@ -678,8 +678,8 @@ exports.testMultipleContentContextString3 = function (assert, done) {
let item = new loader.cm.Item({
label: "item",
contentScript: 'self.on("context", function () "new label 1"); ' +
'self.on("context", function () "new label 2");'
contentScript: 'self.on("context", () => "new label 1"); ' +
'self.on("context", () => "new label 2");'
});
test.showMenu(null, function (popup) {
@ -699,23 +699,23 @@ exports.testContentContextMatchActiveElement = function (assert, done) {
let items = [
new loader.cm.Item({
label: "item 1",
contentScript: 'self.on("context", function () true);'
contentScript: 'self.on("context", () => true);'
}),
new loader.cm.Item({
label: "item 2",
context: undefined,
contentScript: 'self.on("context", function () true);'
contentScript: 'self.on("context", () => true);'
}),
// These items will always be hidden by the declarative usage of PageContext
new loader.cm.Item({
label: "item 3",
context: loader.cm.PageContext(),
contentScript: 'self.on("context", function () true);'
contentScript: 'self.on("context", () => true);'
}),
new loader.cm.Item({
label: "item 4",
context: [loader.cm.PageContext()],
contentScript: 'self.on("context", function () true);'
contentScript: 'self.on("context", () => true);'
})
];
@ -737,23 +737,23 @@ exports.testContentContextNoMatchActiveElement = function (assert, done) {
let items = [
new loader.cm.Item({
label: "item 1",
contentScript: 'self.on("context", function () false);'
contentScript: 'self.on("context", () => false);'
}),
new loader.cm.Item({
label: "item 2",
context: undefined,
contentScript: 'self.on("context", function () false);'
contentScript: 'self.on("context", () => false);'
}),
// These items will always be hidden by the declarative usage of PageContext
new loader.cm.Item({
label: "item 3",
context: loader.cm.PageContext(),
contentScript: 'self.on("context", function () false);'
contentScript: 'self.on("context", () => false);'
}),
new loader.cm.Item({
label: "item 4",
context: [loader.cm.PageContext()],
contentScript: 'self.on("context", function () false);'
contentScript: 'self.on("context", () => false);'
})
];
@ -775,23 +775,23 @@ exports.testContentContextNoMatchActiveElement = function (assert, done) {
let items = [
new loader.cm.Item({
label: "item 1",
contentScript: 'self.on("context", function () {});'
contentScript: 'self.on("context", () => {});'
}),
new loader.cm.Item({
label: "item 2",
context: undefined,
contentScript: 'self.on("context", function () {});'
contentScript: 'self.on("context", () => {});'
}),
// These items will always be hidden by the declarative usage of PageContext
new loader.cm.Item({
label: "item 3",
context: loader.cm.PageContext(),
contentScript: 'self.on("context", function () {});'
contentScript: 'self.on("context", () => {});'
}),
new loader.cm.Item({
label: "item 4",
context: [loader.cm.PageContext()],
contentScript: 'self.on("context", function () {});'
contentScript: 'self.on("context", () => {});'
})
];
@ -812,7 +812,7 @@ exports.testContentContextMatchString = function (assert, done) {
let item = new loader.cm.Item({
label: "first label",
contentScript: 'self.on("context", function () "second label");'
contentScript: 'self.on("context", () => "second label");'
});
test.showMenu(null, function (popup) {
@ -2213,7 +2213,7 @@ exports.testLoadWithOpenTab = function (assert, done) {
let item = new loader.cm.Item({
label: "item",
contentScript:
'self.on("click", function () self.postMessage("click"));',
'self.on("click", () => self.postMessage("click"));',
onMessage: function (msg) {
if (msg === "click")
test.done();
@ -2643,19 +2643,19 @@ exports.testItemNoData = function (assert, done) {
let item1 = new loader.cm.Item({
label: "item 1",
contentScript: 'self.on("click", function(node, data) self.postMessage(data))',
contentScript: 'self.on("click", (node, data) => self.postMessage(data))',
onMessage: checkData
});
let item2 = new loader.cm.Item({
label: "item 2",
data: null,
contentScript: 'self.on("click", function(node, data) self.postMessage(data))',
contentScript: 'self.on("click", (node, data) => self.postMessage(data))',
onMessage: checkData
});
let item3 = new loader.cm.Item({
label: "item 3",
data: undefined,
contentScript: 'self.on("click", function(node, data) self.postMessage(data))',
contentScript: 'self.on("click", (node, data) => self.postMessage(data))',
onMessage: checkData
});
@ -2892,7 +2892,7 @@ exports.testSubItemContextNoMatchHideMenu = function (assert, done) {
items: [
loader.cm.Item({
label: "subitem 2",
contentScript: 'self.on("context", function () false);'
contentScript: 'self.on("context", () => false);'
})
]
}),
@ -2905,7 +2905,7 @@ exports.testSubItemContextNoMatchHideMenu = function (assert, done) {
}),
loader.cm.Item({
label: "subitem 4",
contentScript: 'self.on("context", function () false);'
contentScript: 'self.on("context", () => false);'
})
]
})
@ -2931,7 +2931,7 @@ exports.testSubItemContextMatch = function (assert, done) {
}),
loader.cm.Item({
label: "subitem 6",
contentScript: 'self.on("context", function () false);'
contentScript: 'self.on("context", () => false);'
})
];
@ -2950,7 +2950,7 @@ exports.testSubItemContextMatch = function (assert, done) {
items: [
loader.cm.Item({
label: "subitem 2",
contentScript: 'self.on("context", function () true);'
contentScript: 'self.on("context", () => true);'
})
]
}),
@ -2960,7 +2960,7 @@ exports.testSubItemContextMatch = function (assert, done) {
hiddenItems[0],
loader.cm.Item({
label: "subitem 4",
contentScript: 'self.on("context", function () true);'
contentScript: 'self.on("context", () => true);'
})
]
}),
@ -2983,7 +2983,7 @@ exports.testSubItemContextMatch = function (assert, done) {
}),
loader.cm.Item({
label: "subitem 8",
contentScript: 'self.on("context", function () true);'
contentScript: 'self.on("context", () => true);'
})
]
})

View File

@ -71,7 +71,9 @@ exports['test no side-effects in emit'] = function(assert) {
exports['test can remove next listener'] = function(assert) {
let target = { name: 'target' };
function fail() assert.fail('Listener should be removed');
function fail() {
return assert.fail('Listener should be removed');
};
on(target, 'data', function() {
assert.pass('first litener called');

View File

@ -7,16 +7,20 @@ const { on, emit } = require("sdk/event/core");
const { filter, map, merge, expand, pipe, stripListeners } = require("sdk/event/utils");
const $ = require("./event/helpers");
function isEven(x) !(x % 2)
function inc(x) x + 1
function isEven(x) {
return !(x % 2);
}
function inc(x) {
return x + 1;
}
exports["test filter events"] = function(assert) {
let input = {};
let evens = filter(input, isEven);
let actual = [];
on(evens, "data", function(e) actual.push(e));
on(evens, "data", e => actual.push(e));
[1, 2, 3, 4, 5, 6, 7].forEach(function(x) emit(input, "data", x));
[1, 2, 3, 4, 5, 6, 7].forEach(x => emit(input, "data", x));
assert.deepEqual(actual, [2, 4, 6], "only even numbers passed through");
};
@ -45,9 +49,9 @@ exports["test map events"] = function(assert) {
let input = {};
let incs = map(input, inc);
let actual = [];
on(incs, "data", function(e) actual.push(e));
on(incs, "data", e => actual.push(e));
[1, 2, 3, 4].forEach(function(x) emit(input, "data", x));
[1, 2, 3, 4].forEach(x => emit(input, "data", x));
assert.deepEqual(actual, [2, 3, 4, 5], "all numbers were incremented");
};
@ -77,7 +81,7 @@ exports["test merge stream[stream]"] = function(assert) {
let inputs = {};
let actual = [];
on(merge(inputs), "data", function($) actual.push($))
on(merge(inputs), "data", $ => actual.push($))
emit(inputs, "data", a);
emit(a, "data", "a1");
@ -99,7 +103,7 @@ exports["test merge array[stream]"] = function(assert) {
let inputs = {};
let actual = [];
on(merge([a, b, c]), "data", function($) actual.push($))
on(merge([a, b, c]), "data", $ => actual.push($))
emit(a, "data", "a1");
emit(b, "data", "b1");
@ -147,14 +151,14 @@ exports["test expand"] = function(assert) {
let inputs = {};
let actual = [];
on(expand(inputs, function($) $()), "data", function($) actual.push($))
on(expand(inputs, $ => $()), "data", $ => actual.push($))
emit(inputs, "data", function() a);
emit(inputs, "data", () => a);
emit(a, "data", "a1");
emit(inputs, "data", function() b);
emit(inputs, "data", () => b);
emit(b, "data", "b1");
emit(a, "data", "a2");
emit(inputs, "data", function() c);
emit(inputs, "data", () => c);
emit(c, "data", "c1");
emit(c, "data", "c2");
emit(b, "data", "b2");

View File

@ -233,7 +233,7 @@ exports.testMkpathExistingNondirectory = function (assert) {
var fname = file.join(profilePath, 'conflict.txt');
file.open(fname, "w").close();
assert.ok(file.exists(fname), "File should exist");
assert.throws(function() file.mkpath(fname),
assert.throws(() => file.mkpath(fname),
/^The path already exists and is not a directory: .+$/,
"mkpath on file should raise error");
file.remove(fname);
@ -248,7 +248,7 @@ exports.testRmdirNondirectory = function (assert) {
}, ERRORS.NOT_A_DIRECTORY, "rmdir on file should raise error");
file.remove(fname);
assert.ok(!file.exists(fname), "File should not exist");
assert.throws(function () file.rmdir(fname),
assert.throws(() => file.rmdir(fname),
ERRORS.FILE_NOT_FOUND,
"rmdir on non-existing file should raise error");
};
@ -263,7 +263,7 @@ exports.testRmdirNonempty = function (assert) {
file.open(filePath, "w").close();
assert.ok(file.exists(filePath),
"Sanity check: path should exist: " + filePath);
assert.throws(function () file.rmdir(path),
assert.throws(() => file.rmdir(path),
/^The directory is not empty: .+$/,
"rmdir on non-empty directory should raise error");
file.remove(filePath);

View File

@ -86,32 +86,32 @@ exports.testMatchPatternTestFalse = function(assert) {
exports.testMatchPatternErrors = function(assert) {
assert.throws(
function() new MatchPattern("*.google.com/*"),
() => new MatchPattern("*.google.com/*"),
/There can be at most one/,
"MatchPattern throws when supplied multiple '*'"
);
assert.throws(
function() new MatchPattern("google.com"),
() => new MatchPattern("google.com"),
/expected to be either an exact URL/,
"MatchPattern throws when the wildcard doesn't use '*' and doesn't " +
"look like a URL"
);
assert.throws(
function() new MatchPattern("http://google*.com"),
() => new MatchPattern("http://google*.com"),
/expected to be the first or the last/,
"MatchPattern throws when a '*' is in the middle of the wildcard"
);
assert.throws(
function() new MatchPattern(/ /g),
() => new MatchPattern(/ /g),
/^A RegExp match pattern cannot be set to `global` \(i\.e\. \/\/g\)\.$/,
"MatchPattern throws on a RegExp set to `global` (i.e. //g)."
);
assert.throws(
function() new MatchPattern( / /m ),
() => new MatchPattern( / /m ),
/^A RegExp match pattern cannot be set to `multiline` \(i\.e\. \/\/m\)\.$/,
"MatchPattern throws on a RegExp set to `multiline` (i.e. //m)."
);

View File

@ -68,9 +68,9 @@ exports.testUnwrappedDOM = function(assert, done) {
let page = Page({
allow: { script: true },
contentURL: "data:text/html;charset=utf-8,<script>document.getElementById=3;window.scrollTo=3;</script>",
contentScript: "window.addEventListener('load', function () " +
"self.postMessage([typeof(unsafeWindow.document.getElementById), " +
"typeof(unsafeWindow.scrollTo)]), true)",
contentScript: "window.addEventListener('load', function () {" +
"return self.postMessage([typeof(unsafeWindow.document.getElementById), " +
"typeof(unsafeWindow.scrollTo)]); }, true)",
onMessage: function (message) {
assert.equal(message[0],
"number",
@ -95,7 +95,7 @@ exports.testPageProperties = function(assert) {
assert.ok(prop in page, prop + " property is defined on page.");
}
assert.ok(function () page.postMessage("foo") || true,
assert.ok(() => page.postMessage("foo") || true,
"postMessage doesn't throw exception on page.");
}
@ -151,13 +151,13 @@ exports.testAutoDestructor = function(assert, done) {
exports.testValidateOptions = function(assert) {
assert.throws(
function () Page({ contentURL: 'home' }),
() => Page({ contentURL: 'home' }),
/The `contentURL` option must be a valid URL\./,
"Validation correctly denied a non-URL contentURL"
);
assert.throws(
function () Page({ onMessage: "This is not a function."}),
() => Page({ onMessage: "This is not a function."}),
/The option "onMessage" must be one of the following types: function/,
"Validation correctly denied a non-function onMessage."
);
@ -345,7 +345,7 @@ exports.testGetActiveViewAndDestroy = function(assert) {
exports.testPingPong = function(assert, done) {
let page = Page({
contentURL: 'data:text/html;charset=utf-8,ping-pong',
contentScript: 'self.on("message", function(message) self.postMessage("pong"));'
contentScript: 'self.on("message", message => self.postMessage("pong"));'
+ 'self.postMessage("ready");',
onMessage: function(message) {
if ('ready' == message) {

View File

@ -52,7 +52,7 @@ exports["test Panel"] = function(assert, done) {
let panel = Panel({
contentURL: "about:buildconfig",
contentScript: "self.postMessage(1); self.on('message', function() self.postMessage(2));",
contentScript: "self.postMessage(1); self.on('message', () => self.postMessage(2));",
onMessage: function (message) {
assert.equal(this, panel, "The 'this' object is the panel.");
switch(message) {
@ -77,7 +77,7 @@ exports["test Panel Emit"] = function(assert, done) {
contentURL: "about:buildconfig",
contentScript: "self.port.emit('loaded');" +
"self.port.on('addon-to-content', " +
" function() self.port.emit('received'));",
" () => self.port.emit('received'));",
});
panel.port.on("loaded", function () {
assert.pass("The panel was loaded and sent a first event.");
@ -96,7 +96,7 @@ exports["test Panel Emit Early"] = function(assert, done) {
let panel = Panel({
contentURL: "about:buildconfig",
contentScript: "self.port.on('addon-to-content', " +
" function() self.port.emit('received'));",
" () => self.port.emit('received'));",
});
panel.port.on("received", function () {
assert.pass("The panel posted a message early and received a response.");
@ -148,7 +148,7 @@ exports["test Document Reload"] = function(assert, done) {
contentURL: URL("data:text/html;charset=utf-8," + encodeURIComponent(content)),
contentScript: "self.postMessage(window.location.href);" +
// initiate change to url2
"self.port.once('move', function() document.defaultView.postMessage('move', '*'));",
"self.port.once('move', () => document.defaultView.postMessage('move', '*'));",
onMessage: function (message) {
messageCount++;
assert.notEqual(message, "about:blank", "about:blank is not a message " + messageCount);
@ -533,7 +533,7 @@ exports["test Automatic Destroy"] = function(assert) {
let panel = loader.require("sdk/panel").Panel({
contentURL: "about:buildconfig",
contentScript:
"self.port.on('event', function() self.port.emit('event-back'));"
"self.port.on('event', () => self.port.emit('event-back'));"
});
loader.unload();
@ -585,7 +585,7 @@ exports["test Content URL Option"] = function(assert) {
assert.ok(panel.contentURL == null, "contentURL is undefined.");
panel.destroy();
assert.throws(function () Panel({ contentURL: "foo" }),
assert.throws(() => Panel({ contentURL: "foo" }),
/The `contentURL` option must be a valid URL./,
"Panel throws an exception if contentURL is not a URL.");
};

View File

@ -73,7 +73,7 @@ exports.testPlainTextConsole = function(assert) {
"PlainTextConsole.log() must stringify null.");
// TODO: Fix console.jsm to detect custom toString.
con.log("testing", { toString: function() "obj.toString()" });
con.log("testing", { toString: () => "obj.toString()" });
assert.equal(lastPrint(), "console.log: " + name + ": testing {}\n",
"PlainTextConsole.log() doesn't printify custom toString.");

View File

@ -41,7 +41,7 @@ exports.testRemove = function (test, done) {
else done();
}
});
urls.forEach(function (url) rules.add(url));
urls.forEach(url => rules.add(url));
rules.remove(urls[0]);
};

View File

@ -43,7 +43,7 @@ exports['test non-privileged'] = function(assert) {
exports['test injection'] = function(assert) {
let fixture = sandbox();
fixture.hi = function(name) 'Hi ' + name
fixture.hi = name => 'Hi ' + name;
assert.equal(evaluate(fixture, 'hi("sandbox");'), 'Hi sandbox',
'injected functions are callable');
};
@ -100,7 +100,7 @@ exports['test load'] = function(assert) {
};
exports['test load with data: URL'] = function(assert) {
let code = "var a = 1; this.b = 2; function f() 4";
let code = "var a = 1; this.b = 2; function f() { return 4; }";
let fixture = sandbox();
load(fixture, "data:," + encodeURIComponent(code));

View File

@ -284,7 +284,7 @@ exports.testSetNoSetRead = function (assert, done) {
function setGetRoot(assert, done, val, compare) {
compare = compare || function (a, b) a === b;
compare = compare || (a, b) => a === b;
// Load the module once, set a value.
let loader = Loader(module);
@ -312,7 +312,7 @@ function setGetRootError(assert, done, val, msg) {
"array, boolean, null, number, object, string");
let loader = Loader(module);
let ss = loader.require("sdk/simple-storage");
assert.throws(function () ss.storage = val, pred, msg);
assert.throws(() => ss.storage = val, pred, msg);
done();
loader.unload();
}

View File

@ -209,7 +209,7 @@ exports.testAttachOnMultipleDocuments_alt = function (assert, done) {
if (onReadyCount == 1) {
worker1 = tab.attach({
contentScript: 'self.on("message", ' +
' function () self.postMessage(document.location.href)' +
' () => self.postMessage(document.location.href)' +
');',
onMessage: function (msg) {
assert.equal(msg, firstLocation,
@ -232,7 +232,7 @@ exports.testAttachOnMultipleDocuments_alt = function (assert, done) {
else if (onReadyCount == 2) {
worker2 = tab.attach({
contentScript: 'self.on("message", ' +
' function () self.postMessage(document.location.href)' +
' () => self.postMessage(document.location.href)' +
');',
onMessage: function (msg) {
assert.equal(msg, secondLocation,
@ -288,7 +288,7 @@ exports.testAttachWrappers_alt = function (assert, done) {
onMessage: function (msg) {
assert.equal(msg, true, "Worker has wrapped objects ("+count+")");
if (count++ == 1)
tab.close(function() done());
tab.close(() => done());
}
});
}
@ -325,11 +325,11 @@ exports.testActiveWindowActiveTabOnActivate_alt = function(assert, done) {
tabs.open({
url: URL.replace("#title#", "tabs.open1"),
onOpen: function(tab) newTabs.push(tab)
onOpen: tab => newTabs.push(tab)
});
tabs.open({
url: URL.replace("#title#", "tabs.open2"),
onOpen: function(tab) newTabs.push(tab)
onOpen: tab => newTabs.push(tab)
});
};
@ -454,7 +454,7 @@ exports.testTabReload = function(assert, done) {
assert.pass("the tab was loaded again");
assert.equal(tab.url, url, "the tab has the same URL");
tab.close(function() done());
tab.close(() => done());
}
);
@ -498,8 +498,12 @@ exports.testOnPageShowEvent = function (assert, done) {
}
}
function onOpen () events.push('open');
function onReady () events.push('ready');
function onOpen () {
return events.push('open');
}
function onReady () {
return events.push('ready');
}
tabs.on('pageshow', onPageShow);
tabs.on('open', onOpen);
@ -544,8 +548,12 @@ exports.testOnPageShowEventDeclarative = function (assert, done) {
}
}
function onOpen () events.push('open');
function onReady () events.push('ready');
function onOpen () {
return events.push('open');
}
function onReady () {
return events.push('ready');
}
tabs.open({
url: firstUrl,

View File

@ -21,10 +21,10 @@ exports.testWriteRead = function (assert) {
stream.write(str);
stream.close();
assert.ok(stream.closed, "stream.closed after close should be true");
assert.throws(function () stream.close(),
assert.throws(() => stream.close(),
STREAM_CLOSED_ERROR,
"stream.close after already closed should raise error");
assert.throws(function () stream.write("This shouldn't be written!"),
assert.throws(() => stream.write("This shouldn't be written!"),
STREAM_CLOSED_ERROR,
"stream.write after close should raise error");
@ -37,10 +37,10 @@ exports.testWriteRead = function (assert) {
"stream.read at EOS should return empty string");
stream.close();
assert.ok(stream.closed, "stream.closed after close should be true");
assert.throws(function () stream.close(),
assert.throws(() => stream.close(),
STREAM_CLOSED_ERROR,
"stream.close after already closed should raise error");
assert.throws(function () stream.read(),
assert.throws(() => stream.read(),
STREAM_CLOSED_ERROR,
"stream.read after close should raise error");
@ -116,10 +116,10 @@ exports.testWriteAsync = function (assert, done) {
assert.equal(err, undefined,
"stream.writeAsync should not cause error");
assert.ok(stream.closed, "stream.closed after write should be true");
assert.throws(function () stream.close(),
assert.throws(() => stream.close(),
STREAM_CLOSED_ERROR,
"stream.close after already closed should raise error");
assert.throws(function () stream.writeAsync("This shouldn't work!"),
assert.throws(() => stream.writeAsync("This shouldn't work!"),
STREAM_CLOSED_ERROR,
"stream.writeAsync after close should raise error");

View File

@ -47,8 +47,8 @@ exports.testATeardownAsyncTestPart2 = function(test) {
exports.testWaitUntilInstant = function(test) {
test.waitUntilDone();
test.waitUntil(function () true, "waitUntil with instant true pass")
.then(function () test.done());
test.waitUntil(() => true, "waitUntil with instant true pass")
.then(() => test.done());
}
exports.testWaitUntil = function(test) {
@ -167,7 +167,7 @@ exports.testWaitUntilTimeoutInCallback = function(test) {
name: "wait4ever",
testFunction: function(test) {
test.waitUntilDone(100);
test.waitUntil(function() false);
test.waitUntil(() => false);
}
},
onDone: function() {}

View File

@ -175,13 +175,13 @@ exports.testFromFilename = function(assert) {
exports.testURL = function(assert) {
assert.ok(URL('h:foo') instanceof URL, 'instance is of correct type');
assert.throws(function() URL(),
assert.throws(() => URL(),
/malformed URI: undefined/i,
'url.URL should throw on undefined');
assert.throws(function() URL(''),
assert.throws(() => URL(''),
/malformed URI: /i,
'url.URL should throw on empty string');
assert.throws(function() URL('foo'),
assert.throws(() => URL('foo'),
/malformed URI: foo/i,
'url.URL should throw on invalid URI');
assert.ok(URL('h:foo').scheme, 'has scheme');
@ -193,7 +193,7 @@ exports.testURL = function(assert) {
'http://foo/mypath',
'relative URL resolved to base');
// test relative + no base
assert.throws(function() URL('path').toString(),
assert.throws(() => URL('path').toString(),
/malformed URI: path/i,
'no base for relative URI should throw');
@ -343,7 +343,7 @@ exports.testWindowLocationMatch = function (assert, done) {
assert.equal(urlObject[prop], loc[prop], prop + ' matches');
}
tab.close(function() server.stop(done));
tab.close(() => server.stop(done));
},
contentScript: '(' + function () {
let res = {};

View File

@ -174,7 +174,7 @@ exports['test window watcher without untracker'] = function(assert, done) {
exports['test active window'] = function(assert, done) {
let browserWindow = WM.getMostRecentWindow("navigator:browser");
let continueAfterFocus = function(window) onFocus(window).then(nextTest);
let continueAfterFocus = window => onFocus(window).then(nextTest);
assert.equal(windowUtils.activeBrowserWindow, browserWindow,
"Browser window is the active browser window.");

View File

@ -57,7 +57,9 @@ exports['test implement xpcom interfaces'] = function(assert) {
exports['test implement factory without contract'] = function(assert) {
let actual = xpcom.Factory({
get wrappedJSObject() this,
get wrappedJSObject() {
return this;
},
});
assert.ok(isCIDRegistered(actual.id), 'factory is regiseterd');
@ -69,7 +71,9 @@ exports['test implement xpcom factory'] = function(assert) {
let Component = Class({
extends: xpcom.Unknown,
interfaces: [ 'nsIObserver' ],
get wrappedJSObject() this,
get wrappedJSObject() {
return this;
},
observe: function() {}
});
@ -100,7 +104,9 @@ exports['test implement xpcom service'] = function(assert) {
Component: Class({
extends: xpcom.Unknown,
interfaces: [ 'nsIObserver'],
get wrappedJSObject() this,
get wrappedJSObject() {
return this;
},
observe: function() {},
name: 'my-service'
})
@ -127,7 +133,9 @@ function testRegister(assert, text) {
register: false,
Component: Class({
extends: xpcom.Unknown,
get wrappedJSObject() this,
get wrappedJSObject() {
return this;
},
interfaces: [ 'nsIAboutModule' ],
newChannel : function(aURI, aLoadInfo) {
var ios = Cc["@mozilla.org/network/io-service;1"].