From 55313b4bc93da3860c3b8ad1aa1a67bceb2577ae Mon Sep 17 00:00:00 2001 From: Iris Hsiao Date: Fri, 13 Jan 2017 11:06:43 +0800 Subject: [PATCH] Backed out changeset 7e0a0bd74199 (bug 1330014) --- .eslintignore | 6 - services/.eslintrc.js | 29 ---- services/cloudsync/CloudSync.jsm | 24 ++-- services/cloudsync/CloudSyncAdapters.jsm | 22 +-- services/cloudsync/CloudSyncBookmarks.jsm | 116 +++++++-------- .../CloudSyncBookmarksFolderCache.jsm | 18 +-- services/cloudsync/CloudSyncEventSource.jsm | 16 +-- services/cloudsync/CloudSyncLocal.jsm | 6 +- services/cloudsync/CloudSyncPlacesWrapper.jsm | 62 ++++---- services/cloudsync/CloudSyncTabs.jsm | 58 ++++---- .../tests/mochitest/browser_tabEvents.js | 14 +- services/cloudsync/tests/xpcshell/head.js | 2 +- .../tests/xpcshell/test_bookmarks.js | 20 +-- .../cloudsync/tests/xpcshell/test_module.js | 4 +- .../cloudsync/tests/xpcshell/test_tabs.js | 10 +- services/common/async.js | 2 +- services/common/blocklist-clients.js | 10 +- services/common/hawkclient.js | 22 +-- services/common/hawkrequest.js | 12 +- services/common/kinto-storage-adapter.js | 11 +- .../common/modules-testing/storageserver.js | 28 ++-- services/common/observers.js | 23 +-- services/common/rest.js | 16 +-- services/common/stringbundle.js | 11 +- services/common/tests/unit/head_helpers.js | 2 +- .../common/tests/unit/test_async_chain.js | 8 +- .../tests/unit/test_async_querySpinningly.js | 4 +- .../tests/unit/test_blocklist_certificates.js | 10 +- .../tests/unit/test_blocklist_clients.js | 18 +-- .../tests/unit/test_blocklist_pinning.js | 20 +-- .../tests/unit/test_blocklist_signatures.js | 12 +- .../tests/unit/test_blocklist_updater.js | 8 +- services/common/tests/unit/test_hawkclient.js | 16 +-- .../common/tests/unit/test_hawkrequest.js | 10 +- services/common/tests/unit/test_kinto.js | 18 +-- .../common/tests/unit/test_load_modules.js | 4 +- services/common/tests/unit/test_observers.js | 4 +- .../common/tests/unit/test_restrequest.js | 70 ++++----- .../common/tests/unit/test_storage_adapter.js | 4 +- .../common/tests/unit/test_storage_server.js | 10 +- .../unit/test_tokenauthenticatedrequest.js | 4 +- .../tests/unit/test_tokenserverclient.js | 10 +- .../tests/unit/test_utils_convert_string.js | 26 ++-- .../tests/unit/test_utils_encodeBase64URL.js | 2 +- services/common/tests/unit/test_utils_json.js | 2 +- .../tests/unit/test_utils_namedTimer.js | 2 +- services/common/tokenserverclient.js | 8 +- services/common/utils.js | 26 ++-- .../crypto/component/tests/unit/test_jpake.js | 6 +- services/crypto/modules/WeaveCrypto.js | 4 +- services/crypto/modules/utils.js | 81 +++++------ services/crypto/tests/unit/head_helpers.js | 5 +- services/crypto/tests/unit/test_utils_hawk.js | 18 +-- .../crypto/tests/unit/test_utils_httpmac.js | 4 +- .../crypto/tests/unit/test_utils_pbkdf2.js | 48 +++---- services/fxaccounts/Credentials.jsm | 20 +-- services/fxaccounts/FxAccounts.jsm | 64 ++++----- services/fxaccounts/FxAccountsClient.jsm | 32 ++--- services/fxaccounts/FxAccountsManager.jsm | 56 ++++---- services/fxaccounts/FxAccountsOAuthClient.jsm | 12 +- .../fxaccounts/FxAccountsOAuthGrantClient.jsm | 16 +-- services/fxaccounts/FxAccountsProfile.jsm | 14 +- .../fxaccounts/FxAccountsProfileClient.jsm | 8 +- services/fxaccounts/FxAccountsPush.js | 2 +- services/fxaccounts/FxAccountsStorage.jsm | 12 +- services/fxaccounts/FxAccountsWebChannel.jsm | 2 +- .../tests/xpcshell/test_accounts.js | 87 ++++++------ .../test_accounts_device_registration.js | 46 +++--- .../fxaccounts/tests/xpcshell/test_client.js | 71 +++++----- .../tests/xpcshell/test_oauth_grant_client.js | 46 +++--- .../test_oauth_grant_client_server.js | 2 +- .../xpcshell/test_oauth_token_storage.js | 2 +- .../tests/xpcshell/test_oauth_tokens.js | 16 +-- .../fxaccounts/tests/xpcshell/test_profile.js | 60 ++++---- .../tests/xpcshell/test_profile_client.js | 58 ++++---- .../tests/xpcshell/test_push_service.js | 22 +-- .../tests/xpcshell/test_storage_manager.js | 6 +- .../tests/xpcshell/test_web_channel.js | 22 +-- services/sync/Weave.js | 10 +- services/sync/modules-testing/fakeservices.js | 2 +- services/sync/modules-testing/fxa_utils.js | 116 +++++++-------- services/sync/modules-testing/utils.js | 4 +- services/sync/modules/SyncedTabs.jsm | 2 +- services/sync/modules/addonsreconciler.js | 14 +- services/sync/modules/addonutils.js | 21 +-- services/sync/modules/bookmark_validator.js | 8 +- services/sync/modules/browserid_identity.js | 71 +++++----- services/sync/modules/collection_validator.js | 2 +- services/sync/modules/engines.js | 134 +++++++++--------- services/sync/modules/engines/addons.js | 6 +- services/sync/modules/engines/bookmarks.js | 24 ++-- services/sync/modules/engines/clients.js | 6 +- .../sync/modules/engines/extension-storage.js | 20 +-- services/sync/modules/engines/forms.js | 52 +++---- services/sync/modules/engines/history.js | 34 ++--- services/sync/modules/engines/passwords.js | 36 ++--- services/sync/modules/engines/prefs.js | 42 +++--- services/sync/modules/engines/tabs.js | 56 ++++---- services/sync/modules/identity.js | 22 +-- services/sync/modules/jpakeclient.js | 74 +++++----- services/sync/modules/main.js | 2 +- services/sync/modules/policies.js | 12 +- services/sync/modules/record.js | 44 +++--- services/sync/modules/resource.js | 11 +- services/sync/modules/service.js | 47 +++--- services/sync/modules/stages/declined.js | 10 +- services/sync/modules/stages/enginesync.js | 10 +- services/sync/modules/status.js | 4 +- services/sync/modules/telemetry.js | 4 +- services/sync/modules/userapi.js | 12 +- services/sync/modules/util.js | 31 ++-- services/sync/services-sync.js | 12 +- services/sync/tests/tps/mozmill_sanity.js | 2 +- services/sync/tests/tps/test_bug563989.js | 2 +- services/sync/tests/tps/test_bug575423.js | 4 +- services/sync/tests/tps/test_formdata.js | 2 +- services/sync/tests/tps/test_sync.js | 2 +- .../sync/tests/unit/fake_login_manager.js | 6 +- services/sync/tests/unit/head_helpers.js | 20 +-- services/sync/tests/unit/head_http_server.js | 52 +++---- services/sync/tests/unit/test_addon_utils.js | 10 +- .../sync/tests/unit/test_addons_engine.js | 2 +- services/sync/tests/unit/test_addons_store.js | 6 +- .../sync/tests/unit/test_addons_tracker.js | 4 +- .../tests/unit/test_bookmark_batch_fail.js | 3 +- .../sync/tests/unit/test_bookmark_duping.js | 2 +- .../sync/tests/unit/test_bookmark_engine.js | 24 ++-- .../unit/test_bookmark_smart_bookmarks.js | 2 +- .../sync/tests/unit/test_bookmark_store.js | 10 +- .../sync/tests/unit/test_bookmark_tracker.js | 8 +- .../tests/unit/test_bookmark_validator.js | 2 +- .../tests/unit/test_browserid_identity.js | 26 ++-- .../sync/tests/unit/test_clients_engine.js | 6 +- .../tests/unit/test_collections_recovery.js | 4 +- services/sync/tests/unit/test_corrupt_keys.js | 6 +- services/sync/tests/unit/test_engine.js | 12 +- services/sync/tests/unit/test_engine_abort.js | 4 +- .../sync/tests/unit/test_errorhandler_1.js | 4 +- .../sync/tests/unit/test_errorhandler_2.js | 14 +- .../sync/tests/unit/test_errorhandler_eol.js | 2 +- .../tests/unit/test_errorhandler_filelog.js | 22 +-- ...test_errorhandler_sync_checkServerError.js | 8 +- .../unit/test_extension_storage_crypto.js | 7 +- .../sync/tests/unit/test_forms_tracker.js | 4 +- .../sync/tests/unit/test_fxa_migration.js | 2 +- .../tests/unit/test_fxa_node_reassignment.js | 6 +- .../sync/tests/unit/test_history_engine.js | 6 +- services/sync/tests/unit/test_hmac_error.js | 10 +- .../sync/tests/unit/test_httpd_sync_server.js | 46 +++--- .../sync/tests/unit/test_interval_triggers.js | 12 +- services/sync/tests/unit/test_jpakeclient.js | 2 +- services/sync/tests/unit/test_keys.js | 6 +- .../sync/tests/unit/test_node_reassignment.js | 14 +- .../sync/tests/unit/test_password_store.js | 10 +- .../tests/unit/test_places_guid_downgrade.js | 2 +- services/sync/tests/unit/test_postqueue.js | 22 +-- .../sync/tests/unit/test_records_crypto.js | 12 +- services/sync/tests/unit/test_records_wbo.js | 4 +- services/sync/tests/unit/test_resource.js | 6 +- .../sync/tests/unit/test_resource_async.js | 68 ++++----- .../sync/tests/unit/test_resource_header.js | 4 +- services/sync/tests/unit/test_resource_ua.js | 4 +- .../unit/test_sendcredentials_controller.js | 6 +- .../tests/unit/test_service_detect_upgrade.js | 8 +- .../tests/unit/test_service_getStorageInfo.js | 12 +- .../sync/tests/unit/test_service_login.js | 6 +- .../tests/unit/test_service_migratePrefs.js | 2 +- .../tests/unit/test_service_passwordUTF8.js | 4 +- .../sync/tests/unit/test_service_startOver.js | 2 +- .../sync/tests/unit/test_service_startup.js | 2 +- .../sync/tests/unit/test_service_sync_401.js | 6 +- .../tests/unit/test_service_sync_locked.js | 2 +- .../unit/test_service_sync_remoteSetup.js | 4 +- .../tests/unit/test_service_verifyLogin.js | 6 +- .../tests/unit/test_service_wipeServer.js | 4 +- services/sync/tests/unit/test_syncedtabs.js | 6 +- .../sync/tests/unit/test_syncengine_sync.js | 56 ++++---- .../sync/tests/unit/test_syncscheduler.js | 4 +- .../tests/unit/test_syncstoragerequest.js | 18 +-- services/sync/tests/unit/test_tab_engine.js | 4 +- services/sync/tests/unit/test_tab_store.js | 2 +- services/sync/tests/unit/test_tab_tracker.js | 12 +- services/sync/tests/unit/test_telemetry.js | 6 +- services/sync/tests/unit/test_utils_catch.js | 14 +- services/sync/tests/unit/test_utils_json.js | 8 +- services/sync/tests/unit/test_utils_lock.js | 11 +- services/sync/tests/unit/test_utils_notify.js | 11 +- .../unit/test_warn_on_truncated_response.js | 6 +- .../extensions/tps/components/tps-cmdline.js | 12 +- .../tps/extensions/tps/resource/logger.jsm | 44 +++--- .../tps/resource/modules/bookmarks.jsm | 94 ++++++------ .../extensions/tps/resource/modules/forms.jsm | 8 +- .../tps/resource/modules/history.jsm | 19 +-- .../tps/resource/modules/passwords.jsm | 11 +- .../extensions/tps/resource/modules/prefs.jsm | 14 +- .../extensions/tps/resource/modules/tabs.jsm | 4 +- .../tps/resource/modules/windows.jsm | 2 +- .../sync/tps/extensions/tps/resource/quit.js | 16 ++- .../sync/tps/extensions/tps/resource/tps.jsm | 99 +++++++------ 199 files changed, 1873 insertions(+), 1827 deletions(-) delete mode 100644 services/.eslintrc.js diff --git a/.eslintignore b/.eslintignore index 6be7747c81a4..6d7a3853822e 100644 --- a/.eslintignore +++ b/.eslintignore @@ -184,12 +184,6 @@ mobile/android/modules/HomeProvider.jsm # Uses `#filter substitution` services/sync/modules/constants.js -# Third party services -services/sync/tps/extensions/mozmill/resource/stdlib/json2.js -services/common/kinto-http-client.js -services/common/kinto-offline-client.js -services/sync/tps/extensions/mozmill - # toolkit/ exclusions # Not part of the default build diff --git a/services/.eslintrc.js b/services/.eslintrc.js deleted file mode 100644 index afe1f90f0c05..000000000000 --- a/services/.eslintrc.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; - -module.exports = { - "extends": [ - "../toolkit/.eslintrc.js" - ], - rules: { - /* These rules are only set to warn temporarily - until they get fixed, at which point their - respective line in this file should be removed. */ - "brace-style": "warn", - "consistent-return": "warn", - "no-cond-assign": "warn", - "no-else-return": "warn", - "no-empty": "warn", - "no-ex-assign": "warn", - "no-func-assign": "warn", - "no-irregular-whitespace": "warn", - "no-mixed-spaces-and-tabs": "warn", - "no-native-reassign": "warn", - "no-nested-ternary": "warn", - "no-octal": "warn", - "no-redeclare": "warn", - "no-unreachable": "warn", - "no-unsafe-finally": "warn", - "no-unused-vars": "warn", - "no-useless-call": "warn" - } -}; diff --git a/services/cloudsync/CloudSync.jsm b/services/cloudsync/CloudSync.jsm index 179e51e1f6c3..2c1057ea99f1 100644 --- a/services/cloudsync/CloudSync.jsm +++ b/services/cloudsync/CloudSync.jsm @@ -19,13 +19,13 @@ XPCOMUtils.defineLazyModuleGetter(this, "Tabs", var API_VERSION = 1; -var _CloudSync = function() { +var _CloudSync = function () { }; _CloudSync.prototype = { _adapters: null, - get adapters() { + get adapters () { if (!this._adapters) { this._adapters = new Adapters(); } @@ -34,7 +34,7 @@ _CloudSync.prototype = { _bookmarks: null, - get bookmarks() { + get bookmarks () { if (!this._bookmarks) { this._bookmarks = new Bookmarks(); } @@ -43,7 +43,7 @@ _CloudSync.prototype = { _local: null, - get local() { + get local () { if (!this._local) { this._local = new Local(); } @@ -52,28 +52,28 @@ _CloudSync.prototype = { _tabs: null, - get tabs() { + get tabs () { if (!this._tabs) { this._tabs = new Tabs(); } return this._tabs; }, - get tabsReady() { - return this._tabs ? true : false; + get tabsReady () { + return this._tabs ? true: false; }, - get version() { + get version () { return API_VERSION; }, }; -this.CloudSync = function CloudSync() { +this.CloudSync = function CloudSync () { return _cloudSyncInternal.instance; }; Object.defineProperty(CloudSync, "ready", { - get() { + get: function () { return _cloudSyncInternal.ready; } }); @@ -83,7 +83,7 @@ var _cloudSyncInternal = { ready: false, }; -XPCOMUtils.defineLazyGetter(_cloudSyncInternal, "instance", function() { +XPCOMUtils.defineLazyGetter(_cloudSyncInternal, "instance", function () { _cloudSyncInternal.ready = true; return new _CloudSync(); -}); +}.bind(this)); diff --git a/services/cloudsync/CloudSyncAdapters.jsm b/services/cloudsync/CloudSyncAdapters.jsm index acf413cd6aa6..3c4f1aaf25ed 100644 --- a/services/cloudsync/CloudSyncAdapters.jsm +++ b/services/cloudsync/CloudSyncAdapters.jsm @@ -9,43 +9,43 @@ this.EXPORTED_SYMBOLS = ["Adapters"]; Components.utils.import("resource://gre/modules/Services.jsm"); Components.utils.import("resource://gre/modules/CloudSyncEventSource.jsm"); -this.Adapters = function() { +this.Adapters = function () { let eventTypes = [ "sync", ]; let suspended = true; - let suspend = function() { + let suspend = function () { if (!suspended) { Services.obs.removeObserver(observer, "cloudsync:user-sync"); suspended = true; } - }; + }.bind(this); - let resume = function() { + let resume = function () { if (suspended) { Services.obs.addObserver(observer, "cloudsync:user-sync", false); suspended = false; } - }; + }.bind(this); let eventSource = new EventSource(eventTypes, suspend, resume); let registeredAdapters = new Map(); - function register(name, opts) { + function register (name, opts) { opts = opts || {}; registeredAdapters.set(name, opts); } - function unregister(name) { + function unregister (name) { if (!registeredAdapters.has(name)) { throw new Error("adapter is not registered: " + name) } registeredAdapters.delete(name); } - function getAdapterNames() { + function getAdapterNames () { let result = []; for (let name of registeredAdapters.keys()) { result.push(name); @@ -53,19 +53,19 @@ this.Adapters = function() { return result; } - function getAdapter(name) { + function getAdapter (name) { if (!registeredAdapters.has(name)) { throw new Error("adapter is not registered: " + name) } return registeredAdapters.get(name); } - function countAdapters() { + function countAdapters () { return registeredAdapters.size; } let observer = { - observe(subject, topic, data) { + observe: function (subject, topic, data) { switch (topic) { case "cloudsync:user-sync": eventSource.emit("sync"); diff --git a/services/cloudsync/CloudSyncBookmarks.jsm b/services/cloudsync/CloudSyncBookmarks.jsm index d62868bf8e1d..bb2e48d59828 100644 --- a/services/cloudsync/CloudSyncBookmarks.jsm +++ b/services/cloudsync/CloudSyncBookmarks.jsm @@ -49,18 +49,18 @@ function asyncCallback(ctx, func, args) { CommonUtils.nextTick(invoke); } -var Record = function(params) { +var Record = function (params) { this.id = params.guid; this.parent = params.parent || null; this.index = params.position; this.title = params.title; - this.dateAdded = Math.floor(params.dateAdded / 1000); - this.lastModified = Math.floor(params.lastModified / 1000); + this.dateAdded = Math.floor(params.dateAdded/1000); + this.lastModified = Math.floor(params.lastModified/1000); this.uri = params.url; let annos = params.annos || {}; Object.defineProperty(this, "annos", { - get() { + get: function () { return annos; }, enumerable: false @@ -95,8 +95,8 @@ Record.prototype = { version: DATA_VERSION, }; -var Bookmarks = function() { - let createRootFolder = function(name) { +var Bookmarks = function () { + let createRootFolder = function (name) { let ROOT_FOLDER_ANNO = "cloudsync/rootFolder/" + name; let ROOT_SHORTCUT_ANNO = "cloudsync/rootShortcut/" + name; @@ -142,7 +142,7 @@ var Bookmarks = function() { return deferred.promise; }; - let getRootFolder = function(name) { + let getRootFolder = function (name) { let ROOT_FOLDER_ANNO = "cloudsync/rootFolder/" + name; let ROOT_SHORTCUT_ANNO = "cloudsync/rootShortcut/" + name; let deferred = Promise.defer(); @@ -166,7 +166,7 @@ var Bookmarks = function() { return deferred.promise; }; - let deleteRootFolder = function(name) { + let deleteRootFolder = function (name) { let ROOT_FOLDER_ANNO = "cloudsync/rootFolder/" + name; let ROOT_SHORTCUT_ANNO = "cloudsync/rootShortcut/" + name; @@ -197,7 +197,7 @@ var Bookmarks = function() { let rootFolderId = folderIds[0]; PlacesWrapper.removeFolderChildren(rootFolderId).then( - function() { + function () { return PlacesWrapper.removeItem(rootFolderId); } ).then(deleteFolderDeferred.resolve, deleteFolderDeferred.reject); @@ -221,23 +221,23 @@ var Bookmarks = function() { this.Bookmarks = Bookmarks; -var RootFolder = function(rootId, rootName) { +var RootFolder = function (rootId, rootName) { let suspended = true; let ignoreAll = false; - let suspend = function() { + let suspend = function () { if (!suspended) { PlacesUtils.bookmarks.removeObserver(observer); suspended = true; } - }; + }.bind(this); - let resume = function() { + let resume = function () { if (suspended) { PlacesUtils.bookmarks.addObserver(observer, false); suspended = false; } - }; + }.bind(this); let eventTypes = [ "add", @@ -251,7 +251,7 @@ var RootFolder = function(rootId, rootName) { let folderCache = new FolderCache; folderCache.insert(rootId, null); - let getCachedFolderIds = function(cache, roots) { + let getCachedFolderIds = function (cache, roots) { let nodes = [...roots]; let results = []; @@ -264,7 +264,7 @@ var RootFolder = function(rootId, rootName) { return results; }; - let getLocalItems = function() { + let getLocalItems = function () { let deferred = Promise.defer(); let folders = getCachedFolderIds(folderCache, folderCache.getChildren(rootId)); @@ -288,9 +288,9 @@ var RootFolder = function(rootId, rootName) { function getParentGuids(results) { results = Array.prototype.concat.apply([], results); let promises = []; - results.map(function(result) { + results.map(function (result) { let promise = PlacesWrapper.localIdToGuid(result.parent).then( - function(guidResult) { + function (guidResult) { result.parent = guidResult; return Promise.resolve(result); }, @@ -304,9 +304,9 @@ var RootFolder = function(rootId, rootName) { function getAnnos(results) { results = Array.prototype.concat.apply([], results); let promises = []; - results.map(function(result) { + results.map(function (result) { let promise = PlacesWrapper.getItemAnnotationsForLocalId(result.id).then( - function(annos) { + function (annos) { result.annos = annos; return Promise.resolve(result); }, @@ -325,7 +325,7 @@ var RootFolder = function(rootId, rootName) { Promise.all(promises) .then(getParentGuids) .then(getAnnos) - .then(function(results) { + .then(function (results) { results = results.map((result) => new Record(result)); deferred.resolve(results); }, @@ -334,7 +334,7 @@ var RootFolder = function(rootId, rootName) { return deferred.promise; }; - let getLocalItemsById = function(guids) { + let getLocalItemsById = function (guids) { let deferred = Promise.defer(); let types = [ @@ -346,9 +346,9 @@ var RootFolder = function(rootId, rootName) { function getParentGuids(results) { let promises = []; - results.map(function(result) { + results.map(function (result) { let promise = PlacesWrapper.localIdToGuid(result.parent).then( - function(guidResult) { + function (guidResult) { result.parent = guidResult; return Promise.resolve(result); }, @@ -361,7 +361,7 @@ var RootFolder = function(rootId, rootName) { PlacesWrapper.getItemsByGuid(guids, types) .then(getParentGuids) - .then(function(results) { + .then(function (results) { results = results.map((result) => new Record(result)); deferred.resolve(results); }, @@ -370,7 +370,7 @@ var RootFolder = function(rootId, rootName) { return deferred.promise; }; - let _createItem = function(item) { + let _createItem = function (item) { let deferred = Promise.defer(); function getFolderId() { @@ -432,11 +432,11 @@ var RootFolder = function(rootId, rootName) { return deferred.promise; }; - let _deleteItem = function(item) { + let _deleteItem = function (item) { let deferred = Promise.defer(); PlacesWrapper.guidToLocalId(item.id).then( - function(localId) { + function (localId) { folderCache.remove(localId); return PlacesWrapper.removeItem(localId); } @@ -445,11 +445,11 @@ var RootFolder = function(rootId, rootName) { return deferred.promise; }; - let _updateItem = function(item) { + let _updateItem = function (item) { let deferred = Promise.defer(); PlacesWrapper.guidToLocalId(item.id).then( - function(localId) { + function (localId) { let promises = []; if (item.hasOwnProperty("dateAdded")) { @@ -472,7 +472,7 @@ var RootFolder = function(rootId, rootName) { let deferred = Promise.defer(); PlacesWrapper.guidToLocalId(item.parent) .then( - function(parent) { + function (parent) { let index = item.hasOwnProperty("index") ? item.index : PlacesUtils.bookmarks.DEFAULT_INDEX; if (CS_FOLDER & item.type) { folderCache.setParent(localId, parent); @@ -504,7 +504,7 @@ var RootFolder = function(rootId, rootName) { return deferred.promise; }; - let mergeRemoteItems = function(items) { + let mergeRemoteItems = function (items) { ignoreAll = true; let deferred = Promise.defer(); @@ -513,10 +513,10 @@ var RootFolder = function(rootId, rootName) { let updatedItems = []; let deletedItems = []; - let sortItems = function() { + let sortItems = function () { let promises = []; - let exists = function(item) { + let exists = function (item) { let existsDeferred = Promise.defer(); if (!item.id) { Object.defineProperty(item, "__exists__", { @@ -526,7 +526,7 @@ var RootFolder = function(rootId, rootName) { existsDeferred.resolve(item); } else { PlacesWrapper.guidToLocalId(item.id).then( - function(localId) { + function (localId) { Object.defineProperty(item, "__exists__", { value: localId ? true : false, enumerable: false @@ -539,7 +539,7 @@ var RootFolder = function(rootId, rootName) { return existsDeferred.promise; } - let handleSortedItem = function(item) { + let handleSortedItem = function (item) { if (!item.__exists__ && !item.deleted) { if (CS_FOLDER == item.type) { newFolders[item.id] = item; @@ -566,7 +566,7 @@ var RootFolder = function(rootId, rootName) { return Promise.all(promises); } - let processNewFolders = function() { + let processNewFolders = function () { let newFolderGuids = Object.keys(newFolders); let newFolderRoots = []; @@ -578,14 +578,14 @@ var RootFolder = function(rootId, rootName) { } else { newFolderRoots.push(guid); } - } + }; let promises = []; for (let guid of newFolderRoots) { let root = newFolders[guid]; let promise = Promise.resolve(); promise = promise.then( - function() { + function () { return _createItem(root); }, Promise.reject.bind(Promise) @@ -596,7 +596,7 @@ var RootFolder = function(rootId, rootName) { let item = newFolders[items.shift()]; items = items.concat(item._children); promise = promise.then( - function() { + function () { return _createItem(item); }, Promise.reject.bind(Promise) @@ -608,7 +608,7 @@ var RootFolder = function(rootId, rootName) { return Promise.all(promises); } - let processItems = function() { + let processItems = function () { let promises = []; for (let item of newItems) { @@ -628,11 +628,11 @@ var RootFolder = function(rootId, rootName) { sortItems().then(processNewFolders) .then(processItems) - .then(function() { + .then(function () { ignoreAll = false; deferred.resolve(items); }, - function(err) { + function (err) { ignoreAll = false; deferred.reject(err); }); @@ -640,7 +640,7 @@ var RootFolder = function(rootId, rootName) { return deferred.promise; }; - let ignore = function(id, parent) { + let ignore = function (id, parent) { if (ignoreAll) { return true; } @@ -652,7 +652,7 @@ var RootFolder = function(rootId, rootName) { return true; }; - let handleItemAdded = function(id, parent, index, type, uri, title, dateAdded, guid, parentGuid) { + let handleItemAdded = function (id, parent, index, type, uri, title, dateAdded, guid, parentGuid) { let deferred = Promise.defer(); if (PlacesUtils.bookmarks.TYPE_FOLDER == type) { @@ -665,7 +665,7 @@ var RootFolder = function(rootId, rootName) { return deferred.promise; }; - let handleItemRemoved = function(id, parent, index, type, uri, guid, parentGuid) { + let handleItemRemoved = function (id, parent, index, type, uri, guid, parentGuid) { let deferred = Promise.defer(); if (PlacesUtils.bookmarks.TYPE_FOLDER == type) { @@ -678,7 +678,7 @@ var RootFolder = function(rootId, rootName) { return deferred.promise; }; - let handleItemChanged = function(id, property, isAnnotation, newValue, lastModified, type, parent, guid, parentGuid) { + let handleItemChanged = function (id, property, isAnnotation, newValue, lastModified, type, parent, guid, parentGuid) { let deferred = Promise.defer(); eventSource.emit('change', guid); @@ -687,7 +687,7 @@ var RootFolder = function(rootId, rootName) { return deferred.promise; }; - let handleItemMoved = function(id, oldParent, oldIndex, newParent, newIndex, type, guid, oldParentGuid, newParentGuid) { + let handleItemMoved = function (id, oldParent, oldIndex, newParent, newIndex, type, guid, oldParentGuid, newParentGuid) { let deferred = Promise.defer(); function complete() { @@ -718,13 +718,13 @@ var RootFolder = function(rootId, rootName) { }; let observer = { - onBeginBatchUpdate() { + onBeginBatchUpdate: function () { }, - onEndBatchUpdate() { + onEndBatchUpdate: function () { }, - onItemAdded(id, parent, index, type, uri, title, dateAdded, guid, parentGuid) { + onItemAdded: function (id, parent, index, type, uri, title, dateAdded, guid, parentGuid) { if (ignore(id, parent)) { return; } @@ -732,7 +732,7 @@ var RootFolder = function(rootId, rootName) { asyncCallback(this, handleItemAdded, Array.prototype.slice.call(arguments)); }, - onItemRemoved(id, parent, index, type, uri, guid, parentGuid) { + onItemRemoved: function (id, parent, index, type, uri, guid, parentGuid) { if (ignore(id, parent)) { return; } @@ -740,7 +740,7 @@ var RootFolder = function(rootId, rootName) { asyncCallback(this, handleItemRemoved, Array.prototype.slice.call(arguments)); }, - onItemChanged(id, property, isAnnotation, newValue, lastModified, type, parent, guid, parentGuid) { + onItemChanged: function (id, property, isAnnotation, newValue, lastModified, type, parent, guid, parentGuid) { if (ignore(id, parent)) { return; } @@ -748,7 +748,7 @@ var RootFolder = function(rootId, rootName) { asyncCallback(this, handleItemChanged, Array.prototype.slice.call(arguments)); }, - onItemMoved(id, oldParent, oldIndex, newParent, newIndex, type, guid, oldParentGuid, newParentGuid) { + onItemMoved: function (id, oldParent, oldIndex, newParent, newIndex, type, guid, oldParentGuid, newParentGuid) { if (ignore(id, oldParent) && ignore(id, newParent)) { return; } @@ -765,20 +765,20 @@ var RootFolder = function(rootId, rootName) { this.mergeRemoteItems = mergeRemoteItems.bind(this); let rootGuid = null; // resolved before becoming ready (below) - this.__defineGetter__("id", function() { + this.__defineGetter__("id", function () { return rootGuid; }); - this.__defineGetter__("name", function() { + this.__defineGetter__("name", function () { return rootName; }); let deferred = Promise.defer(); - let getGuidForRootFolder = function() { + let getGuidForRootFolder = function () { return PlacesWrapper.localIdToGuid(rootId); } PlacesWrapper.updateCachedFolderIds(folderCache, rootId) .then(getGuidForRootFolder, getGuidForRootFolder) - .then(function(guid) { + .then(function (guid) { rootGuid = guid; deferred.resolve(this); }.bind(this), diff --git a/services/cloudsync/CloudSyncBookmarksFolderCache.jsm b/services/cloudsync/CloudSyncBookmarksFolderCache.jsm index 9263361cbb71..f3c3fc8f24f6 100644 --- a/services/cloudsync/CloudSyncBookmarksFolderCache.jsm +++ b/services/cloudsync/CloudSyncBookmarksFolderCache.jsm @@ -7,16 +7,16 @@ this.EXPORTED_SYMBOLS = ["FolderCache"]; // Cache for bookmarks folder heirarchy. -var FolderCache = function() { +var FolderCache = function () { this.cache = new Map(); } FolderCache.prototype = { - has(id) { + has: function (id) { return this.cache.has(id); }, - insert(id, parentId) { + insert: function (id, parentId) { if (this.cache.has(id)) { return; } @@ -35,7 +35,7 @@ FolderCache.prototype = { } }, - remove(id) { + remove: function (id) { if (!(this.cache.has(id))) { throw new Error("remote :: id not found in cache: " + id); } @@ -52,7 +52,7 @@ FolderCache.prototype = { this.cache.delete(id); }, - setParent(id, parentId) { + setParent: function (id, parentId) { if (!(this.cache.has(id))) { throw new Error("setParent :: id not found in cache: " + id); } @@ -71,7 +71,7 @@ FolderCache.prototype = { return true; }, - getParent(id) { + getParent: function (id) { if (this.cache.has(id)) { return this.cache.get(id).parent; } @@ -79,7 +79,7 @@ FolderCache.prototype = { throw new Error("getParent :: id not found in cache: " + id); }, - getChildren(id) { + getChildren: function (id) { if (this.cache.has(id)) { return this.cache.get(id).children; } @@ -87,7 +87,7 @@ FolderCache.prototype = { throw new Error("getChildren :: id not found in cache: " + id); }, - setChildren(id, children) { + setChildren: function (id, children) { for (let child of children) { if (!this.cache.has(child)) { this.insert(child, id); @@ -97,7 +97,7 @@ FolderCache.prototype = { } }, - dump() { + dump: function () { dump("FolderCache: " + JSON.stringify(this.cache) + "\n"); }, }; diff --git a/services/cloudsync/CloudSyncEventSource.jsm b/services/cloudsync/CloudSyncEventSource.jsm index 6d0066bf4ed7..edb9c426b292 100644 --- a/services/cloudsync/CloudSyncEventSource.jsm +++ b/services/cloudsync/CloudSyncEventSource.jsm @@ -6,21 +6,21 @@ this.EXPORTED_SYMBOLS = ["EventSource"]; Components.utils.import("resource://services-common/utils.js"); -var EventSource = function(types, suspendFunc, resumeFunc) { +var EventSource = function (types, suspendFunc, resumeFunc) { this.listeners = new Map(); for (let type of types) { this.listeners.set(type, new Set()); } - this.suspend = suspendFunc || function() {}; - this.resume = resumeFunc || function() {}; + this.suspend = suspendFunc || function () {}; + this.resume = resumeFunc || function () {}; this.addEventListener = this.addEventListener.bind(this); this.removeEventListener = this.removeEventListener.bind(this); }; EventSource.prototype = { - addEventListener(type, listener) { + addEventListener: function (type, listener) { if (!this.listeners.has(type)) { return; } @@ -28,7 +28,7 @@ EventSource.prototype = { this.resume(); }, - removeEventListener(type, listener) { + removeEventListener: function (type, listener) { if (!this.listeners.has(type)) { return; } @@ -38,7 +38,7 @@ EventSource.prototype = { } }, - hasListeners() { + hasListeners: function () { for (let l of this.listeners.values()) { if (l.size > 0) { return true; @@ -47,12 +47,12 @@ EventSource.prototype = { return false; }, - emit(type, arg) { + emit: function (type, arg) { if (!this.listeners.has(type)) { return; } CommonUtils.nextTick( - function() { + function () { for (let listener of this.listeners.get(type)) { listener.call(undefined, arg); } diff --git a/services/cloudsync/CloudSyncLocal.jsm b/services/cloudsync/CloudSyncLocal.jsm index c04717314fb7..998c0c3c4d21 100644 --- a/services/cloudsync/CloudSyncLocal.jsm +++ b/services/cloudsync/CloudSyncLocal.jsm @@ -29,9 +29,9 @@ function makeGUID() { return CommonUtils.encodeBase64URL(CryptoUtils.generateRandomBytes(9)); } -this.Local = function() { +this.Local = function () { let prefs = new Preferences("services.cloudsync."); - this.__defineGetter__("prefs", function() { + this.__defineGetter__("prefs", function () { return prefs; }); }; @@ -39,7 +39,7 @@ this.Local = function() { Local.prototype = { get id() { let clientId = this.prefs.get("client.GUID", ""); - return clientId == "" ? this.id = makeGUID() : clientId; + return clientId == "" ? this.id = makeGUID(): clientId; }, set id(value) { diff --git a/services/cloudsync/CloudSyncPlacesWrapper.jsm b/services/cloudsync/CloudSyncPlacesWrapper.jsm index eca29ea193f9..dd8c5c52eb4c 100644 --- a/services/cloudsync/CloudSyncPlacesWrapper.jsm +++ b/services/cloudsync/CloudSyncPlacesWrapper.jsm @@ -14,13 +14,13 @@ Cu.import("resource://gre/modules/PlacesUtils.jsm"); Cu.import("resource:///modules/PlacesUIUtils.jsm"); Cu.import("resource://services-common/utils.js"); -var PlacesQueries = function() { +var PlacesQueries = function () { } PlacesQueries.prototype = { cachedStmts: {}, - getQuery(queryString) { + getQuery: function (queryString) { if (queryString in this.cachedStmts) { return this.cachedStmts[queryString]; } @@ -30,13 +30,13 @@ PlacesQueries.prototype = { } }; -var PlacesWrapper = function() { +var PlacesWrapper = function () { } PlacesWrapper.prototype = { placesQueries: new PlacesQueries(), - guidToLocalId(guid) { + guidToLocalId: function (guid) { let deferred = Promise.defer(); let stmt = "SELECT id AS item_id " + @@ -58,7 +58,7 @@ PlacesWrapper.prototype = { return deferred.promise; }, - localIdToGuid(id) { + localIdToGuid: function (id) { let deferred = Promise.defer(); let stmt = "SELECT guid " + @@ -80,7 +80,7 @@ PlacesWrapper.prototype = { return deferred.promise; }, - getItemsById(ids, types) { + getItemsById: function (ids, types) { let deferred = Promise.defer(); let stmt = "SELECT b.id, b.type, b.parent, b.position, b.title, b.guid, b.dateAdded, b.lastModified, p.url " + "FROM moz_bookmarks b " + @@ -95,7 +95,7 @@ PlacesWrapper.prototype = { return deferred.promise; }, - getItemsByParentId(parents, types) { + getItemsByParentId: function (parents, types) { let deferred = Promise.defer(); let stmt = "SELECT b.id, b.type, b.parent, b.position, b.title, b.guid, b.dateAdded, b.lastModified, p.url " + "FROM moz_bookmarks b " + @@ -110,7 +110,7 @@ PlacesWrapper.prototype = { return deferred.promise; }, - getItemsByGuid(guids, types) { + getItemsByGuid: function (guids, types) { let deferred = Promise.defer(); guids = guids.map(JSON.stringify); let stmt = "SELECT b.id, b.type, b.parent, b.position, b.title, b.guid, b.dateAdded, b.lastModified, p.url " + @@ -126,7 +126,7 @@ PlacesWrapper.prototype = { return deferred.promise; }, - updateCachedFolderIds(folderCache, folder) { + updateCachedFolderIds: function (folderCache, folder) { let deferred = Promise.defer(); let stmt = "SELECT id, guid " + "FROM moz_bookmarks " + @@ -137,7 +137,7 @@ PlacesWrapper.prototype = { query.params.item_type = PlacesUtils.bookmarks.TYPE_FOLDER; this.asyncQuery(query, ["id", "guid"]).then( - function(items) { + function (items) { let previousIds = folderCache.getChildren(folder); let currentIds = new Set(); for (let item of items) { @@ -175,7 +175,7 @@ PlacesWrapper.prototype = { return deferred.promise; }, - getLocalIdsWithAnnotation(anno) { + getLocalIdsWithAnnotation: function (anno) { let deferred = Promise.defer(); let stmt = "SELECT a.item_id " + "FROM moz_anno_attributes n " + @@ -186,7 +186,7 @@ PlacesWrapper.prototype = { query.params.anno_name = anno.toString(); this.asyncQuery(query, ["item_id"]) - .then(function(items) { + .then(function (items) { let results = []; for (let item of items) { results.push(item.item_id); @@ -198,7 +198,7 @@ PlacesWrapper.prototype = { return deferred.promise; }, - getItemAnnotationsForLocalId(id) { + getItemAnnotationsForLocalId: function (id) { let deferred = Promise.defer(); let stmt = "SELECT a.name, b.content " + "FROM moz_anno_attributes a " + @@ -209,7 +209,7 @@ PlacesWrapper.prototype = { query.params.item_id = id; this.asyncQuery(query, ["name", "content"]) - .then(function(results) { + .then(function (results) { let annos = {}; for (let result of results) { annos[result.name] = result.content; @@ -221,7 +221,7 @@ PlacesWrapper.prototype = { return deferred.promise; }, - insertBookmark(parent, uri, index, title, guid) { + insertBookmark: function (parent, uri, index, title, guid) { let parsedURI; try { parsedURI = CommonUtils.makeURI(uri) @@ -237,7 +237,7 @@ PlacesWrapper.prototype = { } }, - setItemAnnotation(item, anno, value, flags, exp) { + setItemAnnotation: function (item, anno, value, flags, exp) { try { return Promise.resolve(PlacesUtils.annotations.setItemAnnotation(item, anno, value, flags, exp)); } catch (e) { @@ -245,7 +245,7 @@ PlacesWrapper.prototype = { } }, - itemHasAnnotation(item, anno) { + itemHasAnnotation: function (item, anno) { try { return Promise.resolve(PlacesUtils.annotations.itemHasAnnotation(item, anno)); } catch (e) { @@ -253,7 +253,7 @@ PlacesWrapper.prototype = { } }, - createFolder(parent, name, index, guid) { + createFolder: function (parent, name, index, guid) { try { return Promise.resolve(PlacesUtils.bookmarks.createFolder(parent, name, index, guid)); } catch (e) { @@ -261,7 +261,7 @@ PlacesWrapper.prototype = { } }, - removeFolderChildren(folder) { + removeFolderChildren: function (folder) { try { PlacesUtils.bookmarks.removeFolderChildren(folder); return Promise.resolve(); @@ -270,7 +270,7 @@ PlacesWrapper.prototype = { } }, - insertSeparator(parent, index, guid) { + insertSeparator: function (parent, index, guid) { try { return Promise.resolve(PlacesUtils.bookmarks.insertSeparator(parent, index, guid)); } catch (e) { @@ -278,7 +278,7 @@ PlacesWrapper.prototype = { } }, - removeItem(item) { + removeItem: function (item) { try { return Promise.resolve(PlacesUtils.bookmarks.removeItem(item)); } catch (e) { @@ -286,7 +286,7 @@ PlacesWrapper.prototype = { } }, - setItemDateAdded(item, dateAdded) { + setItemDateAdded: function (item, dateAdded) { try { return Promise.resolve(PlacesUtils.bookmarks.setItemDateAdded(item, dateAdded)); } catch (e) { @@ -294,7 +294,7 @@ PlacesWrapper.prototype = { } }, - setItemLastModified(item, lastModified) { + setItemLastModified: function (item, lastModified) { try { return Promise.resolve(PlacesUtils.bookmarks.setItemLastModified(item, lastModified)); } catch (e) { @@ -302,7 +302,7 @@ PlacesWrapper.prototype = { } }, - setItemTitle(item, title) { + setItemTitle: function (item, title) { try { return Promise.resolve(PlacesUtils.bookmarks.setItemTitle(item, title)); } catch (e) { @@ -310,7 +310,7 @@ PlacesWrapper.prototype = { } }, - changeBookmarkURI(item, uri) { + changeBookmarkURI: function (item, uri) { try { uri = CommonUtils.makeURI(uri); return Promise.resolve(PlacesUtils.bookmarks.changeBookmarkURI(item, uri)); @@ -319,7 +319,7 @@ PlacesWrapper.prototype = { } }, - moveItem(item, parent, index) { + moveItem: function (item, parent, index) { try { return Promise.resolve(PlacesUtils.bookmarks.moveItem(item, parent, index)); } catch (e) { @@ -327,7 +327,7 @@ PlacesWrapper.prototype = { } }, - setItemIndex(item, index) { + setItemIndex: function (item, index) { try { return Promise.resolve(PlacesUtils.bookmarks.setItemIndex(item, index)); } catch (e) { @@ -335,11 +335,11 @@ PlacesWrapper.prototype = { } }, - asyncQuery(query, names) { + asyncQuery: function (query, names) { let deferred = Promise.defer(); let storageCallback = { results: [], - handleResult(results) { + handleResult: function (results) { if (!names) { return; } @@ -354,11 +354,11 @@ PlacesWrapper.prototype = { } }, - handleError(error) { + handleError: function (error) { deferred.reject(error); }, - handleCompletion(reason) { + handleCompletion: function (reason) { if (REASON_ERROR == reason) { return; } diff --git a/services/cloudsync/CloudSyncTabs.jsm b/services/cloudsync/CloudSyncTabs.jsm index 3e416a80ba1a..7debc26782b3 100644 --- a/services/cloudsync/CloudSyncTabs.jsm +++ b/services/cloudsync/CloudSyncTabs.jsm @@ -19,7 +19,7 @@ XPCOMUtils.defineLazyServiceGetter(this, "Session", "@mozilla.org/browser/sessio const DATA_VERSION = 1; -var ClientRecord = function(params) { +var ClientRecord = function (params) { this.id = params.id; this.name = params.name || "?"; this.tabs = new Set(); @@ -28,7 +28,7 @@ var ClientRecord = function(params) { ClientRecord.prototype = { version: DATA_VERSION, - update(params) { + update: function (params) { if (this.id !== params.id) { throw new Error("expected " + this.id + " to equal " + params.id); } @@ -37,7 +37,7 @@ ClientRecord.prototype = { } }; -var TabRecord = function(params) { +var TabRecord = function (params) { this.url = params.url || ""; this.update(params); }; @@ -45,7 +45,7 @@ var TabRecord = function(params) { TabRecord.prototype = { version: DATA_VERSION, - update(params) { + update: function (params) { if (this.url && this.url !== params.url) { throw new Error("expected " + this.url + " to equal " + params.url); } @@ -60,13 +60,13 @@ TabRecord.prototype = { }, }; -var TabCache = function() { +var TabCache = function () { this.tabs = new Map(); this.clients = new Map(); }; TabCache.prototype = { - merge(client, tabs) { + merge: function (client, tabs) { if (!client || !client.id) { return; } @@ -113,7 +113,7 @@ TabCache.prototype = { } }, - clear(client) { + clear: function (client) { if (client) { this.clients.delete(client.id); } else { @@ -122,7 +122,7 @@ TabCache.prototype = { } }, - get() { + get: function () { let results = []; for (let client of this.clients.values()) { results.push(client); @@ -130,13 +130,13 @@ TabCache.prototype = { return results; }, - isEmpty() { + isEmpty: function () { return 0 == this.clients.size; }, }; -this.Tabs = function() { +this.Tabs = function () { let suspended = true; let topics = [ @@ -146,7 +146,7 @@ this.Tabs = function() { "TabSelect", ]; - let update = function(event) { + let update = function (event) { if (event.originalTarget.linkedBrowser) { if (PrivateBrowsingUtils.isBrowserPrivate(event.originalTarget.linkedBrowser) && !PrivateBrowsingUtils.permanentPrivateBrowsing) { @@ -157,26 +157,26 @@ this.Tabs = function() { eventSource.emit("change"); }; - let registerListenersForWindow = function(window) { + let registerListenersForWindow = function (window) { for (let topic of topics) { window.addEventListener(topic, update, false); } window.addEventListener("unload", unregisterListeners, false); }; - let unregisterListenersForWindow = function(window) { + let unregisterListenersForWindow = function (window) { window.removeEventListener("unload", unregisterListeners, false); for (let topic of topics) { window.removeEventListener(topic, update, false); } }; - let unregisterListeners = function(event) { + let unregisterListeners = function (event) { unregisterListenersForWindow(event.target); }; let observer = { - observe(subject, topic, data) { + observe: function (subject, topic, data) { switch (topic) { case "domwindowopened": let onLoad = () => { @@ -192,7 +192,7 @@ this.Tabs = function() { } }; - let resume = function() { + let resume = function () { if (suspended) { Observers.add("domwindowopened", observer); let wins = Services.wm.getEnumerator("navigator:browser"); @@ -200,9 +200,9 @@ this.Tabs = function() { registerListenersForWindow(wins.getNext()); } } - }; + }.bind(this); - let suspend = function() { + let suspend = function () { if (!suspended) { Observers.remove("domwindowopened", observer); let wins = Services.wm.getEnumerator("navigator:browser"); @@ -210,7 +210,7 @@ this.Tabs = function() { unregisterListenersForWindow(wins.getNext()); } } - }; + }.bind(this); let eventTypes = [ "change", @@ -220,20 +220,20 @@ this.Tabs = function() { let tabCache = new TabCache(); - let getWindowEnumerator = function() { + let getWindowEnumerator = function () { return Services.wm.getEnumerator("navigator:browser"); }; - let shouldSkipWindow = function(win) { + let shouldSkipWindow = function (win) { return win.closed || PrivateBrowsingUtils.isWindowPrivate(win); }; - let getTabState = function(tab) { + let getTabState = function (tab) { return JSON.parse(Session.getTabState(tab)); }; - let getLocalTabs = function(filter) { + let getLocalTabs = function (filter) { let deferred = Promise.defer(); filter = (undefined === filter) ? true : filter; @@ -242,11 +242,11 @@ this.Tabs = function() { let allTabs = []; let currentState = JSON.parse(Session.getBrowserState()); - currentState.windows.forEach(function(window) { + currentState.windows.forEach(function (window) { if (window.isPrivate) { return; } - window.tabs.forEach(function(tab) { + window.tabs.forEach(function (tab) { if (!tab.entries.length) { return; } @@ -273,7 +273,7 @@ this.Tabs = function() { return deferred.promise; }; - let mergeRemoteTabs = function(client, tabs) { + let mergeRemoteTabs = function (client, tabs) { let deferred = Promise.defer(); deferred.resolve(tabCache.merge(client, tabs)); @@ -282,7 +282,7 @@ this.Tabs = function() { return deferred.promise; }; - let clearRemoteTabs = function(client) { + let clearRemoteTabs = function (client) { let deferred = Promise.defer(); deferred.resolve(tabCache.clear(client)); @@ -291,7 +291,7 @@ this.Tabs = function() { return deferred.promise; }; - let getRemoteTabs = function() { + let getRemoteTabs = function () { let deferred = Promise.defer(); deferred.resolve(tabCache.get()); @@ -299,7 +299,7 @@ this.Tabs = function() { return deferred.promise; }; - let hasRemoteTabs = function() { + let hasRemoteTabs = function () { return !tabCache.isEmpty(); }; diff --git a/services/cloudsync/tests/mochitest/browser_tabEvents.js b/services/cloudsync/tests/mochitest/browser_tabEvents.js index 1e9ebd10596e..9d80090a0a5b 100644 --- a/services/cloudsync/tests/mochitest/browser_tabEvents.js +++ b/services/cloudsync/tests/mochitest/browser_tabEvents.js @@ -17,30 +17,30 @@ function test() { let testURL = "chrome://mochitests/content/browser/services/cloudsync/tests/mochitest/other_window.html"; let expected = [ testURL, - testURL + "?x=1", - testURL + "?x=%20a", + testURL+"?x=1", + testURL+"?x=%20a", // testURL+"?x=å", ]; let nevents = 0; let nflushed = 0; - function handleTabChangeEvent() { + function handleTabChangeEvent () { cloudSync.tabs.removeEventListener("change", handleTabChangeEvent); - ++nevents; + ++ nevents; info("tab change event " + nevents); next(); } function getLocalTabs() { cloudSync.tabs.getLocalTabs().then( - function(tabs) { + function (tabs) { for (let tab of tabs) { ok(expected.indexOf(tab.url) >= 0, "found an expected tab"); } is(tabs.length, expected.length, "found the right number of tabs"); - opentabs.forEach(function(tab) { + opentabs.forEach(function (tab) { gBrowser.removeTab(tab); }); @@ -59,7 +59,7 @@ function test() { function flush() { tab.linkedBrowser.removeEventListener("load", flush, true); local.TabStateFlusher.flush(tab.linkedBrowser).then(() => { - ++nflushed; + ++ nflushed; info("flushed " + nflushed); next(); }); diff --git a/services/cloudsync/tests/xpcshell/head.js b/services/cloudsync/tests/xpcshell/head.js index 921d30f749ca..bd517cafaa34 100644 --- a/services/cloudsync/tests/xpcshell/head.js +++ b/services/cloudsync/tests/xpcshell/head.js @@ -5,6 +5,6 @@ var {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components; "use strict"; -(function initCloudSyncTestingInfrastructure() { +(function initCloudSyncTestingInfrastructure () { do_get_profile(); }).call(this); diff --git a/services/cloudsync/tests/xpcshell/test_bookmarks.js b/services/cloudsync/tests/xpcshell/test_bookmarks.js index dd951712ac3d..d4e1d2b754b5 100644 --- a/services/cloudsync/tests/xpcshell/test_bookmarks.js +++ b/services/cloudsync/tests/xpcshell/test_bookmarks.js @@ -5,22 +5,22 @@ Cu.import("resource://gre/modules/CloudSync.jsm"); -function run_test() { +function run_test () { run_next_test(); } -function cleanup() { +function cleanup () { } -add_task(function* test_merge_bookmarks_flat() { +add_task(function* test_merge_bookmarks_flat () { try { let rootFolder = yield CloudSync().bookmarks.getRootFolder("TEST"); ok(rootFolder.id, "root folder id is ok"); let items = [ - {"id":"G_UL4ZhOyX8m", "type":rootFolder.BOOKMARK, "title":"reddit: the front page of the internet 1", "uri":"http://www.reddit.com", index:2}, - {"id":"G_UL4ZhOyX8n", "type":rootFolder.BOOKMARK, "title":"reddit: the front page of the internet 2", "uri":"http://www.reddit.com?1", index:1}, + {"id":"G_UL4ZhOyX8m","type":rootFolder.BOOKMARK,"title":"reddit: the front page of the internet 1","uri":"http://www.reddit.com",index:2}, + {"id":"G_UL4ZhOyX8n","type":rootFolder.BOOKMARK,"title":"reddit: the front page of the internet 2","uri":"http://www.reddit.com?1",index:1}, ]; yield rootFolder.mergeRemoteItems(items); @@ -31,15 +31,15 @@ add_task(function* test_merge_bookmarks_flat() { } }); -add_task(function* test_merge_bookmarks_in_folders() { +add_task(function* test_merge_bookmarks_in_folders () { try { let rootFolder = yield CloudSync().bookmarks.getRootFolder("TEST"); ok(rootFolder.id, "root folder id is ok"); let items = [ - {"id":"G_UL4ZhOyX8m", "type":rootFolder.BOOKMARK, "title":"reddit: the front page of the internet 1", "uri":"http://www.reddit.com", index:2}, - {"id":"G_UL4ZhOyX8n", "type":rootFolder.BOOKMARK, parent:"G_UL4ZhOyX8x", "title":"reddit: the front page of the internet 2", "uri":"http://www.reddit.com/?a=å%20ä%20ö", index:1}, - {"id":"G_UL4ZhOyX8x", "type":rootFolder.FOLDER}, + {"id":"G_UL4ZhOyX8m","type":rootFolder.BOOKMARK,"title":"reddit: the front page of the internet 1","uri":"http://www.reddit.com",index:2}, + {"id":"G_UL4ZhOyX8n","type":rootFolder.BOOKMARK,parent:"G_UL4ZhOyX8x","title":"reddit: the front page of the internet 2","uri":"http://www.reddit.com/?a=å%20ä%20ö",index:1}, + {"id":"G_UL4ZhOyX8x","type":rootFolder.FOLDER}, ]; yield rootFolder.mergeRemoteItems(items); @@ -70,4 +70,4 @@ add_task(function* test_merge_bookmarks_in_folders() { } finally { yield CloudSync().bookmarks.deleteRootFolder("TEST"); } -}); +}); \ No newline at end of file diff --git a/services/cloudsync/tests/xpcshell/test_module.js b/services/cloudsync/tests/xpcshell/test_module.js index 3c9456225581..6d31345ed681 100644 --- a/services/cloudsync/tests/xpcshell/test_module.js +++ b/services/cloudsync/tests/xpcshell/test_module.js @@ -5,11 +5,11 @@ Cu.import("resource://gre/modules/CloudSync.jsm"); -function run_test() { +function run_test () { run_next_test(); } -add_task(function test_module_load() { +add_task(function test_module_load () { ok(CloudSync); let cloudSync = CloudSync(); ok(cloudSync.adapters); diff --git a/services/cloudsync/tests/xpcshell/test_tabs.js b/services/cloudsync/tests/xpcshell/test_tabs.js index aa78d3cf3da7..50f7a73dee1c 100644 --- a/services/cloudsync/tests/xpcshell/test_tabs.js +++ b/services/cloudsync/tests/xpcshell/test_tabs.js @@ -5,11 +5,11 @@ Cu.import("resource://gre/modules/CloudSync.jsm"); -function run_test() { +function run_test () { run_next_test(); } -add_task(function* test_get_remote_tabs() { +add_task(function* test_get_remote_tabs () { let cloudSync = CloudSync(); let clients = yield cloudSync.tabs.getRemoteTabs(); equal(clients.length, 0); @@ -17,9 +17,9 @@ add_task(function* test_get_remote_tabs() { yield cloudSync.tabs.mergeRemoteTabs({ id: "001", name: "FakeClient", - }, [ - {url:"https://www.google.ca?a=å%20ä%20ö", title:"Google Canada", icon:"https://www.google.ca/favicon.ico", lastUsed:0}, - {url:"http://www.reddit.com", title:"Reddit", icon:"http://www.reddit.com/favicon.ico", lastUsed:1}, + },[ + {url:"https://www.google.ca?a=å%20ä%20ö",title:"Google Canada",icon:"https://www.google.ca/favicon.ico",lastUsed:0}, + {url:"http://www.reddit.com",title:"Reddit",icon:"http://www.reddit.com/favicon.ico",lastUsed:1}, ]); ok(cloudSync.tabs.hasRemoteTabs()); diff --git a/services/common/async.js b/services/common/async.js index 0f17df0068c0..e8cd50eeeb2c 100644 --- a/services/common/async.js +++ b/services/common/async.js @@ -226,7 +226,7 @@ this.Async = { promiseSpinningly(promise) { let cb = Async.makeSpinningCallback(); - promise.then(result => { + promise.then(result => { cb(null, result); }, err => { cb(err || new Error("Promise rejected without explicit error")); diff --git a/services/common/blocklist-clients.js b/services/common/blocklist-clients.js index 69037e154a82..6ae20e0ea462 100644 --- a/services/common/blocklist-clients.js +++ b/services/common/blocklist-clients.js @@ -92,7 +92,7 @@ function kintoClient(connection, bucket) { let config = { remote: base, - bucket, + bucket: bucket, adapter: FirefoxAdapter, adapterOptions: {sqliteHandle: connection}, }; @@ -280,7 +280,7 @@ function* updatePinningList(records) { // write each KeyPin entry to the preload list for (let item of records) { try { - const {pinType, pins = [], versions} = item; + const {pinType, pins=[], versions} = item; if (versions.indexOf(appInfo.version) != -1) { if (pinType == "KeyPin" && pins.length) { siteSecurityService.setKeyPins(item.hostName, @@ -301,6 +301,8 @@ function* updatePinningList(records) { // 1254099. } } + } else { + return; } } @@ -318,9 +320,9 @@ function* updateJSONBlocklist(filename, records) { yield OS.File.writeAtomic(path, serialized, {tmpPath: path + ".tmp"}); // Notify change to `nsBlocklistService` - const eventData = {filename}; + const eventData = {filename: filename}; Services.cpmm.sendAsyncMessage("Blocklist:reload-from-disk", eventData); - } catch (e) { + } catch(e) { Cu.reportError(e); } } diff --git a/services/common/hawkclient.js b/services/common/hawkclient.js index 31437c5d6881..88e9c2f2d24a 100644 --- a/services/common/hawkclient.js +++ b/services/common/hawkclient.js @@ -114,9 +114,9 @@ this.HawkClient.prototype = { * @param error * A string or object describing the error */ - _constructError(restResponse, error) { + _constructError: function(restResponse, error) { let errorObj = { - error, + error: error, // This object is likely to be JSON.stringify'd, but neither Error() // objects nor Components.Exception objects do the right thing there, // so we add a new element which is simply the .toString() version of @@ -156,12 +156,12 @@ this.HawkClient.prototype = { * For HAWK clock skew and replay protection, see * https://github.com/hueniverse/hawk#replay-protection */ - _updateClockOffset(dateString) { + _updateClockOffset: function(dateString) { try { let serverDateMsec = Date.parse(dateString); this._localtimeOffsetMsec = serverDateMsec - this.now(); log.debug("Clock offset vs " + this.host + ": " + this._localtimeOffsetMsec); - } catch (err) { + } catch(err) { log.warn("Bad date header in server response: " + dateString); } }, @@ -180,7 +180,7 @@ this.HawkClient.prototype = { /* * return current time in milliseconds */ - now() { + now: function() { return Date.now(); }, @@ -203,8 +203,8 @@ this.HawkClient.prototype = { * as JSON and contains an 'error' property, the promise will be * rejected with this JSON-parsed response. */ - request(path, method, credentials = null, payloadObj = {}, extraHeaders = {}, - retryOK = true) { + request: function(path, method, credentials=null, payloadObj={}, extraHeaders = {}, + retryOK=true) { method = method.toLowerCase(); let deferred = Promise.defer(); @@ -263,7 +263,7 @@ this.HawkClient.prototype = { let jsonResponse = {}; try { jsonResponse = JSON.parse(restResponse.body); - } catch (notJSON) {} + } catch(notJSON) {} let okResponse = (200 <= status && status < 300); if (!okResponse || jsonResponse.error) { @@ -275,7 +275,7 @@ this.HawkClient.prototype = { // It's up to the caller to know how to decode the response. // We just return the whole response. deferred.resolve(this.response); - } + }; function onComplete(error) { try { @@ -319,7 +319,7 @@ this.HawkClient.prototype = { observerPrefix: null, // Given an optional header value, notify that a backoff has been requested. - _maybeNotifyBackoff(response, headerName) { + _maybeNotifyBackoff: function (response, headerName) { if (!this.observerPrefix || !response.headers) { return; } @@ -339,7 +339,7 @@ this.HawkClient.prototype = { }, // override points for testing. - newHAWKAuthenticatedRESTRequest(uri, credentials, extra) { + newHAWKAuthenticatedRESTRequest: function(uri, credentials, extra) { return new HAWKAuthenticatedRESTRequest(uri, credentials, extra); }, diff --git a/services/common/hawkrequest.js b/services/common/hawkrequest.js index a2fd9029f07d..454960b7b95c 100644 --- a/services/common/hawkrequest.js +++ b/services/common/hawkrequest.js @@ -53,7 +53,7 @@ const Prefs = new Preferences("services.common.rest."); */ this.HAWKAuthenticatedRESTRequest = - function HawkAuthenticatedRESTRequest(uri, credentials, extra = {}) { + function HawkAuthenticatedRESTRequest(uri, credentials, extra={}) { RESTRequest.call(this, uri); this.credentials = credentials; @@ -79,7 +79,7 @@ HAWKAuthenticatedRESTRequest.prototype = { localtimeOffsetMsec: this.localtimeOffsetMsec, credentials: this.credentials, payload: data && JSON.stringify(data) || "", - contentType, + contentType: contentType, }; let header = CryptoUtils.computeHAWK(this.uri, method, options); this.setHeader("Authorization", header.field); @@ -157,19 +157,19 @@ this.Intl = function Intl() { }; this.Intl.prototype = { - init() { + init: function() { Services.prefs.addObserver("intl.accept_languages", this, false); }, - uninit() { + uninit: function() { Services.prefs.removeObserver("intl.accept_languages", this); }, - observe(subject, topic, data) { + observe: function(subject, topic, data) { this.readPref(); }, - readPref() { + readPref: function() { this._everRead = true; try { this._accepted = Services.prefs.getComplexValue( diff --git a/services/common/kinto-storage-adapter.js b/services/common/kinto-storage-adapter.js index 01a6e357ed8a..8896ed9dda3b 100644 --- a/services/common/kinto-storage-adapter.js +++ b/services/common/kinto-storage-adapter.js @@ -329,7 +329,7 @@ class FirefoxAdapter extends Kinto.adapters.BaseAdapter { yield connection.executeTransaction(function* doImport() { for (let record of records) { const params = { - collection_name, + collection_name: collection_name, record_id: record.id, record: JSON.stringify(record), }; @@ -337,7 +337,7 @@ class FirefoxAdapter extends Kinto.adapters.BaseAdapter { } const lastModified = Math.max(...records.map(record => record.last_modified)); const params = { - collection_name, + collection_name: collection_name, }; const previousLastModified = yield connection.execute( statements.getLastModified, params).then(result => { @@ -347,7 +347,7 @@ class FirefoxAdapter extends Kinto.adapters.BaseAdapter { }); if (lastModified > previousLastModified) { const params = { - collection_name, + collection_name: collection_name, last_modified: lastModified, }; yield connection.execute(statements.saveLastModified, params); @@ -393,14 +393,15 @@ class FirefoxAdapter extends Kinto.adapters.BaseAdapter { return this._connection.executeTransaction(function* (conn) { const promises = []; - yield conn.execute(statements.scanAllRecords, null, function(row) { + yield conn.execute(statements.scanAllRecords, null, function (row) { const record = JSON.parse(row.getResultByName("record")); const record_id = row.getResultByName("record_id"); const collection_name = row.getResultByName("collection_name"); if (record._status === "deleted") { // Garbage collect deleted records. promises.push(conn.execute(statements.deleteData, { collection_name, record_id })); - } else { + } + else { const newRecord = Object.assign({}, record, { _status: "created", last_modified: undefined, diff --git a/services/common/modules-testing/storageserver.js b/services/common/modules-testing/storageserver.js index cf5a8618788a..650ac307fcad 100644 --- a/services/common/modules-testing/storageserver.js +++ b/services/common/modules-testing/storageserver.js @@ -275,7 +275,7 @@ ServerBSO.prototype = { * collection. This should be in the format returned by new_timestamp(). */ this.StorageServerCollection = - function StorageServerCollection(bsos, acceptNew, timestamp = new_timestamp()) { + function StorageServerCollection(bsos, acceptNew, timestamp=new_timestamp()) { this._bsos = bsos || {}; this.acceptNew = acceptNew || false; @@ -577,7 +577,7 @@ StorageServerCollection.prototype = { failed[record.id] = "Exception when processing."; } } - return {success, failed}; + return {success: success, failed: failed}; }, delete: function delete_(options) { @@ -805,7 +805,7 @@ StorageServerCollection.prototype = { let self = this; return function(request, response) { - switch (request.method) { + switch(request.method) { case "GET": return self.getHandler(request, response); @@ -845,9 +845,9 @@ StorageServerCollection.prototype = { }; -// ===========================================================================// +//===========================================================================// // httpd.js-based Storage server. // -// ===========================================================================// +//===========================================================================// /** * In general, the preferred way of using StorageServer is to directly @@ -946,7 +946,7 @@ StorageServer.prototype = { * The numeric port on which to start. The default is to choose * any available port. */ - startSynchronous: function startSynchronous(port = -1) { + startSynchronous: function startSynchronous(port=-1) { let cb = Async.makeSpinningCallback(); this.start(port, cb); cb.wait(); @@ -996,7 +996,7 @@ StorageServer.prototype = { this._log.info("Registering new user with server: " + username); this.users[username] = { - password, + password: password, collections: {}, quota: this.DEFAULT_QUOTA, }; @@ -1186,18 +1186,18 @@ StorageServer.prototype = { let collection = this.getCollection.bind(this, username); let createCollection = this.createCollection.bind(this, username); let createContents = this.createContents.bind(this, username); - let modified = function(collectionName) { + let modified = function (collectionName) { return collection(collectionName).timestamp; } let deleteCollections = this.deleteCollections.bind(this, username); let quota = this.getQuota.bind(this, username); return { - collection, - createCollection, - createContents, - deleteCollections, - modified, - quota, + collection: collection, + createCollection: createCollection, + createContents: createContents, + deleteCollections: deleteCollections, + modified: modified, + quota: quota, }; }, diff --git a/services/common/observers.js b/services/common/observers.js index 4d236384d7ad..c0b77104824e 100644 --- a/services/common/observers.js +++ b/services/common/observers.js @@ -33,7 +33,7 @@ this.Observers = { * * @returns the observer */ - add(topic, callback, thisObject) { + add: function(topic, callback, thisObject) { let observer = new Observer(topic, callback, thisObject); this._cache.push(observer); this._service.addObserver(observer, topic, true); @@ -53,13 +53,13 @@ this.Observers = { * @param thisObject {Object} [optional] * the object being used as |this| when calling a Function callback */ - remove(topic, callback, thisObject) { + remove: function(topic, callback, thisObject) { // This seems fairly inefficient, but I'm not sure how much better // we can make it. We could index by topic, but we can't index by callback // or thisObject, as far as I know, since the keys to JavaScript hashes // (a.k.a. objects) can apparently only be primitive values. - let [observer] = this._cache.filter(v => v.topic == topic && - v.callback == callback && + let [observer] = this._cache.filter(v => v.topic == topic && + v.callback == callback && v.thisObject == thisObject); if (observer) { this._service.removeObserver(observer, topic); @@ -83,9 +83,9 @@ this.Observers = { * the observer, wrap them in an object and pass them via the subject * parameter (i.e.: { foo: 1, bar: "some string", baz: myObject }) */ - notify(topic, subject, data) { + notify: function(topic, subject, data) { subject = (typeof subject == "undefined") ? null : new Subject(subject); - data = (typeof data == "undefined") ? null : data; + data = (typeof data == "undefined") ? null : data; this._service.notifyObservers(subject, topic, data); }, @@ -114,7 +114,7 @@ function Observer(topic, callback, thisObject) { Observer.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - observe(subject, topic, data) { + observe: function(subject, topic, data) { // Extract the wrapped object for subjects that are one of our wrappers // around a JS object. This way we support both wrapped subjects created // using this module and those that are real XPCOM components. @@ -128,7 +128,8 @@ Observer.prototype = { this.callback.call(this.thisObject, subject, data); else this.callback(subject, data); - } else // typeof this.callback == "object" (nsIObserver) + } + else // typeof this.callback == "object" (nsIObserver) this.callback.observe(subject, topic, data); } } @@ -139,11 +140,11 @@ function Subject(object) { // as one of our wrappers to distinguish between subjects that are one of our // wrappers (which we should unwrap when notifying our observers) and those // that are real JS XPCOM components (which we should pass through unaltered). - this.wrappedJSObject = { observersModuleSubjectWrapper: true, object }; + this.wrappedJSObject = { observersModuleSubjectWrapper: true, object: object }; } Subject.prototype = { QueryInterface: XPCOMUtils.generateQI([]), - getScriptableHelper() {}, - getInterfaces() {} + getScriptableHelper: function() {}, + getInterfaces: function() {} }; diff --git a/services/common/rest.js b/services/common/rest.js index 21e65f0308e4..7f08153c30c1 100644 --- a/services/common/rest.js +++ b/services/common/rest.js @@ -102,7 +102,7 @@ RESTRequest.prototype = { Ci.nsIChannelEventSink ]), - /** * Public API: ***/ + /*** Public API: ***/ /** * A constant boolean that indicates whether this object will automatically @@ -293,7 +293,7 @@ RESTRequest.prototype = { } }, - /** * Implementation stuff ***/ + /*** Implementation stuff ***/ dispatch: function dispatch(method, data, onComplete, onProgress) { if (this.status != this.NOT_SENT) { @@ -412,7 +412,7 @@ RESTRequest.prototype = { this.onComplete(error); }, - /** * nsIStreamListener ***/ + /*** nsIStreamListener ***/ onStartRequest: function onStartRequest(channel) { if (this.status == this.ABORTED) { @@ -573,13 +573,13 @@ RESTRequest.prototype = { this.delayTimeout(); }, - /** * nsIInterfaceRequestor ***/ + /*** nsIInterfaceRequestor ***/ - getInterface(aIID) { + getInterface: function(aIID) { return this.QueryInterface(aIID); }, - /** * nsIBadCertListener2 ***/ + /*** nsIBadCertListener2 ***/ notifyCertProblem: function notifyCertProblem(socketInfo, sslStatus, targetHost) { this._log.warn("Invalid HTTPS certificate encountered!"); @@ -601,7 +601,7 @@ RESTRequest.prototype = { return isInternal && isSameURI; }, - /** * nsIChannelEventSink ***/ + /*** nsIChannelEventSink ***/ asyncOnChannelRedirect: function asyncOnChannelRedirect(oldChannel, newChannel, flags, callback) { @@ -707,7 +707,7 @@ RESTResponse.prototype = { try { this._log.trace("Processing response headers."); let channel = this.request.channel.QueryInterface(Ci.nsIHttpChannel); - channel.visitResponseHeaders(function(header, value) { + channel.visitResponseHeaders(function (header, value) { headers[header.toLowerCase()] = value; }); } catch (ex) { diff --git a/services/common/stringbundle.js b/services/common/stringbundle.js index da2a14f75d4d..a07fa4831edd 100644 --- a/services/common/stringbundle.js +++ b/services/common/stringbundle.js @@ -45,7 +45,8 @@ StringBundle.prototype = { return Cc["@mozilla.org/intl/nslocaleservice;1"]. getService(Ci.nsILocaleService). getApplicationLocale(); - } catch (ex) { + } + catch(ex) { return null; } }, @@ -89,7 +90,7 @@ StringBundle.prototype = { * * @returns {String} the value of the string */ - get(key, args) { + get: function(key, args) { if (args) return this.stringBundle.formatStringFromName(key, args, args.length); else @@ -102,7 +103,7 @@ StringBundle.prototype = { * @returns {Array} * an array of objects with key and value properties */ - getAll() { + getAll: function() { let strings = []; // FIXME: for performance, return an enumerable array that wraps the string @@ -169,7 +170,7 @@ StringBundle.prototype = { * @returns {String} * the value of the string */ - getString(key) { + getString: function(key) { return this.get(key); }, @@ -185,7 +186,7 @@ StringBundle.prototype = { * @returns {String} * the formatted value of the string */ - getFormattedString(key, args) { + getFormattedString: function(key, args) { return this.get(key, args); }, diff --git a/services/common/tests/unit/head_helpers.js b/services/common/tests/unit/head_helpers.js index f7fbf7af43e7..b54045ec1d19 100644 --- a/services/common/tests/unit/head_helpers.js +++ b/services/common/tests/unit/head_helpers.js @@ -69,7 +69,7 @@ var _ = function(some, debug, text, to) { print(Array.slice(arguments).join(" ")); }; -function httpd_setup(handlers, port = -1) { +function httpd_setup (handlers, port=-1) { let server = new HttpServer(); for (let path in handlers) { server.registerPathHandler(path, handlers[path]); diff --git a/services/common/tests/unit/test_async_chain.js b/services/common/tests/unit/test_async_chain.js index 1f9bac9df3c6..c3abef2962ac 100644 --- a/services/common/tests/unit/test_async_chain.js +++ b/services/common/tests/unit/test_async_chain.js @@ -7,17 +7,17 @@ function run_test() { _("Chain a few async methods, making sure the 'this' object is correct."); let methods = { - save(x, callback) { + save: function(x, callback) { this.x = x; callback(x); }, - addX(x, callback) { + addX: function(x, callback) { callback(x + this.x); }, - double(x, callback) { + double: function(x, callback) { callback(x * 2); }, - neg(x, callback) { + neg: function(x, callback) { callback(-x); } }; diff --git a/services/common/tests/unit/test_async_querySpinningly.js b/services/common/tests/unit/test_async_querySpinningly.js index 76d4ffbbb135..8c63fe33c81c 100644 --- a/services/common/tests/unit/test_async_querySpinningly.js +++ b/services/common/tests/unit/test_async_querySpinningly.js @@ -85,10 +85,10 @@ function run_test() { _("Generate an execution error"); let query = "INSERT INTO moz_formhistory (fieldname, value) VALUES ('one', NULL)"; let stmt = Svc.Form.DBConnection.createStatement(query); - let r11, except; + let r11, except; ; try { r11 = Async.querySpinningly(stmt); - } catch (e) { + } catch(e) { except = e; } stmt.finalize() diff --git a/services/common/tests/unit/test_blocklist_certificates.js b/services/common/tests/unit/test_blocklist_certificates.js index df365ca9645e..423dd5d39aa4 100644 --- a/services/common/tests/unit/test_blocklist_certificates.js +++ b/services/common/tests/unit/test_blocklist_certificates.js @@ -31,7 +31,7 @@ function do_get_kinto_collection(collectionName, sqliteHandle) { // correctly and that simple kinto operations are working as expected. There // are more tests for core Kinto.js (and its storage adapter) in the // xpcshell tests under /services/common -add_task(function* test_something() { +add_task(function* test_something(){ const configPath = "/v1/"; const recordsPath = "/v1/buckets/blocklists/collections/certificates/records"; @@ -39,7 +39,7 @@ add_task(function* test_something() { `http://localhost:${server.identity.primaryPort}/v1`); // register a handler - function handleResponse(request, response) { + function handleResponse (request, response) { try { const sample = getSampleResponse(request, server.identity.primaryPort); if (!sample) { @@ -179,7 +179,7 @@ function getSampleResponse(req, port) { "serialNumber":"ATFpsA==", "id":"dabafde9-df4a-ddba-2548-748da04cc02c", "last_modified":4000 - }, { + },{ "subject":"MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQtZW50aXR5", "pubKeyHash":"VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8=", "id":"dabafde9-df4a-ddba-2548-748da04cc02d", @@ -200,12 +200,12 @@ function getSampleResponse(req, port) { "serialNumber":"not a base64 encoded serial", "id":"dabafde9-df4a-ddba-2548-748da04cc02e", "last_modified":5000 - }, { + },{ "subject":"not a base64 encoded subject", "pubKeyHash":"not a base64 encoded pubKeyHash", "id":"dabafde9-df4a-ddba-2548-748da04cc02f", "last_modified":5000 - }, { + },{ "subject":"MCIxIDAeBgNVBAMMF0Fub3RoZXIgVGVzdCBFbmQtZW50aXR5", "pubKeyHash":"VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8=", "id":"dabafde9-df4a-ddba-2548-748da04cc02g", diff --git a/services/common/tests/unit/test_blocklist_clients.js b/services/common/tests/unit/test_blocklist_clients.js index 57b2a68f25fc..cc405c2b32bd 100644 --- a/services/common/tests/unit/test_blocklist_clients.js +++ b/services/common/tests/unit/test_blocklist_clients.js @@ -17,9 +17,9 @@ const BinaryInputStream = CC("@mozilla.org/binaryinputstream;1", const kintoFilename = "kinto.sqlite"; const gBlocklistClients = [ - {client: BlocklistClients.AddonBlocklistClient, filename: BlocklistClients.FILENAME_ADDONS_JSON, testData: ["i808", "i720", "i539"]}, - {client: BlocklistClients.PluginBlocklistClient, filename: BlocklistClients.FILENAME_PLUGINS_JSON, testData: ["p1044", "p32", "p28"]}, - {client: BlocklistClients.GfxBlocklistClient, filename: BlocklistClients.FILENAME_GFX_JSON, testData: ["g204", "g200", "g36"]}, + {client: BlocklistClients.AddonBlocklistClient, filename: BlocklistClients.FILENAME_ADDONS_JSON, testData: ["i808","i720", "i539"]}, + {client: BlocklistClients.PluginBlocklistClient, filename: BlocklistClients.FILENAME_PLUGINS_JSON, testData: ["p1044","p32","p28"]}, + {client: BlocklistClients.GfxBlocklistClient, filename: BlocklistClients.FILENAME_GFX_JSON, testData: ["g204","g200","g36"]}, ]; @@ -118,7 +118,7 @@ function run_test() { }); } -add_task(function* test_records_obtained_from_server_are_stored_in_db() { +add_task(function* test_records_obtained_from_server_are_stored_in_db(){ for (let {client} of gBlocklistClients) { // Test an empty db populates let result = yield client.maybeSync(2000, Date.now()); @@ -134,7 +134,7 @@ add_task(function* test_records_obtained_from_server_are_stored_in_db() { }); add_task(clear_state); -add_task(function* test_list_is_written_to_file_in_profile() { +add_task(function* test_list_is_written_to_file_in_profile(){ for (let {client, filename, testData} of gBlocklistClients) { const profFile = FileUtils.getFile(KEY_PROFILEDIR, [filename]); strictEqual(profFile.exists(), false); @@ -148,7 +148,7 @@ add_task(function* test_list_is_written_to_file_in_profile() { }); add_task(clear_state); -add_task(function* test_current_server_time_is_saved_in_pref() { +add_task(function* test_current_server_time_is_saved_in_pref(){ for (let {client} of gBlocklistClients) { const before = Services.prefs.getIntPref(client.lastCheckTimePref); const serverTime = Date.now(); @@ -159,7 +159,7 @@ add_task(function* test_current_server_time_is_saved_in_pref() { }); add_task(clear_state); -add_task(function* test_update_json_file_when_addons_has_changes() { +add_task(function* test_update_json_file_when_addons_has_changes(){ for (let {client, filename, testData} of gBlocklistClients) { yield client.maybeSync(2000, Date.now() - 1000); const before = Services.prefs.getIntPref(client.lastCheckTimePref); @@ -180,7 +180,7 @@ add_task(function* test_update_json_file_when_addons_has_changes() { }); add_task(clear_state); -add_task(function* test_sends_reload_message_when_blocklist_has_changes() { +add_task(function* test_sends_reload_message_when_blocklist_has_changes(){ for (let {client, filename} of gBlocklistClients) { let received = yield new Promise((resolve, reject) => { Services.ppmm.addMessageListener("Blocklist:reload-from-disk", { @@ -195,7 +195,7 @@ add_task(function* test_sends_reload_message_when_blocklist_has_changes() { }); add_task(clear_state); -add_task(function* test_do_nothing_when_blocklist_is_up_to_date() { +add_task(function* test_do_nothing_when_blocklist_is_up_to_date(){ for (let {client, filename} of gBlocklistClients) { yield client.maybeSync(2000, Date.now() - 1000); const before = Services.prefs.getIntPref(client.lastCheckTimePref); diff --git a/services/common/tests/unit/test_blocklist_pinning.js b/services/common/tests/unit/test_blocklist_pinning.js index ae1fa57ec747..7d1f4053c3ee 100644 --- a/services/common/tests/unit/test_blocklist_pinning.js +++ b/services/common/tests/unit/test_blocklist_pinning.js @@ -24,7 +24,7 @@ Cu.import("resource://testing-common/AppInfo.jsm", this); updateAppInfo({ name: appName, ID: id, - version, + version: version, platformVersion: platformVersion ? platformVersion : "1.0", crashReporter: true, }); @@ -49,7 +49,7 @@ function do_get_kinto_collection(connection, collectionName) { // Some simple tests to demonstrate that the core preload sync operations work // correctly and that simple kinto operations are working as expected. -add_task(function* test_something() { +add_task(function* test_something(){ // set the collection name explicitly - since there will be version // specific collection names in prefs Services.prefs.setCharPref(PREF_BLOCKLIST_PINNING_COLLECTION, @@ -64,7 +64,7 @@ add_task(function* test_something() { `http://localhost:${server.identity.primaryPort}/v1`); // register a handler - function handleResponse(request, response) { + function handleResponse (request, response) { try { const sample = getSampleResponse(request, server.identity.primaryPort); if (!sample) { @@ -245,7 +245,7 @@ function getSampleResponse(req, port) { "versions" : [appInfo.version], "id":"dabafde9-df4a-ddba-2548-748da04cc02c", "last_modified":4000 - }, { + },{ "pinType": "KeyPin", "hostName": "three.example.com", "includeSubdomains": false, @@ -255,7 +255,7 @@ function getSampleResponse(req, port) { "versions" : [appInfo.version, "some other version that won't match"], "id":"dabafde9-df4a-ddba-2548-748da04cc02d", "last_modified":4000 - }, { + },{ "pinType": "KeyPin", "hostName": "four.example.com", "includeSubdomains": false, @@ -265,7 +265,7 @@ function getSampleResponse(req, port) { "versions" : ["some version that won't match"], "id":"dabafde9-df4a-ddba-2548-748da04cc02e", "last_modified":4000 - }, { + },{ "pinType": "STSPin", "hostName": "five.example.com", "includeSubdomains": false, @@ -289,16 +289,16 @@ function getSampleResponse(req, port) { "pinType": "KeyPin", "id":"dabafde9-df4a-ddba-2548-748da04cc02f", "last_modified":5000 - }, { + },{ "irrelevant":"this entry has data of the wrong type", "pinType": "KeyPin", "hostName": 3, "includeSubdomains": "nonsense", "expires": "more nonsense", - "pins" : [1, 2, 3, 4], + "pins" : [1,2,3,4], "id":"dabafde9-df4a-ddba-2548-748da04cc030", "last_modified":5000 - }, { + },{ "irrelevant":"this entry is missing the actual pins", "pinType": "KeyPin", "hostName": "missingpins.example.com", @@ -307,7 +307,7 @@ function getSampleResponse(req, port) { "versions" : [appInfo.version], "id":"dabafde9-df4a-ddba-2548-748da04cc031", "last_modified":5000 - }, { + },{ "pinType": "STSPin", "hostName": "five.example.com", "includeSubdomains": true, diff --git a/services/common/tests/unit/test_blocklist_signatures.js b/services/common/tests/unit/test_blocklist_signatures.js index 38700f0b0792..e0464821c35f 100644 --- a/services/common/tests/unit/test_blocklist_signatures.js +++ b/services/common/tests/unit/test_blocklist_signatures.js @@ -65,7 +65,7 @@ function* checkRecordCount(count) { const sqliteHandle = yield FirefoxAdapter.openConnection({path: kintoFilename}); const config = { remote: base, - bucket, + bucket: bucket, adapter: FirefoxAdapter, adapterOptions: {sqliteHandle}, }; @@ -83,7 +83,7 @@ function* checkRecordCount(count) { // Check to ensure maybeSync is called with correct values when a changes // document contains information on when a collection was last modified -add_task(function* test_check_signatures() { +add_task(function* test_check_signatures(){ const port = server.identity.primaryPort; // a response to give the client when the cert chain is expected @@ -97,7 +97,7 @@ add_task(function* test_check_signatures() { public_key: "fake", "content-signature": `x5u=http://localhost:${port}/test_blocklist_signatures/test_cert_chain.pem;p384ecdsa=${signature}`, signature_encoding: "rs_base64url", - signature, + signature: signature, hash_algorithm: "sha384", ref: "1yryrnmzou5rf31ou80znpnq8n" } @@ -107,7 +107,7 @@ add_task(function* test_check_signatures() { function makeMetaResponse(eTag, body, comment) { return { - comment, + comment: comment, sampleHeaders: [ "Content-Type: application/json; charset=UTF-8", `ETag: \"${eTag}\"` @@ -117,8 +117,8 @@ add_task(function* test_check_signatures() { }; } - function registerHandlers(responses) { - function handleResponse(serverTimeMillis, request, response) { + function registerHandlers(responses){ + function handleResponse (serverTimeMillis, request, response) { const key = `${request.method}:${request.path}?${request.queryString}`; const available = responses[key]; const sampled = available.length > 1 ? available.shift() : available[0]; diff --git a/services/common/tests/unit/test_blocklist_updater.js b/services/common/tests/unit/test_blocklist_updater.js index 97d4bc17330e..070b7f4ea76c 100644 --- a/services/common/tests/unit/test_blocklist_updater.js +++ b/services/common/tests/unit/test_blocklist_updater.js @@ -9,11 +9,11 @@ const PREF_CLOCK_SKEW_SECONDS = "services.blocklist.clock_skew_seconds"; // Check to ensure maybeSync is called with correct values when a changes // document contains information on when a collection was last modified -add_task(function* test_check_maybeSync() { +add_task(function* test_check_maybeSync(){ const changesPath = "/v1/buckets/monitor/collections/changes/records"; // register a handler - function handleResponse(serverTimeMillis, request, response) { + function handleResponse (serverTimeMillis, request, response) { try { const sampled = getSampleResponse(request, server.identity.primaryPort); if (!sampled) { @@ -87,7 +87,7 @@ add_task(function* test_check_maybeSync() { Services.prefs.setIntPref(PREF_LAST_UPDATE, 0); // If server has no change, a 304 is received, maybeSync() is not called. updater.addTestBlocklistClient("test-collection", { - maybeSync: () => { throw new Error("Should not be called"); } + maybeSync: () => {throw new Error("Should not be called");} }); yield updater.checkVersions(); // Last update is overwritten @@ -95,7 +95,7 @@ add_task(function* test_check_maybeSync() { // Simulate a server error. - function simulateErrorResponse(request, response) { + function simulateErrorResponse (request, response) { response.setHeader("Date", (new Date(3000)).toUTCString()); response.setHeader("Content-Type", "application/json; charset=UTF-8"); response.write(JSON.stringify({ diff --git a/services/common/tests/unit/test_hawkclient.js b/services/common/tests/unit/test_hawkclient.js index c309156a7197..0896cf00c846 100644 --- a/services/common/tests/unit/test_hawkclient.js +++ b/services/common/tests/unit/test_hawkclient.js @@ -156,7 +156,7 @@ add_task(function* test_server_error() { try { yield client.request("/foo", method, TEST_CREDS); do_throw("Expected an error"); - } catch (err) { + } catch(err) { do_check_eq(418, err.code); do_check_eq("I am a Teapot", err.message); } @@ -179,7 +179,7 @@ add_task(function* test_server_error_json() { try { yield client.request("/foo", method, TEST_CREDS); do_throw("Expected an error"); - } catch (err) { + } catch(err) { do_check_eq("Cannot get ye flask.", err.error); } @@ -312,7 +312,7 @@ add_task(function* test_retry_request_on_fail() { let message = "i love you!!!"; response.setStatusLine(request.httpVersion, 200, "OK"); response.bodyOutputStream.write(message, message.length); - + return; } }); @@ -417,7 +417,7 @@ add_task(function* test_500_no_retry() { try { yield client.request("/no-shutup", method, credentials); do_throw("Expected an error"); - } catch (err) { + } catch(err) { do_check_eq(err.code, 500); } @@ -461,7 +461,7 @@ add_task(function* test_401_then_500() { let message = "Cannot get ye flask."; response.setStatusLine(request.httpVersion, 500, "Internal server error"); response.bodyOutputStream.write(message, message.length); - + return; } }); @@ -480,7 +480,7 @@ add_task(function* test_401_then_500() { // Request will have bad timestamp; client will retry once try { yield client.request("/maybe", method, credentials); - } catch (err) { + } catch(err) { do_check_eq(err.code, 500); } do_check_eq(attempts, 2); @@ -493,7 +493,7 @@ add_task(function* throw_if_not_json_body() { try { yield client.request("/bogus", "GET", {}, "I am not json"); do_throw("Expected an error"); - } catch (err) { + } catch(err) { do_check_true(!!err.message); } }); @@ -501,7 +501,7 @@ add_task(function* throw_if_not_json_body() { // End of tests. // Utility functions follow -function getTimestampDelta(authHeader, now = Date.now()) { +function getTimestampDelta(authHeader, now=Date.now()) { let tsMS = new Date( parseInt(/ts="(\d+)"/.exec(authHeader)[1], 10) * SECOND_MS); return Math.abs(tsMS - now); diff --git a/services/common/tests/unit/test_hawkrequest.js b/services/common/tests/unit/test_hawkrequest.js index af66b695ba19..7f598125a9ed 100644 --- a/services/common/tests/unit/test_hawkrequest.js +++ b/services/common/tests/unit/test_hawkrequest.js @@ -9,13 +9,13 @@ Cu.import("resource://services-common/hawkrequest.js"); // https://github.com/mozilla/fxa-auth-server/wiki/onepw-protocol#wiki-use-session-certificatesign-etc var SESSION_KEYS = { - sessionToken: h("a0a1a2a3a4a5a6a7 a8a9aaabacadaeaf" + + sessionToken: h("a0a1a2a3a4a5a6a7 a8a9aaabacadaeaf"+ "b0b1b2b3b4b5b6b7 b8b9babbbcbdbebf"), - tokenID: h("c0a29dcf46174973 da1378696e4c82ae" + + tokenID: h("c0a29dcf46174973 da1378696e4c82ae"+ "10f723cf4f4d9f75 e39f4ae3851595ab"), - reqHMACkey: h("9d8f22998ee7f579 8b887042466b72d5" + + reqHMACkey: h("9d8f22998ee7f579 8b887042466b72d5"+ "3e56ab0c094388bf 65831f702d2febc0"), }; @@ -75,7 +75,7 @@ add_test(function test_intl_accept_language() { do_print("Checked " + testCount + " languages. Removing checkLanguagePref as pref observer."); Services.prefs.removeObserver("intl.accept_languages", checkLanguagePref); run_next_test(); - + return; }); } }); @@ -201,7 +201,7 @@ add_test(function test_hawk_language_pref_changed() { do_check_eq(languages[0], request._intl.accept_languages); // Change the language pref ... - setLanguage(languages[1]); + setLanguage(languages[1]); CommonUtils.nextTick(testRequest); } diff --git a/services/common/tests/unit/test_kinto.js b/services/common/tests/unit/test_kinto.js index 29e5fa1e8157..c4bda3159da5 100644 --- a/services/common/tests/unit/test_kinto.js +++ b/services/common/tests/unit/test_kinto.js @@ -17,7 +17,7 @@ function do_get_kinto_sqliteHandle() { return FirefoxAdapter.openConnection({path: kintoFilename}); } -function do_get_kinto_collection(sqliteHandle, collection = "test_collection") { +function do_get_kinto_collection(sqliteHandle, collection="test_collection") { let config = { remote:`http://localhost:${server.identity.primaryPort}/v1/`, headers: {Authorization: "Basic " + btoa("user:pass")}, @@ -154,7 +154,7 @@ add_task(function* test_kinto_clear() { add_task(clear_collection); -add_task(function* test_kinto_delete() { +add_task(function* test_kinto_delete(){ let sqliteHandle; try { sqliteHandle = yield do_get_kinto_sqliteHandle(); @@ -180,7 +180,7 @@ add_task(function* test_kinto_delete() { } }); -add_task(function* test_kinto_list() { +add_task(function* test_kinto_list(){ let sqliteHandle; try { sqliteHandle = yield do_get_kinto_sqliteHandle(); @@ -214,7 +214,7 @@ add_task(function* test_kinto_list() { add_task(clear_collection); -add_task(function* test_loadDump_ignores_already_imported_records() { +add_task(function* test_loadDump_ignores_already_imported_records(){ let sqliteHandle; try { sqliteHandle = yield do_get_kinto_sqliteHandle(); @@ -230,7 +230,7 @@ add_task(function* test_loadDump_ignores_already_imported_records() { add_task(clear_collection); -add_task(function* test_loadDump_should_overwrite_old_records() { +add_task(function* test_loadDump_should_overwrite_old_records(){ let sqliteHandle; try { sqliteHandle = yield do_get_kinto_sqliteHandle(); @@ -247,7 +247,7 @@ add_task(function* test_loadDump_should_overwrite_old_records() { add_task(clear_collection); -add_task(function* test_loadDump_should_not_overwrite_unsynced_records() { +add_task(function* test_loadDump_should_not_overwrite_unsynced_records(){ let sqliteHandle; try { sqliteHandle = yield do_get_kinto_sqliteHandle(); @@ -264,7 +264,7 @@ add_task(function* test_loadDump_should_not_overwrite_unsynced_records() { add_task(clear_collection); -add_task(function* test_loadDump_should_not_overwrite_records_without_last_modified() { +add_task(function* test_loadDump_should_not_overwrite_records_without_last_modified(){ let sqliteHandle; try { sqliteHandle = yield do_get_kinto_sqliteHandle(); @@ -284,11 +284,11 @@ add_task(clear_collection); // Now do some sanity checks against a server - we're not looking to test // core kinto.js functionality here (there is excellent test coverage in // kinto.js), more making sure things are basically working as expected. -add_task(function* test_kinto_sync() { +add_task(function* test_kinto_sync(){ const configPath = "/v1/"; const recordsPath = "/v1/buckets/default/collections/test_collection/records"; // register a handler - function handleResponse(request, response) { + function handleResponse (request, response) { try { const sampled = getSampleResponse(request, server.identity.primaryPort); if (!sampled) { diff --git a/services/common/tests/unit/test_load_modules.js b/services/common/tests/unit/test_load_modules.js index d9a404934d13..66ecf0734ac6 100644 --- a/services/common/tests/unit/test_load_modules.js +++ b/services/common/tests/unit/test_load_modules.js @@ -25,7 +25,7 @@ const non_android_test_modules = [ "storageserver.js", ]; -function expectImportsToSucceed(mm, base = MODULE_BASE) { +function expectImportsToSucceed(mm, base=MODULE_BASE) { for (let m of mm) { let resource = base + m; let succeeded = false; @@ -40,7 +40,7 @@ function expectImportsToSucceed(mm, base = MODULE_BASE) { } } -function expectImportsToFail(mm, base = MODULE_BASE) { +function expectImportsToFail(mm, base=MODULE_BASE) { for (let m of mm) { let resource = base + m; let succeeded = false; diff --git a/services/common/tests/unit/test_observers.js b/services/common/tests/unit/test_observers.js index 84a2b01ca241..f11e83d5d2a3 100644 --- a/services/common/tests/unit/test_observers.js +++ b/services/common/tests/unit/test_observers.js @@ -36,7 +36,7 @@ add_test(function test_function_observer() { add_test(function test_method_observer() { let obj = { foo: false, - onFoo(subject, data) { + onFoo: function(subject, data) { this.foo = !this.foo; do_check_eq(subject, gSubject); do_check_eq(data, "some data"); @@ -59,7 +59,7 @@ add_test(function test_method_observer() { add_test(function test_object_observer() { let obj = { foo: false, - observe(subject, topic, data) { + observe: function(subject, topic, data) { this.foo = !this.foo; do_check_eq(subject, gSubject); diff --git a/services/common/tests/unit/test_restrequest.js b/services/common/tests/unit/test_restrequest.js index 69961f8b4a20..162e0f51784f 100644 --- a/services/common/tests/unit/test_restrequest.js +++ b/services/common/tests/unit/test_restrequest.js @@ -76,7 +76,7 @@ add_test(function test_proxy_auth_redirect() { installFakePAC(); let res = new RESTRequest(server.baseURI + "/original"); - res.get(function(error) { + res.get(function (error) { do_check_true(pacFetched); do_check_true(fetched); do_check_true(!error); @@ -110,7 +110,7 @@ add_test(function test_simple_get() { let handler = httpd_handler(200, "OK", "Huzzah!"); let server = httpd_setup({"/resource": handler}); - let request = new RESTRequest(server.baseURI + "/resource").get(function(error) { + let request = new RESTRequest(server.baseURI + "/resource").get(function (error) { do_check_eq(error, null); do_check_eq(this.status, this.COMPLETED); @@ -134,7 +134,7 @@ add_test(function test_get() { let request = new RESTRequest(server.baseURI + "/resource"); do_check_eq(request.status, request.NOT_SENT); - request.onProgress = request.onComplete = function() { + request.onProgress = request.onComplete = function () { do_throw("This function should have been overwritten!"); }; @@ -146,7 +146,7 @@ add_test(function test_get() { do_check_true(!!(this.channel.loadFlags & Ci.nsIRequest.LOAD_BYPASS_CACHE)); do_check_true(!!(this.channel.loadFlags & Ci.nsIRequest.INHIBIT_CACHING)); - } + }; function onComplete(error) { do_check_eq(error, null); @@ -158,17 +158,17 @@ add_test(function test_get() { do_check_eq(handler.request.method, "GET"); do_check_true(onProgress_called); - CommonUtils.nextTick(function() { + CommonUtils.nextTick(function () { do_check_eq(request.onComplete, null); do_check_eq(request.onProgress, null); server.stop(run_next_test); }); - } + }; do_check_eq(request.get(onComplete, onProgress), request); do_check_eq(request.status, request.SENT); do_check_eq(request.method, "GET"); - do_check_throws(function() { + do_check_throws(function () { request.get(); }); }); @@ -315,7 +315,7 @@ function check_posting_data(method) { let request = new RESTRequest(server.baseURI + "/resource"); do_check_eq(request.status, request.NOT_SENT); - request.onProgress = request.onComplete = function() { + request.onProgress = request.onComplete = function () { do_throw("This function should have been overwritten!"); }; @@ -324,7 +324,7 @@ function check_posting_data(method) { onProgress_called = true; do_check_eq(this.status, request.IN_PROGRESS); do_check_true(this.response.body.length > 0); - } + }; function onComplete(error) { do_check_eq(error, null); @@ -339,17 +339,17 @@ function check_posting_data(method) { do_check_eq(handler.request.getHeader("Content-Type"), "text/plain"); do_check_true(onProgress_called); - CommonUtils.nextTick(function() { + CommonUtils.nextTick(function () { do_check_eq(request.onComplete, null); do_check_eq(request.onProgress, null); server.stop(run_next_test); }); - } + }; do_check_eq(request[funcName]("Hullo?", onComplete, onProgress), request); do_check_eq(request.status, request.SENT); do_check_eq(request.method, method); - do_check_throws(function() { + do_check_throws(function () { request[funcName]("Hai!"); }); } @@ -385,7 +385,7 @@ add_test(function test_delete() { let request = new RESTRequest(server.baseURI + "/resource"); do_check_eq(request.status, request.NOT_SENT); - request.onProgress = request.onComplete = function() { + request.onProgress = request.onComplete = function () { do_throw("This function should have been overwritten!"); }; @@ -394,7 +394,7 @@ add_test(function test_delete() { onProgress_called = true; do_check_eq(this.status, request.IN_PROGRESS); do_check_true(this.response.body.length > 0); - } + }; function onComplete(error) { do_check_eq(error, null); @@ -406,17 +406,17 @@ add_test(function test_delete() { do_check_eq(handler.request.method, "DELETE"); do_check_true(onProgress_called); - CommonUtils.nextTick(function() { + CommonUtils.nextTick(function () { do_check_eq(request.onComplete, null); do_check_eq(request.onProgress, null); server.stop(run_next_test); }); - } + }; do_check_eq(request.delete(onComplete, onProgress), request); do_check_eq(request.status, request.SENT); do_check_eq(request.method, "DELETE"); - do_check_throws(function() { + do_check_throws(function () { request.delete(); }); }); @@ -429,7 +429,7 @@ add_test(function test_get_404() { let server = httpd_setup({"/resource": handler}); let request = new RESTRequest(server.baseURI + "/resource"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.status, this.COMPLETED); @@ -455,7 +455,7 @@ add_test(function test_put_json() { number: 42 }; let request = new RESTRequest(server.baseURI + "/resource"); - request.put(sample_data, function(error) { + request.put(sample_data, function (error) { do_check_eq(error, null); do_check_eq(this.status, this.COMPLETED); @@ -485,7 +485,7 @@ add_test(function test_post_json() { number: 42 }; let request = new RESTRequest(server.baseURI + "/resource"); - request.post(sample_data, function(error) { + request.post(sample_data, function (error) { do_check_eq(error, null); do_check_eq(this.status, this.COMPLETED); @@ -511,7 +511,7 @@ add_test(function test_post_json() { let sample_data = "hello"; let request = new RESTRequest(server.baseURI + "/resource"); - request.post(sample_data, function(error) { + request.post(sample_data, function (error) { do_check_eq(error, null); do_check_eq(this.status, this.COMPLETED); @@ -536,7 +536,7 @@ add_test(function test_put_override_content_type() { let request = new RESTRequest(server.baseURI + "/resource"); request.setHeader("Content-Type", "application/lolcat"); - request.put("O HAI!!1!", function(error) { + request.put("O HAI!!1!", function (error) { do_check_eq(error, null); do_check_eq(this.status, this.COMPLETED); @@ -561,7 +561,7 @@ add_test(function test_post_override_content_type() { let request = new RESTRequest(server.baseURI + "/resource"); request.setHeader("Content-Type", "application/lolcat"); - request.post("O HAI!!1!", function(error) { + request.post("O HAI!!1!", function (error) { do_check_eq(error, null); do_check_eq(this.status, this.COMPLETED); @@ -589,7 +589,7 @@ add_test(function test_get_no_headers() { "connection", "pragma", "cache-control", "content-length"]; - new RESTRequest(server.baseURI + "/resource").get(function(error) { + new RESTRequest(server.baseURI + "/resource").get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 200); @@ -616,7 +616,7 @@ add_test(function test_changing_uri() { let request = new RESTRequest("http://localhost:1234/the-wrong-resource"); request.uri = CommonUtils.makeURI(server.baseURI + "/resource"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 200); server.stop(run_next_test); @@ -636,7 +636,7 @@ add_test(function test_request_setHeader() { request.setHeader("X-WHAT-is-Weave", "more awesomer"); request.setHeader("Another-Header", "Hello World"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 200); @@ -661,7 +661,7 @@ add_test(function test_response_headers() { let server = httpd_setup({"/resource": handler}); let request = new RESTRequest(server.baseURI + "/resource"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 200); @@ -683,7 +683,7 @@ add_test(function test_connection_refused() { request.onProgress = function onProgress() { do_throw("Shouldn't have called request.onProgress()!"); }; - request.get(function(error) { + request.get(function (error) { do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED); do_check_eq(error.message, "NS_ERROR_CONNECTION_REFUSED"); do_check_eq(this.status, this.COMPLETED); @@ -704,23 +704,23 @@ add_test(function test_abort() { let request = new RESTRequest(server.baseURI + "/resource"); // Aborting a request that hasn't been sent yet is pointless and will throw. - do_check_throws(function() { + do_check_throws(function () { request.abort(); }); - request.onProgress = request.onComplete = function() { + request.onProgress = request.onComplete = function () { do_throw("Shouldn't have gotten here!"); }; request.get(); request.abort(); // Aborting an already aborted request is pointless and will throw. - do_check_throws(function() { + do_check_throws(function () { request.abort(); }); do_check_eq(request.status, request.ABORTED); - CommonUtils.nextTick(function() { + CommonUtils.nextTick(function () { server.stop(run_next_test); }); }); @@ -746,7 +746,7 @@ add_test(function test_timeout() { let request = new RESTRequest(uri + "/resource"); request.timeout = 0.1; // 100 milliseconds - request.get(function(error) { + request.get(function (error) { do_check_eq(error.result, Cr.NS_ERROR_NET_TIMEOUT); do_check_eq(this.status, this.ABORTED); @@ -818,7 +818,7 @@ add_test(function test_new_channel() { redirectURL = server2.baseURI + "/resource"; function advance() { - server1.stop(function() { + server1.stop(function () { server2.stop(run_next_test); }); } @@ -863,7 +863,7 @@ add_test(function test_not_sending_cookie() { cookieSer.setCookieString(uri, null, "test=test; path=/;", null); let res = new RESTRequest(server.baseURI + "/test"); - res.get(function(error) { + res.get(function (error) { do_check_null(error); do_check_true(this.response.success); do_check_eq("COOKIE!", this.response.body); diff --git a/services/common/tests/unit/test_storage_adapter.js b/services/common/tests/unit/test_storage_adapter.js index 5c23d257475c..45c7ab0c33b0 100644 --- a/services/common/tests/unit/test_storage_adapter.js +++ b/services/common/tests/unit/test_storage_adapter.js @@ -23,7 +23,7 @@ function do_get_kinto_db() { } function cleanup_kinto() { - add_test(function cleanup_kinto_files() { + add_test(function cleanup_kinto_files(){ let kintoDB = do_get_kinto_db(); // clean up the db kintoDB.remove(false); @@ -251,7 +251,7 @@ add_test(function test_creation_from_empty_db() { let kintoDB = do_get_kinto_db(); let emptyDB = do_get_file("test_storage_adapter/empty.sqlite"); - emptyDB.copyTo(profile, kintoFilename); + emptyDB.copyTo(profile,kintoFilename); run_next_test(); }); diff --git a/services/common/tests/unit/test_storage_server.js b/services/common/tests/unit/test_storage_server.js index 8609a0fa50c5..04b4dfbbbdfe 100644 --- a/services/common/tests/unit/test_storage_server.js +++ b/services/common/tests/unit/test_storage_server.js @@ -12,7 +12,7 @@ const DEFAULT_PASSWORD = "password"; /** * Helper function to prepare a RESTRequest against the server. */ -function localRequest(server, path, user = DEFAULT_USER, password = DEFAULT_PASSWORD) { +function localRequest(server, path, user=DEFAULT_USER, password=DEFAULT_PASSWORD) { _("localRequest: " + path); let identity = server.server.identity; let url = identity.primaryScheme + "://" + identity.primaryHost + ":" + @@ -121,7 +121,7 @@ add_test(function test_creation() { }); do_check_true(!!server); - server.start(-1, function() { + server.start(-1, function () { _("Started on " + server.port); server.stop(run_next_test); }); @@ -191,7 +191,7 @@ add_test(function test_basic_http() { do_check_eq(server.requestCount, 0); let req = localRequest(server, "/2.0/storage/crypto/keys"); _("req is " + req); - req.get(function(err) { + req.get(function (err) { do_check_eq(null, err); do_check_eq(server.requestCount, 1); server.stop(run_next_test); @@ -593,11 +593,11 @@ add_test(function test_x_num_records() { }); server.startSynchronous(); let bso = localRequest(server, "/2.0/123/storage/crypto/foos"); - bso.get(function(err) { + bso.get(function (err) { // BSO fetches don't have one. do_check_false("x-num-records" in this.response.headers); let col = localRequest(server, "/2.0/123/storage/crypto"); - col.get(function(err) { + col.get(function (err) { // Collection fetches do. do_check_eq(this.response.headers["x-num-records"], "2"); server.stop(run_next_test); diff --git a/services/common/tests/unit/test_tokenauthenticatedrequest.js b/services/common/tests/unit/test_tokenauthenticatedrequest.js index d6a8da785deb..0a2db0425b95 100644 --- a/services/common/tests/unit/test_tokenauthenticatedrequest.js +++ b/services/common/tests/unit/test_tokenauthenticatedrequest.js @@ -24,7 +24,7 @@ add_test(function test_authenticated_request() { let nonce = btoa(CryptoUtils.generateRandomBytes(16)); let ts = Math.floor(Date.now() / 1000); - let extra = {ts, nonce}; + let extra = {ts: ts, nonce: nonce}; let auth; @@ -40,7 +40,7 @@ add_test(function test_authenticated_request() { let sig = CryptoUtils.computeHTTPMACSHA1(id, key, method, uri, extra); auth = sig.getHeader(); - let req = new TokenAuthenticatedRESTRequest(uri, {id, key}, extra); + let req = new TokenAuthenticatedRESTRequest(uri, {id: id, key: key}, extra); let cb = Async.makeSpinningCallback(); req.get(cb); let result = cb.wait(); diff --git a/services/common/tests/unit/test_tokenserverclient.js b/services/common/tests/unit/test_tokenserverclient.js index 9ac7481e2dc8..a3650f0478ca 100644 --- a/services/common/tests/unit/test_tokenserverclient.js +++ b/services/common/tests/unit/test_tokenserverclient.js @@ -30,7 +30,7 @@ add_test(function test_working_bid_exchange() { key: "key", api_endpoint: service, uid: "uid", - duration, + duration: duration, }); response.bodyOutputStream.write(body, body.length); } @@ -87,7 +87,7 @@ add_test(function test_conditions_required_response_handling() { response.setHeader("Content-Type", "application/json"); let body = JSON.stringify({ - errors: [{description, location: "body", name: ""}], + errors: [{description: description, location: "body", name: ""}], urls: {tos: tosURL} }); response.bodyOutputStream.write(body, body.length); @@ -221,7 +221,7 @@ add_test(function test_send_extra_headers() { key: "key", api_endpoint: "http://example.com/", uid: "uid", - duration, + duration: duration, }); response.bodyOutputStream.write(body, body.length); } @@ -408,7 +408,7 @@ add_test(function test_rich_media_types() { key: "key", api_endpoint: "foo", uid: "uid", - duration, + duration: duration, }); response.bodyOutputStream.write(body, body.length); } @@ -437,7 +437,7 @@ add_test(function test_exception_during_callback() { key: "key", api_endpoint: "foo", uid: "uid", - duration, + duration: duration, }); response.bodyOutputStream.write(body, body.length); } diff --git a/services/common/tests/unit/test_utils_convert_string.js b/services/common/tests/unit/test_utils_convert_string.js index d416e0bbae0f..265b6734f0e4 100644 --- a/services/common/tests/unit/test_utils_convert_string.js +++ b/services/common/tests/unit/test_utils_convert_string.js @@ -8,21 +8,21 @@ Cu.import("resource://services-common/utils.js"); // A wise line of Greek verse, and the utf-8 byte encoding. // N.b., Greek begins at utf-8 ce 91 const TEST_STR = "πόλλ' οἶδ' ἀλώπηξ, ἀλλ' ἐχῖνος ἓν μέγα"; -const TEST_HEX = h("cf 80 cf 8c ce bb ce bb 27 20 ce bf e1 bc b6 ce" + - "b4 27 20 e1 bc 80 ce bb cf 8e cf 80 ce b7 ce be" + - "2c 20 e1 bc 80 ce bb ce bb 27 20 e1 bc 90 cf 87" + - "e1 bf 96 ce bd ce bf cf 82 20 e1 bc 93 ce bd 20" + +const TEST_HEX = h("cf 80 cf 8c ce bb ce bb 27 20 ce bf e1 bc b6 ce"+ + "b4 27 20 e1 bc 80 ce bb cf 8e cf 80 ce b7 ce be"+ + "2c 20 e1 bc 80 ce bb ce bb 27 20 e1 bc 90 cf 87"+ + "e1 bf 96 ce bd ce bf cf 82 20 e1 bc 93 ce bd 20"+ "ce bc ce ad ce b3 ce b1"); // Integer byte values for the above -const TEST_BYTES = [207, 128, 207, 140, 206, 187, 206, 187, - 39, 32, 206, 191, 225, 188, 182, 206, - 180, 39, 32, 225, 188, 128, 206, 187, - 207, 142, 207, 128, 206, 183, 206, 190, - 44, 32, 225, 188, 128, 206, 187, 206, - 187, 39, 32, 225, 188, 144, 207, 135, - 225, 191, 150, 206, 189, 206, 191, 207, - 130, 32, 225, 188, 147, 206, 189, 32, - 206, 188, 206, 173, 206, 179, 206, 177]; +const TEST_BYTES = [207,128,207,140,206,187,206,187, + 39, 32,206,191,225,188,182,206, + 180, 39, 32,225,188,128,206,187, + 207,142,207,128,206,183,206,190, + 44, 32,225,188,128,206,187,206, + 187, 39, 32,225,188,144,207,135, + 225,191,150,206,189,206,191,207, + 130, 32,225,188,147,206,189, 32, + 206,188,206,173,206,179,206,177]; function run_test() { run_next_test(); diff --git a/services/common/tests/unit/test_utils_encodeBase64URL.js b/services/common/tests/unit/test_utils_encodeBase64URL.js index b1251e12ff11..5d55a6579fd9 100644 --- a/services/common/tests/unit/test_utils_encodeBase64URL.js +++ b/services/common/tests/unit/test_utils_encodeBase64URL.js @@ -13,7 +13,7 @@ add_test(function test_simple() { "<>?": "PD4_", }; - for (let [k, v] of Object.entries(expected)) { + for (let [k,v] of Object.entries(expected)) { do_check_eq(CommonUtils.encodeBase64URL(k), v); } diff --git a/services/common/tests/unit/test_utils_json.js b/services/common/tests/unit/test_utils_json.js index 89ab7444b355..429ac6492cd4 100644 --- a/services/common/tests/unit/test_utils_json.js +++ b/services/common/tests/unit/test_utils_json.js @@ -27,7 +27,7 @@ add_test(function test_writeJSON_readJSON() { do_check_eq(contents.d, json.d); do_check_eq(contents.e, json.e); run_next_test(); - } + }; function doRead() { CommonUtils.readJSON(path) diff --git a/services/common/tests/unit/test_utils_namedTimer.js b/services/common/tests/unit/test_utils_namedTimer.js index f296e6a0c19e..61a65e26037e 100644 --- a/services/common/tests/unit/test_utils_namedTimer.js +++ b/services/common/tests/unit/test_utils_namedTimer.js @@ -13,7 +13,7 @@ add_test(function test_required_args() { do_throw("Shouldn't fire."); }, 0); do_throw("Should have thrown!"); - } catch (ex) { + } catch(ex) { run_next_test(); } }); diff --git a/services/common/tokenserverclient.js b/services/common/tokenserverclient.js index a883f67f907d..b220ab586c13 100644 --- a/services/common/tokenserverclient.js +++ b/services/common/tokenserverclient.js @@ -99,7 +99,7 @@ TokenServerClientNetworkError.prototype._toStringFields = function() { * (string) Error message. */ this.TokenServerClientServerError = - function TokenServerClientServerError(message, cause = "general") { + function TokenServerClientServerError(message, cause="general") { this.now = new Date().toISOString(); // may be useful to diagnose time-skew issues. this.name = "TokenServerClientServerError"; this.message = message || "Server error."; @@ -244,7 +244,7 @@ TokenServerClient.prototype = { * (bool) Whether to send acceptance to service conditions. */ getTokenFromBrowserIDAssertion: - function getTokenFromBrowserIDAssertion(url, assertion, cb, addHeaders = {}) { + function getTokenFromBrowserIDAssertion(url, assertion, cb, addHeaders={}) { if (!url) { throw new TokenServerClientError("url argument is not valid."); } @@ -436,7 +436,7 @@ TokenServerClient.prototype = { observerPrefix: null, // Given an optional header value, notify that a backoff has been requested. - _maybeNotifyBackoff(response, headerName) { + _maybeNotifyBackoff: function (response, headerName) { if (!this.observerPrefix) { return; } @@ -456,7 +456,7 @@ TokenServerClient.prototype = { }, // override points for testing. - newRESTRequest(url) { + newRESTRequest: function(url) { return new RESTRequest(url); } }; diff --git a/services/common/utils.js b/services/common/utils.js index d1ab244d331a..a51e45ec9c08 100644 --- a/services/common/utils.js +++ b/services/common/utils.js @@ -21,7 +21,7 @@ this.CommonUtils = { /** * Return elements of `a` or `b`. */ - union(a, b) { + union: function (a, b) { let out = new Set(a); for (let x of b) { out.add(x); @@ -32,7 +32,7 @@ this.CommonUtils = { /** * Return elements of `a` that are not present in `b`. */ - difference(a, b) { + difference: function (a, b) { let out = new Set(a); for (let x of b) { out.delete(x); @@ -43,7 +43,7 @@ this.CommonUtils = { /** * Return elements of `a` that are also in `b`. */ - intersection(a, b) { + intersection: function (a, b) { let out = new Set(); for (let x of a) { if (b.has(x)) { @@ -57,7 +57,7 @@ this.CommonUtils = { * Return true if `a` and `b` are the same size, and * every element of `a` is in `b`. */ - setEqual(a, b) { + setEqual: function (a, b) { if (a.size != b.size) { return false; } @@ -78,7 +78,7 @@ this.CommonUtils = { * (bool) Whether to include padding characters (=). Defaults * to true for historical reasons. */ - encodeBase64URL: function encodeBase64URL(bytes, pad = true) { + encodeBase64URL: function encodeBase64URL(bytes, pad=true) { let s = btoa(bytes).replace(/\+/g, "-").replace(/\//g, "_"); if (!pad) { @@ -125,7 +125,7 @@ this.CommonUtils = { * accumulation and prevents callers from accidentally relying on * same-tick promise resolution. */ - laterTickResolvingPromise(value, prototype) { + laterTickResolvingPromise: function (value, prototype) { let deferred = Promise.defer(prototype); this.nextTick(deferred.resolve.bind(deferred, value)); return deferred.promise; @@ -142,7 +142,7 @@ this.CommonUtils = { this.nextTick(cb); Async.waitForSyncCallback(cb); - + return; }, /** @@ -380,7 +380,7 @@ this.CommonUtils = { * @param path the file to read. Will be passed to `OS.File.read()`. * @return a promise that resolves to the JSON contents of the named file. */ - readJSON(path) { + readJSON: function(path) { return OS.File.read(path, { encoding: "utf-8" }).then((data) => { return JSON.parse(data); }); @@ -393,7 +393,7 @@ this.CommonUtils = { * @param path the path of the file to write. * @return a promise, as produced by OS.File.writeAtomic. */ - writeJSON(contents, path) { + writeJSON: function(contents, path) { let data = JSON.stringify(contents); return OS.File.writeAtomic(path, data, {encoding: "utf-8", tmpPath: path + ".tmp"}); }, @@ -492,7 +492,7 @@ this.CommonUtils = { * @param log * (Log.Logger) Logger to write warnings to. */ - getEpochPref: function getEpochPref(branch, pref, def = 0, log = null) { + getEpochPref: function getEpochPref(branch, pref, def=0, log=null) { if (!Number.isInteger(def)) { throw new Error("Default value is not a number: " + def); } @@ -537,8 +537,8 @@ this.CommonUtils = { * @param oldestYear * (Number) Oldest year to accept in read values. */ - getDatePref: function getDatePref(branch, pref, def = 0, log = null, - oldestYear = 2010) { + getDatePref: function getDatePref(branch, pref, def=0, log=null, + oldestYear=2010) { let valueInt = this.getEpochPref(branch, pref, def, log); let date = new Date(valueInt); @@ -572,7 +572,7 @@ this.CommonUtils = { * @param oldestYear * (Number) The oldest year to accept for values. */ - setDatePref: function setDatePref(branch, pref, date, oldestYear = 2010) { + setDatePref: function setDatePref(branch, pref, date, oldestYear=2010) { if (date.getFullYear() < oldestYear) { throw new Error("Trying to set " + pref + " to a very old time: " + date + ". The current time is " + new Date() + diff --git a/services/crypto/component/tests/unit/test_jpake.js b/services/crypto/component/tests/unit/test_jpake.js index 794dd627abfa..4e9b25e1b248 100644 --- a/services/crypto/component/tests/unit/test_jpake.js +++ b/services/crypto/component/tests/unit/test_jpake.js @@ -8,7 +8,7 @@ function do_check_throws(func) { let have_error = false; try { func(); - } catch (ex) { + } catch(ex) { dump("Was expecting an exception. Caught: " + ex + "\n"); have_error = true; } @@ -199,7 +199,7 @@ function test_x4_zero() { a_gx2.value, a_gv2.value, a_r2.value, b_A, b_gva, b_ra); }); }; - + // g^x is NIST 3072's p + 1, (p + 1) mod p == 1, x == 0 test("90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD61037E56258A7795A1C" + "7AD46076982CE6BB956936C6AB4DCFE05E6784586940CA544B9B2140E1EB523F" @@ -246,7 +246,7 @@ function test_x4_zero() { } function test_invalid_input_round2() { - let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"] + let a = Cc["@mozilla.org/services-crypto/sync-jpake;1"] .createInstance(Ci.nsISyncJPAKE); a.round1("alice", {}, {}, {}, {}, {}, {}); diff --git a/services/crypto/modules/WeaveCrypto.js b/services/crypto/modules/WeaveCrypto.js index ef15c088a5dc..c040c4f6fcf9 100644 --- a/services/crypto/modules/WeaveCrypto.js +++ b/services/crypto/modules/WeaveCrypto.js @@ -120,7 +120,7 @@ WeaveCrypto.prototype = { ? crypto.subtle.encrypt : crypto.subtle.decrypt) .bind(crypto.subtle); - let algo = { name: CRYPT_ALGO, iv }; + let algo = { name: CRYPT_ALGO, iv: iv }; return Async.promiseSpinningly( @@ -245,7 +245,7 @@ WeaveCrypto.prototype = { let importAlgo = { name: KEY_DERIVATION_ALGO }; let deriveAlgo = { name: KEY_DERIVATION_ALGO, - salt, + salt: salt, iterations: KEY_DERIVATION_ITERATIONS, hash: { name: KEY_DERIVATION_HASHING_ALGO }, }; diff --git a/services/crypto/modules/utils.js b/services/crypto/modules/utils.js index f8e08c9152a0..c17f5dfa185a 100644 --- a/services/crypto/modules/utils.js +++ b/services/crypto/modules/utils.js @@ -15,7 +15,7 @@ this.CryptoUtils = { let bytes = []; if (a.length != b.length) { - throw new Error("can't xor unequal length strings: " + a.length + " vs " + b.length); + throw new Error("can't xor unequal length strings: "+a.length+" vs "+b.length); } for (let i = 0; i < a.length; i++) { @@ -71,7 +71,7 @@ this.CryptoUtils = { * with a single hasher, but eventually you must extract the result * yourself. */ - updateUTF8(message, hasher) { + updateUTF8: function(message, hasher) { let bytes = this._utf8Converter.convertToByteArray(message, {}); hasher.update(bytes, bytes.length); }, @@ -136,10 +136,10 @@ this.CryptoUtils = { hkdf: function hkdf(ikm, xts, info, len) { const BLOCKSIZE = 256 / 8; if (typeof xts === undefined) - xts = String.fromCharCode(0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0); + xts = String.fromCharCode(0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0); let h = CryptoUtils.makeHMACHasher(Ci.nsICryptoHMAC.SHA256, CryptoUtils.makeHMACKey(xts)); let prk = CryptoUtils.digestBytes(ikm, h); @@ -155,7 +155,7 @@ this.CryptoUtils = { CryptoUtils.makeHMACKey(prk)); let T = ""; let Tn = ""; - let iterations = Math.ceil(len / BLOCKSIZE); + let iterations = Math.ceil(len/BLOCKSIZE); for (let i = 0; i < iterations; i++) { Tn = CryptoUtils.digestBytes(Tn + info + String.fromCharCode(i + 1), h); T += Tn; @@ -184,7 +184,7 @@ this.CryptoUtils = { * can encode as you wish. */ pbkdf2Generate : function pbkdf2Generate(P, S, c, dkLen, - hmacAlg = Ci.nsICryptoHMAC.SHA1, hmacLen = 20) { + hmacAlg=Ci.nsICryptoHMAC.SHA1, hmacLen=20) { // We don't have a default in the algo itself, as NSS does. // Use the constant. @@ -247,7 +247,7 @@ this.CryptoUtils = { } let ret = ""; - for (let i = 0; i < l - 1;) { + for (let i = 0; i < l-1;) { ret += T[i++]; } ret += T[l - 1].substr(0, r); @@ -261,7 +261,8 @@ this.CryptoUtils = { forceJS) { if (Svc.Crypto.deriveKeyFromPassphrase && !forceJS) { return Svc.Crypto.deriveKeyFromPassphrase(passphrase, salt, keyLength); - } else { + } + else { // Fall back to JS implementation. // 4096 is hardcoded in WeaveCrypto, so do so here. return CryptoUtils.pbkdf2Generate(passphrase, atob(salt), 4096, @@ -333,12 +334,12 @@ this.CryptoUtils = { let ext = (extra && extra.ext) ? extra.ext : ""; let requestString = ts.toString(10) + "\n" + - nonce + "\n" + - usedMethod + "\n" + - uri.path + "\n" + - host + "\n" + - port + "\n" + - ext + "\n"; + nonce + "\n" + + usedMethod + "\n" + + uri.path + "\n" + + host + "\n" + + port + "\n" + + ext + "\n"; let hasher = CryptoUtils.makeHMACHasher(Ci.nsICryptoHMAC.SHA1, CryptoUtils.makeHMACKey(key)); @@ -350,16 +351,16 @@ this.CryptoUtils = { } return { - identifier, - key, + identifier: identifier, + key: key, method: usedMethod, hostname: host, - port, - mac, - nonce, - ts, - ext, - getHeader + port: port, + mac: mac, + nonce: nonce, + ts: ts, + ext: ext, + getHeader: getHeader }; }, @@ -382,23 +383,23 @@ this.CryptoUtils = { */ getHTTPMACSHA1Header: function getHTTPMACSHA1Header(identifier, ts, nonce, mac, ext) { - let header = 'MAC id="' + identifier + '", ' + - 'ts="' + ts + '", ' + - 'nonce="' + nonce + '", ' + - 'mac="' + btoa(mac) + '"'; + let header ='MAC id="' + identifier + '", ' + + 'ts="' + ts + '", ' + + 'nonce="' + nonce + '", ' + + 'mac="' + btoa(mac) + '"'; if (!ext) { return header; } - return header += ', ext="' + ext + '"'; + return header += ', ext="' + ext +'"'; }, /** * Given an HTTP header value, strip out any attributes. */ - stripHeaderAttributes(value) { + stripHeaderAttributes: function(value) { value = value || ""; let i = value.indexOf(";"); return value.substring(0, (i >= 0) ? i : undefined).trim().toLowerCase(); @@ -457,7 +458,7 @@ this.CryptoUtils = { * ext - (string) app-specific data * MAC - (string) request MAC (base64) */ - computeHAWK(uri, method, options) { + computeHAWK: function(uri, method, options) { let credentials = options.credentials; let ts = options.ts || Math.floor(((options.now || Date.now()) + (options.localtimeOffsetMsec || 0)) @@ -486,7 +487,7 @@ this.CryptoUtils = { } let artifacts = { - ts, + ts: ts, nonce: options.nonce || btoa(CryptoUtils.generateRandomBytes(8)), method: method.toUpperCase(), resource: uri.path, // This includes both path and search/queryarg. @@ -504,7 +505,7 @@ this.CryptoUtils = { .createInstance(Ci.nsICryptoHash); hasher.init(hash_algo); CryptoUtils.updateUTF8("hawk.1.payload\n", hasher); - CryptoUtils.updateUTF8(contentType + "\n", hasher); + CryptoUtils.updateUTF8(contentType+"\n", hasher); CryptoUtils.updateUTF8(options.payload, hasher); CryptoUtils.updateUTF8("\n", hasher); let hash = hasher.finish(false); @@ -514,13 +515,13 @@ this.CryptoUtils = { artifacts.hash = hash_b64; } - let requestString = ("hawk.1.header" + "\n" + + let requestString = ("hawk.1.header" + "\n" + artifacts.ts.toString(10) + "\n" + - artifacts.nonce + "\n" + - artifacts.method + "\n" + - artifacts.resource + "\n" + - artifacts.host + "\n" + - artifacts.port + "\n" + + artifacts.nonce + "\n" + + artifacts.method + "\n" + + artifacts.resource + "\n" + + artifacts.host + "\n" + + artifacts.port + "\n" + (artifacts.hash || "") + "\n"); if (artifacts.ext) { requestString += artifacts.ext.replace("\\", "\\\\").replace("\n", "\\n"); @@ -543,7 +544,7 @@ this.CryptoUtils = { (artifacts.ext ? ('ext="' + escape(artifacts.ext) + '", ') : "") + 'mac="' + artifacts.mac + '"'); return { - artifacts, + artifacts: artifacts, field: header, }; }, diff --git a/services/crypto/tests/unit/head_helpers.js b/services/crypto/tests/unit/head_helpers.js index 8ec6854908ad..cbe005a7f511 100644 --- a/services/crypto/tests/unit/head_helpers.js +++ b/services/crypto/tests/unit/head_helpers.js @@ -8,7 +8,8 @@ Cu.import("resource://gre/modules/XPCOMUtils.jsm"); try { // In the context of xpcshell tests, there won't be a default AppInfo Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo); -} catch (ex) { +} +catch(ex) { // Make sure to provide the right OS so crypto loads the right binaries var OS = "XPCShell"; @@ -25,7 +26,7 @@ updateAppInfo({ ID: "{3e3ba16c-1675-4e88-b9c8-afef81b3d2ef}", version: "1", platformVersion: "", - OS, + OS: OS, }); } diff --git a/services/crypto/tests/unit/test_utils_hawk.js b/services/crypto/tests/unit/test_utils_hawk.js index 2af5dfdab689..0a2cf6c31716 100644 --- a/services/crypto/tests/unit/test_utils_hawk.js +++ b/services/crypto/tests/unit/test_utils_hawk.js @@ -29,8 +29,8 @@ add_test(function test_hawk() { let uri_http = CommonUtils.makeURI("http://example.net/somewhere/over/the/rainbow"); let sha1_opts = { credentials: credentials_sha1, ext: "Bazinga!", - ts, - nonce, + ts: ts, + nonce: nonce, payload: "something to write about", }; result = compute(uri_http, method, sha1_opts); @@ -60,8 +60,8 @@ add_test(function test_hawk() { let uri_https = CommonUtils.makeURI("https://example.net/somewhere/over/the/rainbow"); let sha256_opts = { credentials: credentials_sha256, ext: "Bazinga!", - ts, - nonce, + ts: ts, + nonce: nonce, payload: "something to write about", contentType: "text/plain", }; @@ -83,8 +83,8 @@ add_test(function test_hawk() { do_check_eq(result.artifacts.ext, "Bazinga!"); let sha256_opts_noext = { credentials: credentials_sha256, - ts, - nonce, + ts: ts, + nonce: nonce, payload: "something to write about", contentType: "text/plain", }; @@ -116,8 +116,8 @@ add_test(function test_hawk() { /* The HAWK spec calls for seconds-since-epoch, not ms-since-epoch. * Warning: this test will fail in the year 33658, and for time travellers * who journey earlier than 2001. Please plan accordingly. */ - do_check_true(result.artifacts.ts > 1000 * 1000 * 1000); - do_check_true(result.artifacts.ts < 1000 * 1000 * 1000 * 1000); + do_check_true(result.artifacts.ts > 1000*1000*1000); + do_check_true(result.artifacts.ts < 1000*1000*1000*1000); do_check_true(fields[3].startsWith('nonce="')); do_check_eq(fields[3].length, ('nonce="12345678901=",').length); do_check_eq(result.artifacts.nonce.length, ("12345678901=").length); @@ -159,7 +159,7 @@ add_test(function test_hawk() { result = compute(uri_https, method, { credentials: credentials_sha256, now: 1378848968650, - localtimeOffsetMsec: 1000 * 1000, + localtimeOffsetMsec: 1000*1000, }); do_check_eq(result.artifacts.ts, 1378848968 + 1000); diff --git a/services/crypto/tests/unit/test_utils_httpmac.js b/services/crypto/tests/unit/test_utils_httpmac.js index 01deab4cd623..67b337373e3a 100644 --- a/services/crypto/tests/unit/test_utils_httpmac.js +++ b/services/crypto/tests/unit/test_utils_httpmac.js @@ -22,7 +22,7 @@ add_test(function test_sha1() { let uri = CommonUtils.makeURI("http://10.250.2.176/alias/"); let result = CryptoUtils.computeHTTPMACSHA1(id, key, method, uri, - {ts, nonce}); + {ts: ts, nonce: nonce}); do_check_eq(btoa(result.mac), "jzh5chjQc2zFEvLbyHnPdX11Yck="); @@ -33,7 +33,7 @@ add_test(function test_sha1() { let ext = "EXTRA DATA; foo,bar=1"; result = CryptoUtils.computeHTTPMACSHA1(id, key, method, uri, - {ts, nonce, ext}); + {ts: ts, nonce: nonce, ext: ext}); do_check_eq(btoa(result.mac), "bNf4Fnt5k6DnhmyipLPkuZroH68="); do_check_eq(result.getHeader(), 'MAC id="vmo1txkttblmn51u2p3zk2xiy16hgvm5ok8qiv1yyi86ffjzy9zj0ez9x6wnvbx7", ' + diff --git a/services/crypto/tests/unit/test_utils_pbkdf2.js b/services/crypto/tests/unit/test_utils_pbkdf2.js index e010fa562171..7313819ec489 100644 --- a/services/crypto/tests/unit/test_utils_pbkdf2.js +++ b/services/crypto/tests/unit/test_utils_pbkdf2.js @@ -30,8 +30,8 @@ add_task(function test_pbkdf2_hmac_sha1() { S: "salt", // (4 octets) c: 1, dkLen: 20, - DK: h("0c 60 c8 0f 96 1f 0e 71" + - "f3 a9 b5 24 af 60 12 06" + + DK: h("0c 60 c8 0f 96 1f 0e 71"+ + "f3 a9 b5 24 af 60 12 06"+ "2f e0 37 a6"), // (20 octets) }, @@ -39,8 +39,8 @@ add_task(function test_pbkdf2_hmac_sha1() { S: "salt", // (4 octets) c: 2, dkLen: 20, - DK: h("ea 6c 01 4d c7 2d 6f 8c" + - "cd 1e d9 2a ce 1d 41 f0" + + DK: h("ea 6c 01 4d c7 2d 6f 8c"+ + "cd 1e d9 2a ce 1d 41 f0"+ "d8 de 89 57"), // (20 octets) }, @@ -48,8 +48,8 @@ add_task(function test_pbkdf2_hmac_sha1() { S: "salt", // (4 octets) c: 4096, dkLen: 20, - DK: h("4b 00 79 01 b7 65 48 9a" + - "be ad 49 d9 26 f7 21 d0" + + DK: h("4b 00 79 01 b7 65 48 9a"+ + "be ad 49 d9 26 f7 21 d0"+ "65 a4 29 c1"), // (20 octets) }, @@ -72,9 +72,9 @@ add_task(function test_pbkdf2_hmac_sha1() { S: "saltSALTsaltSALTsaltSALTsaltSALTsalt", // (36 octets) c: 4096, dkLen: 25, - DK: h("3d 2e ec 4f e4 1c 84 9b" + - "80 c8 d8 36 62 c0 e4 4a" + - "8b 29 1a 96 4c f2 f0 70" + + DK: h("3d 2e ec 4f e4 1c 84 9b"+ + "80 c8 d8 36 62 c0 e4 4a"+ + "8b 29 1a 96 4c f2 f0 70"+ "38"), // (25 octets) }, @@ -83,7 +83,7 @@ add_task(function test_pbkdf2_hmac_sha1() { S: "sa\0lt", // (5 octets) c: 4096, dkLen: 16, - DK: h("56 fa 6a a7 55 48 09 9d" + + DK: h("56 fa 6a a7 55 48 09 9d"+ "cc 37 d7 f0 34 25 e0 c3"), // (16 octets) }, ]; @@ -104,9 +104,9 @@ add_task(function test_pbkdf2_hmac_sha256() { S: "salt", // (4 octets) c: 1, dkLen: 32, - DK: h("12 0f b6 cf fc f8 b3 2c" + - "43 e7 22 52 56 c4 f8 37" + - "a8 65 48 c9 2c cc 35 48" + + DK: h("12 0f b6 cf fc f8 b3 2c"+ + "43 e7 22 52 56 c4 f8 37"+ + "a8 65 48 c9 2c cc 35 48"+ "08 05 98 7c b7 0b e1 7b"), // (32 octets) }, @@ -114,9 +114,9 @@ add_task(function test_pbkdf2_hmac_sha256() { S: "salt", // (4 octets) c: 2, dkLen: 32, - DK: h("ae 4d 0c 95 af 6b 46 d3" + - "2d 0a df f9 28 f0 6d d0" + - "2a 30 3f 8e f3 c2 51 df" + + DK: h("ae 4d 0c 95 af 6b 46 d3"+ + "2d 0a df f9 28 f0 6d d0"+ + "2a 30 3f 8e f3 c2 51 df"+ "d6 e2 d8 5a 95 47 4c 43"), // (32 octets) }, @@ -124,9 +124,9 @@ add_task(function test_pbkdf2_hmac_sha256() { S: "salt", // (4 octets) c: 4096, dkLen: 32, - DK: h("c5 e4 78 d5 92 88 c8 41" + - "aa 53 0d b6 84 5c 4c 8d" + - "96 28 93 a0 01 ce 4e 11" + + DK: h("c5 e4 78 d5 92 88 c8 41"+ + "aa 53 0d b6 84 5c 4c 8d"+ + "96 28 93 a0 01 ce 4e 11"+ "a4 96 38 73 aa 98 13 4a"), // (32 octets) }, @@ -134,10 +134,10 @@ add_task(function test_pbkdf2_hmac_sha256() { S: "saltSALTsaltSALTsaltSALTsaltSALTsalt", // (36 octets) c: 4096, dkLen: 40, - DK: h("34 8c 89 db cb d3 2b 2f" + - "32 d8 14 b8 11 6e 84 cf" + - "2b 17 34 7e bc 18 00 18" + - "1c 4e 2a 1f b8 dd 53 e1" + + DK: h("34 8c 89 db cb d3 2b 2f"+ + "32 d8 14 b8 11 6e 84 cf"+ + "2b 17 34 7e bc 18 00 18"+ + "1c 4e 2a 1f b8 dd 53 e1"+ "c6 35 51 8c 7d ac 47 e9"), // (40 octets) }, @@ -145,7 +145,7 @@ add_task(function test_pbkdf2_hmac_sha256() { S: "sa\0lt", // (5 octets) c: 4096, dkLen: 16, - DK: h("89 b6 9d 05 16 f8 29 89" + + DK: h("89 b6 9d 05 16 f8 29 89"+ "3c 69 62 26 65 0a 86 87"), // (16 octets) }, ]; diff --git a/services/fxaccounts/Credentials.jsm b/services/fxaccounts/Credentials.jsm index 8c774084d9db..56e8b3db78cd 100644 --- a/services/fxaccounts/Credentials.jsm +++ b/services/fxaccounts/Credentials.jsm @@ -50,13 +50,13 @@ this.Credentials = Object.freeze({ * Make constants accessible to tests */ constants: { - PROTOCOL_VERSION, - PBKDF2_ROUNDS, - STRETCHED_PW_LENGTH_BYTES, - HKDF_SALT, - HKDF_LENGTH, - HMAC_ALGORITHM, - HMAC_LENGTH, + PROTOCOL_VERSION: PROTOCOL_VERSION, + PBKDF2_ROUNDS: PBKDF2_ROUNDS, + STRETCHED_PW_LENGTH_BYTES: STRETCHED_PW_LENGTH_BYTES, + HKDF_SALT: HKDF_SALT, + HKDF_LENGTH: HKDF_LENGTH, + HMAC_ALGORITHM: HMAC_ALGORITHM, + HMAC_LENGTH: HMAC_LENGTH, }, /** @@ -72,7 +72,7 @@ this.Credentials = Object.freeze({ * Note that PROTOCOL_VERSION does not refer in any way to the version of the * Firefox Accounts API. */ - keyWord(context) { + keyWord: function(context) { return CommonUtils.stringToBytes(PROTOCOL_VERSION + context); }, @@ -89,11 +89,11 @@ this.Credentials = Object.freeze({ * Note that PROTOCOL_VERSION does not refer in any way to the version of the * Firefox Accounts API. */ - keyWordExtended(name, email) { + keyWordExtended: function(name, email) { return CommonUtils.stringToBytes(PROTOCOL_VERSION + name + ':' + email); }, - setup(emailInput, passwordInput, options = {}) { + setup: function(emailInput, passwordInput, options={}) { let deferred = Promise.defer(); log.debug("setup credentials for " + emailInput); diff --git a/services/fxaccounts/FxAccounts.jsm b/services/fxaccounts/FxAccounts.jsm index 541b0273ed1b..0ecff61f5d8e 100644 --- a/services/fxaccounts/FxAccounts.jsm +++ b/services/fxaccounts/FxAccounts.jsm @@ -166,7 +166,7 @@ AccountState.prototype = { return this.storageManager.updateAccountData(updatedFields); }, - resolve(result) { + resolve: function(result) { if (!this.isCurrent) { log.info("An accountState promise was resolved, but was actually rejected" + " due to a different user being signed in. Originally resolved" + @@ -176,7 +176,7 @@ AccountState.prototype = { return Promise.resolve(result); }, - reject(error) { + reject: function(error) { // It could be argued that we should just let it reject with the original // error - but this runs the risk of the error being (eg) a 401, which // might cause the consumer to attempt some remediation and cause other @@ -312,7 +312,7 @@ function urlsafeBase64Encode(key) { /** * The public API's constructor. */ -this.FxAccounts = function(mockInternal) { +this.FxAccounts = function (mockInternal) { let internal = new FxAccountsInternal(); let external = {}; @@ -334,7 +334,7 @@ this.FxAccounts = function(mockInternal) { if (!internal.fxaPushService) { // internal.fxaPushService option is used in testing. // Otherwise we load the service lazily. - XPCOMUtils.defineLazyGetter(internal, "fxaPushService", function() { + XPCOMUtils.defineLazyGetter(internal, "fxaPushService", function () { return Components.classes["@mozilla.org/fxaccounts/push;1"] .getService(Components.interfaces.nsISupports) .wrappedJSObject; @@ -393,7 +393,7 @@ FxAccountsInternal.prototype = { let profileServerUrl = Services.urlFormatter.formatURLPref("identity.fxaccounts.remote.profile.uri"); this._profile = new FxAccountsProfile({ fxa: this, - profileServerUrl, + profileServerUrl: profileServerUrl, }); } return this._profile; @@ -411,7 +411,7 @@ FxAccountsInternal.prototype = { * * @return Promise */ - notifyDevices(deviceIds, payload, TTL) { + notifyDevices: function(deviceIds, payload, TTL) { if (!Array.isArray(deviceIds)) { deviceIds = [deviceIds]; } @@ -433,11 +433,11 @@ FxAccountsInternal.prototype = { * Return the current time in milliseconds as an integer. Allows tests to * manipulate the date to simulate certificate expiration. */ - now() { + now: function() { return this.fxAccountsClient.now(); }, - getAccountsClient() { + getAccountsClient: function() { return this.fxAccountsClient; }, @@ -714,7 +714,7 @@ FxAccountsInternal.prototype = { }); }, - checkVerificationStatus() { + checkVerificationStatus: function() { log.trace('checkVerificationStatus'); let currentState = this.currentAccountState; return currentState.getUserAccountData().then(data => { @@ -731,7 +731,7 @@ FxAccountsInternal.prototype = { }); }, - _destroyOAuthToken(tokenData) { + _destroyOAuthToken: function(tokenData) { let client = new FxAccountsOAuthGrantClient({ serverURL: tokenData.server, client_id: FX_OAUTH_CLIENT_ID @@ -739,7 +739,7 @@ FxAccountsInternal.prototype = { return client.destroyToken(tokenData.token) }, - _destroyAllOAuthTokens(tokenInfos) { + _destroyAllOAuthTokens: function(tokenInfos) { // let's just destroy them all in parallel... let promises = []; for (let [key, tokenInfo] of Object.entries(tokenInfos || {})) { @@ -864,7 +864,7 @@ FxAccountsInternal.prototype = { * } * or null if no user is signed in */ - getKeys() { + getKeys: function() { let currentState = this.currentAccountState; return currentState.getUserAccountData().then((userData) => { if (!userData) { @@ -900,7 +900,7 @@ FxAccountsInternal.prototype = { ).then(result => currentState.resolve(result)); }, - fetchAndUnwrapKeys(keyFetchToken) { + fetchAndUnwrapKeys: function(keyFetchToken) { if (logPII) { log.debug("fetchAndUnwrapKeys: token: " + keyFetchToken); } @@ -951,7 +951,7 @@ FxAccountsInternal.prototype = { }.bind(this)).then(result => currentState.resolve(result)); }, - getAssertionFromCert(data, keyPair, cert, audience) { + getAssertionFromCert: function(data, keyPair, cert, audience) { log.debug("getAssertionFromCert"); let payload = {}; let d = Promise.defer(); @@ -978,7 +978,7 @@ FxAccountsInternal.prototype = { return d.promise.then(result => currentState.resolve(result)); }, - getCertificateSigned(sessionToken, serializedPublicKey, lifetime) { + getCertificateSigned: function(sessionToken, serializedPublicKey, lifetime) { log.debug("getCertificateSigned: " + !!sessionToken + " " + !!serializedPublicKey); if (logPII) { log.debug("getCertificateSigned: " + sessionToken + " " + serializedPublicKey); @@ -1003,7 +1003,7 @@ FxAccountsInternal.prototype = { let ignoreCachedAuthCredentials = false; try { ignoreCachedAuthCredentials = Services.prefs.getBoolPref("services.sync.debug.ignoreCachedAuthCredentials"); - } catch (e) { + } catch(e) { // Pref doesn't exist } let mustBeValidUntil = this.now() + ASSERTION_USE_PERIOD; @@ -1074,11 +1074,11 @@ FxAccountsInternal.prototype = { } return { keyPair: keyPair.rawKeyPair, - certificate, + certificate: certificate, } }), - getUserAccountData() { + getUserAccountData: function() { return this.currentAccountState.getUserAccountData(); }, @@ -1089,7 +1089,7 @@ FxAccountsInternal.prototype = { /** * Setup for and if necessary do email verification polling. */ - loadAndPoll() { + loadAndPoll: function() { let currentState = this.currentAccountState; return currentState.getUserAccountData() .then(data => { @@ -1103,7 +1103,7 @@ FxAccountsInternal.prototype = { }); }, - startVerifiedCheck(data) { + startVerifiedCheck: function(data) { log.debug("startVerifiedCheck", data && data.verified); if (logPII) { log.debug("startVerifiedCheck with user data", data); @@ -1125,7 +1125,7 @@ FxAccountsInternal.prototype = { ); }, - whenVerified(data) { + whenVerified: function(data) { let currentState = this.currentAccountState; if (data.verified) { log.debug("already verified"); @@ -1140,7 +1140,7 @@ FxAccountsInternal.prototype = { ); }, - notifyObservers(topic, data) { + notifyObservers: function(topic, data) { log.debug("Notifying observers of " + topic); Services.obs.notifyObservers(null, topic, data); }, @@ -1217,7 +1217,7 @@ FxAccountsInternal.prototype = { }, // Poll email status using truncated exponential back-off. - pollEmailStatusAgain(currentState, sessionToken, timeoutMs) { + pollEmailStatusAgain: function (currentState, sessionToken, timeoutMs) { let ageMs = Date.now() - this.pollStartDate; if (ageMs >= this.POLL_SESSION) { if (currentState.whenVerifiedDeferred) { @@ -1238,11 +1238,11 @@ FxAccountsInternal.prototype = { }, timeoutMs); }, - requiresHttps() { + requiresHttps: function() { let allowHttp = false; try { allowHttp = Services.prefs.getBoolPref("identity.fxaccounts.allowHttp"); - } catch (e) { + } catch(e) { // Pref doesn't exist } return allowHttp !== true; @@ -1280,7 +1280,7 @@ FxAccountsInternal.prototype = { // the current account's profile image. // if settingToEdit is set, the profile page should hightlight that setting // for the user to edit. - promiseAccountsChangeProfileURI(entrypoint, settingToEdit = null) { + promiseAccountsChangeProfileURI: function(entrypoint, settingToEdit = null) { let url = Services.urlFormatter.formatURLPref("identity.fxaccounts.settings.uri"); if (settingToEdit) { @@ -1309,7 +1309,7 @@ FxAccountsInternal.prototype = { // Returns a promise that resolves with the URL to use to manage the current // user's FxA acct. - promiseAccountsManageURI(entrypoint) { + promiseAccountsManageURI: function(entrypoint) { let url = Services.urlFormatter.formatURLPref("identity.fxaccounts.settings.uri"); if (this.requiresHttps() && !/^https:/.test(url)) { // Comment to un-break emacs js-mode highlighting throw new Error("Firefox Accounts server must use HTTPS"); @@ -1397,7 +1397,7 @@ FxAccountsInternal.prototype = { let token = result.access_token; // If we got one, cache it. if (token) { - let entry = {token, server: oAuthURL}; + let entry = {token: token, server: oAuthURL}; // But before we do, check the cache again - if we find one now, it // means someone else concurrently requested the same scope and beat // us to the cache write. To be nice to the server, we revoke the one @@ -1465,7 +1465,7 @@ FxAccountsInternal.prototype = { * NO_ACCOUNT * UNVERIFIED_ACCOUNT */ - _errorToErrorClass(aError) { + _errorToErrorClass: function (aError) { if (aError.errno) { let error = SERVER_ERRNO_TO_ERROR[aError.errno]; return this._error(ERROR_TO_GENERAL_ERROR_CLASS[error] || ERROR_UNKNOWN, aError); @@ -1479,7 +1479,7 @@ FxAccountsInternal.prototype = { return this._error(ERROR_UNKNOWN, aError); }, - _error(aError, aDetails) { + _error: function(aError, aDetails) { log.error("FxA rejecting with error ${aError}, details: ${aDetails}", {aError, aDetails}); let reason = new Error(aError); if (aDetails) { @@ -1510,7 +1510,7 @@ FxAccountsInternal.prototype = { * AUTH_ERROR * UNKNOWN_ERROR */ - getSignedInUserProfile() { + getSignedInUserProfile: function () { let currentState = this.currentAccountState; return this.profile.getProfile().then( profileData => { @@ -1589,7 +1589,7 @@ FxAccountsInternal.prototype = { if (Services.prefs.getBoolPref("identity.fxaccounts.skipDeviceRegistration")) { return Promise.resolve(); } - } catch (ignore) {} + } catch(ignore) {} if (!signedInUser.sessionToken) { return Promise.reject(new Error( diff --git a/services/fxaccounts/FxAccountsClient.jsm b/services/fxaccounts/FxAccountsClient.jsm index 0af6b5c885bb..fbe8da2fe429 100644 --- a/services/fxaccounts/FxAccountsClient.jsm +++ b/services/fxaccounts/FxAccountsClient.jsm @@ -55,7 +55,7 @@ this.FxAccountsClient.prototype = { * Not used by this module, but made available to the FxAccounts.jsm * that uses this client. */ - now() { + now: function() { return this.hawk.now(); }, @@ -87,12 +87,12 @@ this.FxAccountsClient.prototype = { * email * } */ - _createSession(path, email, password, getKeys = false, - retryOK = true) { + _createSession: function(path, email, password, getKeys=false, + retryOK=true) { return Credentials.setup(email, password).then((creds) => { let data = { authPW: CommonUtils.bytesAsHex(creds.authPW), - email, + email: email, }; let keys = getKeys ? "?keys=true" : ""; @@ -151,7 +151,7 @@ this.FxAccountsClient.prototype = { * password (not revealed to the FxA server) * } */ - signUp(email, password, getKeys = false) { + signUp: function(email, password, getKeys=false) { return this._createSession(SIGNUP, email, password, getKeys, false /* no retry */); }, @@ -178,7 +178,7 @@ this.FxAccountsClient.prototype = { * verified: flag indicating verification status of the email * } */ - signIn: function signIn(email, password, getKeys = false) { + signIn: function signIn(email, password, getKeys=false) { return this._createSession(SIGNIN, email, password, getKeys, true /* retry */); }, @@ -191,7 +191,7 @@ this.FxAccountsClient.prototype = { * @return Promise * Resolves with a boolean indicating if the session is still valid */ - sessionStatus(sessionTokenHex) { + sessionStatus: function (sessionTokenHex) { return this._request("/session/status", "GET", deriveHawkCredentials(sessionTokenHex, "sessionToken")).then( () => Promise.resolve(true), @@ -211,7 +211,7 @@ this.FxAccountsClient.prototype = { * The session token encoded in hex * @return Promise */ - signOut(sessionTokenHex, options = {}) { + signOut: function (sessionTokenHex, options = {}) { let path = "/session/destroy"; if (options.service) { path += "?service=" + encodeURIComponent(options.service); @@ -227,7 +227,7 @@ this.FxAccountsClient.prototype = { * The current session token encoded in hex * @return Promise */ - recoveryEmailStatus(sessionTokenHex, options = {}) { + recoveryEmailStatus: function (sessionTokenHex, options = {}) { let path = "/recovery_email/status"; if (options.reason) { path += "?reason=" + encodeURIComponent(options.reason); @@ -244,7 +244,7 @@ this.FxAccountsClient.prototype = { * The current token encoded in hex * @return Promise */ - resendVerificationEmail(sessionTokenHex) { + resendVerificationEmail: function(sessionTokenHex) { return this._request("/recovery_email/resend_code", "POST", deriveHawkCredentials(sessionTokenHex, "sessionToken")); }, @@ -262,7 +262,7 @@ this.FxAccountsClient.prototype = { * user's password (bytes) * } */ - accountKeys(keyFetchTokenHex) { + accountKeys: function (keyFetchTokenHex) { let creds = deriveHawkCredentials(keyFetchTokenHex, "keyFetchToken"); let keyRequestKey = creds.extra.slice(0, 32); let morecreds = CryptoUtils.hkdf(keyRequestKey, undefined, @@ -311,7 +311,7 @@ this.FxAccountsClient.prototype = { * wrapping any of these HTTP code/errno pairs: * https://github.com/mozilla/fxa-auth-server/blob/master/docs/api.md#response-12 */ - signCertificate(sessionTokenHex, serializedPublicKey, lifetime) { + signCertificate: function (sessionTokenHex, serializedPublicKey, lifetime) { let creds = deriveHawkCredentials(sessionTokenHex, "sessionToken"); let body = { publicKey: serializedPublicKey, @@ -334,7 +334,7 @@ this.FxAccountsClient.prototype = { * The promise resolves to true if the account exists, or false * if it doesn't. The promise is rejected on other errors. */ - accountExists(email) { + accountExists: function (email) { return this.signIn(email, "").then( (cantHappen) => { throw new Error("How did I sign in with an empty password?"); @@ -362,8 +362,8 @@ this.FxAccountsClient.prototype = { * * Used for differentiating between password change and account deletion. */ - accountStatus(uid) { - return this._request("/account/status?uid=" + uid, "GET").then( + accountStatus: function(uid) { + return this._request("/account/status?uid="+uid, "GET").then( (result) => { return result.exists; }, @@ -540,7 +540,7 @@ this.FxAccountsClient.prototype = { return this._request(path, "GET", creds, {}); }, - _clearBackoff() { + _clearBackoff: function() { this.backoffError = null; }, diff --git a/services/fxaccounts/FxAccountsManager.jsm b/services/fxaccounts/FxAccountsManager.jsm index f3044833b24f..680310ff55e0 100644 --- a/services/fxaccounts/FxAccountsManager.jsm +++ b/services/fxaccounts/FxAccountsManager.jsm @@ -27,12 +27,12 @@ XPCOMUtils.defineLazyServiceGetter(this, "permissionManager", this.FxAccountsManager = { - init() { + init: function() { Services.obs.addObserver(this, ONLOGOUT_NOTIFICATION, false); Services.obs.addObserver(this, ON_FXA_UPDATE_NOTIFICATION, false); }, - observe(aSubject, aTopic, aData) { + observe: function(aSubject, aTopic, aData) { // Both topics indicate our cache is invalid this._activeSession = null; @@ -67,7 +67,7 @@ this.FxAccountsManager = { } }, - _error(aError, aDetails) { + _error: function(aError, aDetails) { log.error(aError); let reason = { error: aError @@ -78,7 +78,7 @@ this.FxAccountsManager = { return Promise.reject(reason); }, - _getError(aServerResponse) { + _getError: function(aServerResponse) { if (!aServerResponse || !aServerResponse.error || !aServerResponse.error.errno) { return; } @@ -86,7 +86,7 @@ this.FxAccountsManager = { return error; }, - _serverError(aServerResponse) { + _serverError: function(aServerResponse) { let error = this._getError({ error: aServerResponse }); return this._error(error ? error : ERROR_SERVER_ERROR, aServerResponse); }, @@ -96,11 +96,11 @@ this.FxAccountsManager = { // client used by the fxAccounts object because deep down they should have // access to the same hawk request object which will enable them to share // local clock skeq data. - _getFxAccountsClient() { + _getFxAccountsClient: function() { return this._fxAccounts.getAccountsClient(); }, - _signInSignUp(aMethod, aEmail, aPassword, aFetchKeys) { + _signInSignUp: function(aMethod, aEmail, aPassword, aFetchKeys) { if (Services.io.offline) { return this._error(ERROR_OFFLINE); } @@ -135,7 +135,7 @@ this.FxAccountsManager = { let error = this._getError(user); if (!user || !user.uid || !user.sessionToken || error) { return this._error(error ? error : ERROR_INTERNAL_INVALID_USER, { - user + user: user }); } @@ -199,7 +199,7 @@ this.FxAccountsManager = { * FxAccountsClient.signCertificate() * See the latter method for possible (error code, errno) pairs. */ - _handleGetAssertionError(reason, aAudience, aPrincipal) { + _handleGetAssertionError: function(reason, aAudience, aPrincipal) { log.debug("FxAccountsManager._handleGetAssertionError()"); let errno = (reason ? reason.errno : NaN) || NaN; // If the previously valid email/password pair is no longer valid ... @@ -236,7 +236,7 @@ this.FxAccountsManager = { return Promise.reject(reason.message ? { error: reason.message } : reason); }, - _getAssertion(aAudience, aPrincipal) { + _getAssertion: function(aAudience, aPrincipal) { return this._fxAccounts.getAssertion(aAudience).then( (result) => { if (aPrincipal) { @@ -260,8 +260,8 @@ this.FxAccountsManager = { * 2) The person typing can't prove knowledge of the password used * to log in. Failure should do nothing. */ - _refreshAuthentication(aAudience, aEmail, aPrincipal, - logoutOnFailure = false) { + _refreshAuthentication: function(aAudience, aEmail, aPrincipal, + logoutOnFailure=false) { this._refreshing = true; return this._uiRequest(UI_REQUEST_REFRESH_AUTH, aAudience, aPrincipal, aEmail).then( @@ -283,11 +283,11 @@ this.FxAccountsManager = { ); }, - _localSignOut() { + _localSignOut: function() { return this._fxAccounts.signOut(true); }, - _signOut() { + _signOut: function() { if (!this._activeSession) { return Promise.resolve(); } @@ -326,7 +326,7 @@ this.FxAccountsManager = { ); }, - _uiRequest(aRequest, aAudience, aPrincipal, aParams) { + _uiRequest: function(aRequest, aAudience, aPrincipal, aParams) { if (Services.io.offline) { return this._error(ERROR_OFFLINE); } @@ -358,7 +358,7 @@ this.FxAccountsManager = { ); }, - _addPermission(aPrincipal) { + _addPermission: function(aPrincipal) { // This will fail from tests cause we are running them in the child // process until we have chrome tests in b2g. Bug 797164. try { @@ -371,15 +371,15 @@ this.FxAccountsManager = { // -- API -- - signIn(aEmail, aPassword, aFetchKeys) { + signIn: function(aEmail, aPassword, aFetchKeys) { return this._signInSignUp("signIn", aEmail, aPassword, aFetchKeys); }, - signUp(aEmail, aPassword, aFetchKeys) { + signUp: function(aEmail, aPassword, aFetchKeys) { return this._signInSignUp("signUp", aEmail, aPassword, aFetchKeys); }, - signOut() { + signOut: function() { if (!this._activeSession) { // If there is no cached active session, we try to get it from the // account storage. @@ -395,7 +395,7 @@ this.FxAccountsManager = { return this._signOut(); }, - resendVerificationEmail() { + resendVerificationEmail: function() { return this._fxAccounts.resendVerificationEmail().then( (result) => { return result; @@ -406,7 +406,7 @@ this.FxAccountsManager = { ); }, - getAccount() { + getAccount: function() { // We check first if we have session details cached. if (this._activeSession) { // If our cache says that the account is not yet verified, @@ -452,7 +452,7 @@ this.FxAccountsManager = { ); }, - queryAccount(aEmail) { + queryAccount: function(aEmail) { log.debug("queryAccount " + aEmail); if (Services.io.offline) { return this._error(ERROR_OFFLINE); @@ -481,7 +481,7 @@ this.FxAccountsManager = { ); }, - verificationStatus() { + verificationStatus: function() { log.debug("verificationStatus"); if (!this._activeSession || !this._activeSession.sessionToken) { this._error(ERROR_NO_TOKEN_SESSION); @@ -545,7 +545,7 @@ this.FxAccountsManager = { * silent - (bool) Prevent any UI interaction. * I.e., try to get an automatic assertion. */ - getAssertion(aAudience, aPrincipal, aOptions) { + getAssertion: function(aAudience, aPrincipal, aOptions) { if (!aAudience) { return this._error(ERROR_INVALID_AUDIENCE); } @@ -561,7 +561,7 @@ this.FxAccountsManager = { // Three have-user cases to consider. First: are we unverified? if (!user.verified) { return this._error(ERROR_UNVERIFIED_ACCOUNT, { - user + user: user }); } // Second case: do we need to refresh? @@ -620,11 +620,11 @@ this.FxAccountsManager = { ); }, - getKeys() { + getKeys: function() { let syncEnabled = false; try { syncEnabled = Services.prefs.getBoolPref("services.sync.enabled"); - } catch (e) { + } catch(e) { dump("Sync is disabled, so you won't get the keys. " + e + "\n"); } @@ -641,7 +641,7 @@ this.FxAccountsManager = { if (!user.verified) { return this._error(ERROR_UNVERIFIED_ACCOUNT, { - user + user: user }); } diff --git a/services/fxaccounts/FxAccountsOAuthClient.jsm b/services/fxaccounts/FxAccountsOAuthClient.jsm index 5b3091fe3ea6..d06011dd41b6 100644 --- a/services/fxaccounts/FxAccountsOAuthClient.jsm +++ b/services/fxaccounts/FxAccountsOAuthClient.jsm @@ -116,7 +116,7 @@ this.FxAccountsOAuthClient.prototype = { * Opens a tab at "this._fxaOAuthStartUrl". * Registers a WebChannel listener and sets up a callback if needed. */ - launchWebFlow() { + launchWebFlow: function () { if (!this._channelCallback) { this._registerChannel(); } @@ -132,7 +132,7 @@ this.FxAccountsOAuthClient.prototype = { /** * Release all resources that are in use. */ - tearDown() { + tearDown: function() { this.onComplete = null; this.onError = null; this._complete = true; @@ -145,7 +145,7 @@ this.FxAccountsOAuthClient.prototype = { * * @private */ - _configureChannel() { + _configureChannel: function() { this._webChannelId = "oauth_" + this.parameters.client_id; // if this.parameters.content_uri is present but not a valid URI, then this will throw an error. @@ -160,7 +160,7 @@ this.FxAccountsOAuthClient.prototype = { * Create a new channel with the WebChannelBroker, setup a callback listener * @private */ - _registerChannel() { + _registerChannel: function() { /** * Processes messages that are called back from the FxAccountsChannel * @@ -172,7 +172,7 @@ this.FxAccountsOAuthClient.prototype = { * Channel message event sendingContext * @private */ - let listener = function(webChannelId, message, sendingContext) { + let listener = function (webChannelId, message, sendingContext) { if (message) { let command = message.command; let data = message.data; @@ -251,7 +251,7 @@ this.FxAccountsOAuthClient.prototype = { * OAuth client options * @private */ - _validateOptions(options) { + _validateOptions: function (options) { if (!options || !options.parameters) { throw new Error("Missing 'parameters' configuration option"); } diff --git a/services/fxaccounts/FxAccountsOAuthGrantClient.jsm b/services/fxaccounts/FxAccountsOAuthGrantClient.jsm index 5880dda54bea..4319a07ab526 100644 --- a/services/fxaccounts/FxAccountsOAuthGrantClient.jsm +++ b/services/fxaccounts/FxAccountsOAuthGrantClient.jsm @@ -59,7 +59,7 @@ this.FxAccountsOAuthGrantClient.prototype = { * @return Promise * Resolves: {Object} Object with access_token property */ - getTokenFromAssertion(assertion, scope) { + getTokenFromAssertion: function (assertion, scope) { if (!assertion) { throw new Error("Missing 'assertion' parameter"); } @@ -67,9 +67,9 @@ this.FxAccountsOAuthGrantClient.prototype = { throw new Error("Missing 'scope' parameter"); } let params = { - scope, + scope: scope, client_id: this.parameters.client_id, - assertion, + assertion: assertion, response_type: "token" }; @@ -84,12 +84,12 @@ this.FxAccountsOAuthGrantClient.prototype = { * Resolves: {Object} with the server response, which is typically * ignored. */ - destroyToken(token) { + destroyToken: function (token) { if (!token) { throw new Error("Missing 'token' parameter"); } let params = { - token, + token: token, }; return this._createRequest(DESTROY_ENDPOINT, "POST", params); @@ -102,7 +102,7 @@ this.FxAccountsOAuthGrantClient.prototype = { * OAuth client options * @private */ - _validateOptions(options) { + _validateOptions: function (options) { if (!options) { throw new Error("Missing configuration options"); } @@ -131,7 +131,7 @@ this.FxAccountsOAuthGrantClient.prototype = { * Rejects: {FxAccountsOAuthGrantClientError} Profile client error. * @private */ - _createRequest(path, method = "POST", params) { + _createRequest: function(path, method = "POST", params) { return new Promise((resolve, reject) => { let profileDataUrl = this.serverURL + path; let request = new this._Request(profileDataUrl); @@ -140,7 +140,7 @@ this.FxAccountsOAuthGrantClient.prototype = { request.setHeader("Accept", "application/json"); request.setHeader("Content-Type", "application/json"); - request.onComplete = function(error) { + request.onComplete = function (error) { if (error) { return reject(new FxAccountsOAuthGrantClientError({ error: ERROR_NETWORK, diff --git a/services/fxaccounts/FxAccountsProfile.jsm b/services/fxaccounts/FxAccountsProfile.jsm index 46271a7dda75..b63cd64c1d74 100644 --- a/services/fxaccounts/FxAccountsProfile.jsm +++ b/services/fxaccounts/FxAccountsProfile.jsm @@ -71,7 +71,7 @@ function hasChanged(oldData, newData) { return !deepEqual(oldData, newData); } -this.FxAccountsProfile = function(options = {}) { +this.FxAccountsProfile = function (options = {}) { this._cachedProfile = null; this._cachedAt = 0; // when we saved the cached version. this._currentFetchPromise = null; @@ -106,20 +106,20 @@ this.FxAccountsProfile.prototype = { } }, - tearDown() { + tearDown: function () { this.fxa = null; this.client = null; this._cachedProfile = null; Services.obs.removeObserver(this, ON_PROFILE_CHANGE_NOTIFICATION); }, - _getCachedProfile() { + _getCachedProfile: function () { // The cached profile will end up back in the generic accountData // once bug 1157529 is fixed. return Promise.resolve(this._cachedProfile); }, - _notifyProfileChange(uid) { + _notifyProfileChange: function (uid) { this._isNotifying = true; Services.obs.notifyObservers(null, ON_PROFILE_CHANGE_NOTIFICATION, uid); this._isNotifying = false; @@ -127,7 +127,7 @@ this.FxAccountsProfile.prototype = { // Cache fetched data if it is different from what's in the cache. // Send out a notification if it has changed so that UI can update. - _cacheProfile(profileData) { + _cacheProfile: function (profileData) { if (!hasChanged(this._cachedProfile, profileData)) { log.debug("fetched profile matches cached copy"); return Promise.resolve(null); // indicates no change (but only tests care) @@ -142,7 +142,7 @@ this.FxAccountsProfile.prototype = { }); }, - _fetchAndCacheProfile() { + _fetchAndCacheProfile: function () { if (!this._currentFetchPromise) { this._currentFetchPromise = this.client.fetchProfile().then(profile => { return this._cacheProfile(profile).then(() => { @@ -162,7 +162,7 @@ this.FxAccountsProfile.prototype = { // Returns cached data right away if available, then fetches the latest profile // data in the background. After data is fetched a notification will be sent // out if the profile has changed. - getProfile() { + getProfile: function () { return this._getCachedProfile() .then(cachedProfile => { if (cachedProfile) { diff --git a/services/fxaccounts/FxAccountsProfileClient.jsm b/services/fxaccounts/FxAccountsProfileClient.jsm index ea40258fbfc1..1e5edc634c21 100644 --- a/services/fxaccounts/FxAccountsProfileClient.jsm +++ b/services/fxaccounts/FxAccountsProfileClient.jsm @@ -128,7 +128,7 @@ this.FxAccountsProfileClient.prototype = { * Rejects: {FxAccountsProfileClientError} Profile client error. * @private */ - _rawRequest(path, method, token) { + _rawRequest: function(path, method, token) { return new Promise((resolve, reject) => { let profileDataUrl = this.serverURL + path; let request = new this._Request(profileDataUrl); @@ -137,7 +137,7 @@ this.FxAccountsProfileClient.prototype = { request.setHeader("Authorization", "Bearer " + token); request.setHeader("Accept", "application/json"); - request.onComplete = function(error) { + request.onComplete = function (error) { if (error) { return reject(new FxAccountsProfileClientError({ error: ERROR_NETWORK, @@ -192,7 +192,7 @@ this.FxAccountsProfileClient.prototype = { * Resolves: {Object} Successful response from the '/profile' endpoint. * Rejects: {FxAccountsProfileClientError} profile client error. */ - fetchProfile() { + fetchProfile: function () { log.debug("FxAccountsProfileClient: Requested profile"); return this._createRequest("/profile", "GET"); }, @@ -204,7 +204,7 @@ this.FxAccountsProfileClient.prototype = { * Resolves: {Object} Successful response from the '/avatar' endpoint. * Rejects: {FxAccountsProfileClientError} profile client error. */ - fetchProfileImage() { + fetchProfileImage: function () { log.debug("FxAccountsProfileClient: Requested avatar"); return this._createRequest("/avatar", "GET"); } diff --git a/services/fxaccounts/FxAccountsPush.js b/services/fxaccounts/FxAccountsPush.js index c50bfb21dad1..be72f4588d04 100644 --- a/services/fxaccounts/FxAccountsPush.js +++ b/services/fxaccounts/FxAccountsPush.js @@ -240,4 +240,4 @@ const components = [FxAccountsPushService]; this.NSGetFactory = XPCOMUtils.generateNSGetFactory(components); // The following registration below helps with testing this service. -this.EXPORTED_SYMBOLS = ["FxAccountsPushService"]; +this.EXPORTED_SYMBOLS=["FxAccountsPushService"]; diff --git a/services/fxaccounts/FxAccountsStorage.jsm b/services/fxaccounts/FxAccountsStorage.jsm index 0c3a1e56ab40..43e2d21a0ca5 100644 --- a/services/fxaccounts/FxAccountsStorage.jsm +++ b/services/fxaccounts/FxAccountsStorage.jsm @@ -274,7 +274,7 @@ this.FxAccountsStorageManager.prototype = { let got; try { got = yield this.plainStorage.get(); - } catch (err) { + } catch(err) { // File hasn't been created yet. That will be done // when write is called. if (!(err instanceof OS.File.Error) || !err.becauseNoSuchFile) { @@ -444,25 +444,25 @@ this.FxAccountsStorageManager.prototype = { function JSONStorage(options) { this.baseDir = options.baseDir; this.path = OS.Path.join(options.baseDir, options.filename); -} +}; JSONStorage.prototype = { - set(contents) { + set: function(contents) { log.trace("starting write of json user data", contents ? Object.keys(contents.accountData) : "null"); let start = Date.now(); return OS.File.makeDir(this.baseDir, {ignoreExisting: true}) .then(CommonUtils.writeJSON.bind(null, contents, this.path)) .then(result => { - log.trace("finished write of json user data - took", Date.now() - start); + log.trace("finished write of json user data - took", Date.now()-start); return result; }); }, - get() { + get: function() { log.trace("starting fetch of json user data"); let start = Date.now(); return CommonUtils.readJSON(this.path).then(result => { - log.trace("finished fetch of json user data - took", Date.now() - start); + log.trace("finished fetch of json user data - took", Date.now()-start); return result; }); }, diff --git a/services/fxaccounts/FxAccountsWebChannel.jsm b/services/fxaccounts/FxAccountsWebChannel.jsm index 59a6326d1943..fd84dd3e9231 100644 --- a/services/fxaccounts/FxAccountsWebChannel.jsm +++ b/services/fxaccounts/FxAccountsWebChannel.jsm @@ -157,7 +157,7 @@ this.FxAccountsWebChannel.prototype = { let canLinkAccount = this._helpers.shouldAllowRelink(data.email); let response = { - command, + command: command, messageId: message.messageId, data: { ok: canLinkAccount } }; diff --git a/services/fxaccounts/tests/xpcshell/test_accounts.js b/services/fxaccounts/tests/xpcshell/test_accounts.js index b2fa1e86f359..d6139a0765b6 100644 --- a/services/fxaccounts/tests/xpcshell/test_accounts.js +++ b/services/fxaccounts/tests/xpcshell/test_accounts.js @@ -93,7 +93,7 @@ function MockFxAccountsClient() { // mock calls up to the auth server to determine whether the // user account has been verified - this.recoveryEmailStatus = function(sessionToken) { + this.recoveryEmailStatus = function (sessionToken) { // simulate a call to /recovery_email/status return Promise.resolve({ email: this._email, @@ -107,7 +107,7 @@ function MockFxAccountsClient() { return deferred.promise; }; - this.accountKeys = function(keyFetchToken) { + this.accountKeys = function (keyFetchToken) { let deferred = Promise.defer(); do_timeout(50, () => { @@ -149,7 +149,7 @@ function MockFxAccounts() { _getCertificateSigned_calls: [], _d_signCertificate: Promise.defer(), _now_is: new Date(), - now() { + now: function () { return this._now_is; }, newAccountState(credentials) { @@ -158,7 +158,7 @@ function MockFxAccounts() { storage.initialize(credentials); return new AccountState(storage); }, - getCertificateSigned(sessionToken, serializedPublicKey) { + getCertificateSigned: function (sessionToken, serializedPublicKey) { _("mock getCertificateSigned\n"); this._getCertificateSigned_calls.push([sessionToken, serializedPublicKey]); return this._d_signCertificate.promise; @@ -334,7 +334,7 @@ add_task(function* test_getCertificateOffline() { do_check_eq(err, "Error: OFFLINE"); } ); - yield fxa.signOut(/* localOnly = */true); + yield fxa.signOut(/*localOnly = */true); }); add_task(function* test_getCertificateCached() { @@ -361,7 +361,7 @@ add_task(function* test_getCertificateCached() { // should have the same keypair and cert. do_check_eq(keyPair, credentials.keyPair.rawKeyPair); do_check_eq(certificate, credentials.cert.rawCert); - yield fxa.signOut(/* localOnly = */true); + yield fxa.signOut(/*localOnly = */true); }); add_task(function* test_getCertificateExpiredCert() { @@ -392,7 +392,7 @@ add_task(function* test_getCertificateExpiredCert() { // should have the same keypair but a new cert. do_check_eq(keyPair, credentials.keyPair.rawKeyPair); do_check_neq(certificate, credentials.cert.rawCert); - yield fxa.signOut(/* localOnly = */true); + yield fxa.signOut(/*localOnly = */true); }); add_task(function* test_getCertificateExpiredKeypair() { @@ -425,7 +425,7 @@ add_task(function* test_getCertificateExpiredKeypair() { // should have fetched both. do_check_neq(keyPair, credentials.keyPair.rawKeyPair); do_check_neq(certificate, credentials.cert.rawCert); - yield fxa.signOut(/* localOnly = */true); + yield fxa.signOut(/*localOnly = */true); }); // Sanity-check that our mocked client is working correctly @@ -834,7 +834,7 @@ add_task(function* test_resend_email_not_signed_in() { try { yield fxa.resendVerificationEmail(); - } catch (err) { + } catch(err) { do_check_eq(err.message, "Cannot resend verification email; no signed-in user"); return; @@ -964,11 +964,11 @@ add_task(function* test_sign_out_with_device() { signOutAndDeviceDestroy: { count: 0, args: [] } }; const client = fxa.internal.fxAccountsClient; - client.signOut = function() { + client.signOut = function () { spy.signOut.count += 1; return Promise.resolve(); }; - client.signOutAndDestroyDevice = function() { + client.signOutAndDestroyDevice = function () { spy.signOutAndDeviceDestroy.count += 1; spy.signOutAndDeviceDestroy.args.push(arguments); return Promise.resolve(); @@ -1011,12 +1011,12 @@ add_task(function* test_sign_out_without_device() { signOutAndDeviceDestroy: { count: 0 } }; const client = fxa.internal.fxAccountsClient; - client.signOut = function() { + client.signOut = function () { spy.signOut.count += 1; spy.signOut.args.push(arguments); return Promise.resolve(); }; - client.signOutAndDestroyDevice = function() { + client.signOutAndDestroyDevice = function () { spy.signOutAndDeviceDestroy.count += 1; return Promise.resolve(); }; @@ -1079,14 +1079,14 @@ add_test(function test_getOAuthToken() { serverURL: "http://example.com/v1", client_id: "abc123" }); - client.getTokenFromAssertion = function() { + client.getTokenFromAssertion = function () { getTokenFromAssertionCalled = true; return Promise.resolve({ access_token: "token" }); }; fxa.setSignedInUser(alice).then( () => { - fxa.getOAuthToken({ scope: "profile", client }).then( + fxa.getOAuthToken({ scope: "profile", client: client }).then( (result) => { do_check_true(getTokenFromAssertionCalled); do_check_eq(result, "token"); @@ -1111,7 +1111,7 @@ add_test(function test_getOAuthTokenScoped() { serverURL: "http://example.com/v1", client_id: "abc123" }); - client.getTokenFromAssertion = function(assertion, scopeString) { + client.getTokenFromAssertion = function (assertion, scopeString) { equal(scopeString, "foo bar"); getTokenFromAssertionCalled = true; return Promise.resolve({ access_token: "token" }); @@ -1119,7 +1119,7 @@ add_test(function test_getOAuthTokenScoped() { fxa.setSignedInUser(alice).then( () => { - fxa.getOAuthToken({ scope: ["foo", "bar"], client }).then( + fxa.getOAuthToken({ scope: ["foo", "bar"], client: client }).then( (result) => { do_check_true(getTokenFromAssertionCalled); do_check_eq(result, "token"); @@ -1144,22 +1144,22 @@ add_task(function* test_getOAuthTokenCached() { serverURL: "http://example.com/v1", client_id: "abc123" }); - client.getTokenFromAssertion = function() { + client.getTokenFromAssertion = function () { numTokenFromAssertionCalls += 1; return Promise.resolve({ access_token: "token" }); }; yield fxa.setSignedInUser(alice); - let result = yield fxa.getOAuthToken({ scope: "profile", client, service: "test-service" }); + let result = yield fxa.getOAuthToken({ scope: "profile", client: client, service: "test-service" }); do_check_eq(numTokenFromAssertionCalls, 1); do_check_eq(result, "token"); // requesting it again should not re-fetch the token. - result = yield fxa.getOAuthToken({ scope: "profile", client, service: "test-service" }); + result = yield fxa.getOAuthToken({ scope: "profile", client: client, service: "test-service" }); do_check_eq(numTokenFromAssertionCalls, 1); do_check_eq(result, "token"); // But requesting the same service and a different scope *will* get a new one. - result = yield fxa.getOAuthToken({ scope: "something-else", client, service: "test-service" }); + result = yield fxa.getOAuthToken({ scope: "something-else", client: client, service: "test-service" }); do_check_eq(numTokenFromAssertionCalls, 2); do_check_eq(result, "token"); }); @@ -1177,26 +1177,26 @@ add_task(function* test_getOAuthTokenCachedScopeNormalization() { serverURL: "http://example.com/v1", client_id: "abc123" }); - client.getTokenFromAssertion = function() { + client.getTokenFromAssertion = function () { numTokenFromAssertionCalls += 1; return Promise.resolve({ access_token: "token" }); }; yield fxa.setSignedInUser(alice); - let result = yield fxa.getOAuthToken({ scope: ["foo", "bar"], client, service: "test-service" }); + let result = yield fxa.getOAuthToken({ scope: ["foo", "bar"], client: client, service: "test-service" }); do_check_eq(numTokenFromAssertionCalls, 1); do_check_eq(result, "token"); // requesting it again with the scope array in a different order not re-fetch the token. - result = yield fxa.getOAuthToken({ scope: ["bar", "foo"], client, service: "test-service" }); + result = yield fxa.getOAuthToken({ scope: ["bar", "foo"], client: client, service: "test-service" }); do_check_eq(numTokenFromAssertionCalls, 1); do_check_eq(result, "token"); // requesting it again with the scope array in different case not re-fetch the token. - result = yield fxa.getOAuthToken({ scope: ["Bar", "Foo"], client, service: "test-service" }); + result = yield fxa.getOAuthToken({ scope: ["Bar", "Foo"], client: client, service: "test-service" }); do_check_eq(numTokenFromAssertionCalls, 1); do_check_eq(result, "token"); // But requesting with a new entry in the array does fetch one. - result = yield fxa.getOAuthToken({ scope: ["foo", "bar", "etc"], client, service: "test-service" }); + result = yield fxa.getOAuthToken({ scope: ["foo", "bar", "etc"], client: client, service: "test-service" }); do_check_eq(numTokenFromAssertionCalls, 2); do_check_eq(result, "token"); }); @@ -1239,7 +1239,7 @@ add_test(function test_getOAuthToken_misconfigure_oauth_uri() { add_test(function test_getOAuthToken_no_account() { let fxa = new MockFxAccounts(); - fxa.internal.currentAccountState.getUserAccountData = function() { + fxa.internal.currentAccountState.getUserAccountData = function () { return Promise.resolve(null); }; @@ -1275,7 +1275,7 @@ add_test(function test_getOAuthToken_network_error() { serverURL: "http://example.com/v1", client_id: "abc123" }); - client.getTokenFromAssertion = function() { + client.getTokenFromAssertion = function () { return Promise.reject(new FxAccountsOAuthGrantClientError({ error: ERROR_NETWORK, errno: ERRNO_NETWORK @@ -1283,7 +1283,7 @@ add_test(function test_getOAuthToken_network_error() { }; fxa.setSignedInUser(alice).then(() => { - fxa.getOAuthToken({ scope: "profile", client }) + fxa.getOAuthToken({ scope: "profile", client: client }) .then(null, err => { do_check_eq(err.message, "NETWORK_ERROR"); do_check_eq(err.details.errno, ERRNO_NETWORK); @@ -1304,7 +1304,7 @@ add_test(function test_getOAuthToken_auth_error() { serverURL: "http://example.com/v1", client_id: "abc123" }); - client.getTokenFromAssertion = function() { + client.getTokenFromAssertion = function () { return Promise.reject(new FxAccountsOAuthGrantClientError({ error: ERROR_INVALID_FXA_ASSERTION, errno: ERRNO_INVALID_FXA_ASSERTION @@ -1312,7 +1312,7 @@ add_test(function test_getOAuthToken_auth_error() { }; fxa.setSignedInUser(alice).then(() => { - fxa.getOAuthToken({ scope: "profile", client }) + fxa.getOAuthToken({ scope: "profile", client: client }) .then(null, err => { do_check_eq(err.message, "AUTH_ERROR"); do_check_eq(err.details.errno, ERRNO_INVALID_FXA_ASSERTION); @@ -1333,12 +1333,12 @@ add_test(function test_getOAuthToken_unknown_error() { serverURL: "http://example.com/v1", client_id: "abc123" }); - client.getTokenFromAssertion = function() { + client.getTokenFromAssertion = function () { return Promise.reject("boom"); }; fxa.setSignedInUser(alice).then(() => { - fxa.getOAuthToken({ scope: "profile", client }) + fxa.getOAuthToken({ scope: "profile", client: client }) .then(null, err => { do_check_eq(err.message, "UNKNOWN_ERROR"); run_next_test(); @@ -1351,10 +1351,10 @@ add_test(function test_getSignedInUserProfile() { alice.verified = true; let mockProfile = { - getProfile() { + getProfile: function () { return Promise.resolve({ avatar: "image" }); }, - tearDown() {}, + tearDown: function() {}, }; let fxa = new FxAccounts({ _signOutServer() { return Promise.resolve(); }, @@ -1377,17 +1377,17 @@ add_test(function test_getSignedInUserProfile_error_uses_account_data() { let alice = getTestUser("alice"); alice.verified = true; - fxa.internal.getSignedInUser = function() { + fxa.internal.getSignedInUser = function () { return Promise.resolve({ email: "foo@bar.com" }); }; let teardownCalled = false; fxa.setSignedInUser(alice).then(() => { fxa.internal._profile = { - getProfile() { + getProfile: function () { return Promise.reject("boom"); }, - tearDown() { + tearDown: function() { teardownCalled = true; } }; @@ -1420,7 +1420,7 @@ add_test(function test_getSignedInUserProfile_unverified_account() { add_test(function test_getSignedInUserProfile_no_account_data() { let fxa = new MockFxAccounts(); - fxa.internal.getSignedInUser = function() { + fxa.internal.getSignedInUser = function () { return Promise.resolve(null); }; @@ -1469,11 +1469,11 @@ function expandHex(two_hex) { let eight_hex = two_hex + two_hex + two_hex + two_hex; let thirtytwo_hex = eight_hex + eight_hex + eight_hex + eight_hex; return thirtytwo_hex + thirtytwo_hex; -} +}; function expandBytes(two_hex) { return CommonUtils.hexToBytes(expandHex(two_hex)); -} +}; function getTestUser(name) { return { @@ -1493,7 +1493,7 @@ function makeObserver(aObserveTopic, aObserveFunc) { // nsIObserver is to be an observer QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIObserver]), - observe(aSubject, aTopic, aData) { + observe: function (aSubject, aTopic, aData) { log.debug("observed " + aTopic + " " + aData); if (aTopic == aObserveTopic) { removeMe(); @@ -1511,7 +1511,8 @@ function makeObserver(aObserveTopic, aObserveFunc) { return removeMe; } -function do_check_throws(func, result, stack) { +function do_check_throws(func, result, stack) +{ if (!stack) stack = Components.stack.caller; diff --git a/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js b/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js index 11c845188892..9a2d2c127afc 100644 --- a/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js +++ b/services/fxaccounts/tests/xpcshell/test_accounts_device_registration.js @@ -69,7 +69,7 @@ function MockFxAccountsClient(device) { // mock calls up to the auth server to determine whether the // user account has been verified - this.recoveryEmailStatus = function(sessionToken) { + this.recoveryEmailStatus = function (sessionToken) { // simulate a call to /recovery_email/status return Promise.resolve({ email: this._email, @@ -110,7 +110,7 @@ function MockFxAccounts(device = {}) { return new Promise((resolve) => { resolve({ endpoint: "http://mochi.test:8888", - getKey(type) { + getKey: function(type) { return ChromeUtils.base64URLDecode( type === "auth" ? BOGUS_AUTHKEY : BOGUS_PUBLICKEY, { padding: "ignore" }); @@ -138,7 +138,7 @@ add_task(function* test_updateDeviceRegistration_with_new_device() { getDeviceList: { count: 0, args: [] } }; const client = fxa.internal.fxAccountsClient; - client.registerDevice = function() { + client.registerDevice = function () { spy.registerDevice.count += 1; spy.registerDevice.args.push(arguments); return Promise.resolve({ @@ -148,12 +148,12 @@ add_task(function* test_updateDeviceRegistration_with_new_device() { type: deviceType }); }; - client.updateDevice = function() { + client.updateDevice = function () { spy.updateDevice.count += 1; spy.updateDevice.args.push(arguments); return Promise.resolve({}); }; - client.getDeviceList = function() { + client.getDeviceList = function () { spy.getDeviceList.count += 1; spy.getDeviceList.args.push(arguments); return Promise.resolve([]); @@ -194,12 +194,12 @@ add_task(function* test_updateDeviceRegistration_with_existing_device() { getDeviceList: { count: 0, args: [] } }; const client = fxa.internal.fxAccountsClient; - client.registerDevice = function() { + client.registerDevice = function () { spy.registerDevice.count += 1; spy.registerDevice.args.push(arguments); return Promise.resolve({}); }; - client.updateDevice = function() { + client.updateDevice = function () { spy.updateDevice.count += 1; spy.updateDevice.args.push(arguments); return Promise.resolve({ @@ -207,7 +207,7 @@ add_task(function* test_updateDeviceRegistration_with_existing_device() { name: deviceName }); }; - client.getDeviceList = function() { + client.getDeviceList = function () { spy.getDeviceList.count += 1; spy.getDeviceList.args.push(arguments); return Promise.resolve([]); @@ -247,7 +247,7 @@ add_task(function* test_updateDeviceRegistration_with_unknown_device_error() { getDeviceList: { count: 0, args: [] } }; const client = fxa.internal.fxAccountsClient; - client.registerDevice = function() { + client.registerDevice = function () { spy.registerDevice.count += 1; spy.registerDevice.args.push(arguments); return Promise.resolve({ @@ -257,7 +257,7 @@ add_task(function* test_updateDeviceRegistration_with_unknown_device_error() { type: deviceType }); }; - client.updateDevice = function() { + client.updateDevice = function () { spy.updateDevice.count += 1; spy.updateDevice.args.push(arguments); return Promise.reject({ @@ -265,7 +265,7 @@ add_task(function* test_updateDeviceRegistration_with_unknown_device_error() { errno: ERRNO_UNKNOWN_DEVICE }); }; - client.getDeviceList = function() { + client.getDeviceList = function () { spy.getDeviceList.count += 1; spy.getDeviceList.args.push(arguments); return Promise.resolve([]); @@ -307,12 +307,12 @@ add_task(function* test_updateDeviceRegistration_with_device_session_conflict_er getDeviceList: { count: 0, args: [] } }; const client = fxa.internal.fxAccountsClient; - client.registerDevice = function() { + client.registerDevice = function () { spy.registerDevice.count += 1; spy.registerDevice.args.push(arguments); return Promise.resolve({}); }; - client.updateDevice = function() { + client.updateDevice = function () { spy.updateDevice.count += 1; spy.updateDevice.args.push(arguments); spy.updateDevice.time = Date.now(); @@ -327,7 +327,7 @@ add_task(function* test_updateDeviceRegistration_with_device_session_conflict_er name: deviceName }); }; - client.getDeviceList = function() { + client.getDeviceList = function () { spy.getDeviceList.count += 1; spy.getDeviceList.args.push(arguments); spy.getDeviceList.time = Date.now(); @@ -376,7 +376,7 @@ add_task(function* test_updateDeviceRegistration_with_unrecoverable_error() { getDeviceList: { count: 0, args: [] } }; const client = fxa.internal.fxAccountsClient; - client.registerDevice = function() { + client.registerDevice = function () { spy.registerDevice.count += 1; spy.registerDevice.args.push(arguments); return Promise.reject({ @@ -384,12 +384,12 @@ add_task(function* test_updateDeviceRegistration_with_unrecoverable_error() { errno: ERRNO_TOO_MANY_CLIENT_REQUESTS }); }; - client.updateDevice = function() { + client.updateDevice = function () { spy.updateDevice.count += 1; spy.updateDevice.args.push(arguments); return Promise.resolve({}); }; - client.getDeviceList = function() { + client.getDeviceList = function () { spy.getDeviceList.count += 1; spy.getDeviceList.args.push(arguments); return Promise.resolve([]); @@ -420,7 +420,7 @@ add_task(function* test_getDeviceId_with_no_device_id_invokes_device_registratio fxa.internal.currentAccountState.getUserAccountData = () => Promise.resolve({ email: credentials.email, deviceRegistrationVersion: DEVICE_REGISTRATION_VERSION }); - fxa.internal._registerOrUpdateDevice = function() { + fxa.internal._registerOrUpdateDevice = function () { spy.count += 1; spy.args.push(arguments); return Promise.resolve("bar"); @@ -444,7 +444,7 @@ add_task(function* test_getDeviceId_with_registration_version_outdated_invokes_d const spy = { count: 0, args: [] }; fxa.internal.currentAccountState.getUserAccountData = () => Promise.resolve({ deviceId: credentials.deviceId, deviceRegistrationVersion: 0 }); - fxa.internal._registerOrUpdateDevice = function() { + fxa.internal._registerOrUpdateDevice = function () { spy.count += 1; spy.args.push(arguments); return Promise.resolve("wibble"); @@ -467,7 +467,7 @@ add_task(function* test_getDeviceId_with_device_id_and_uptodate_registration_ver const spy = { count: 0 }; fxa.internal.currentAccountState.getUserAccountData = () => Promise.resolve({ deviceId: credentials.deviceId, deviceRegistrationVersion: DEVICE_REGISTRATION_VERSION }); - fxa.internal._registerOrUpdateDevice = function() { + fxa.internal._registerOrUpdateDevice = function () { spy.count += 1; return Promise.resolve("bar"); }; @@ -487,7 +487,7 @@ add_task(function* test_getDeviceId_with_device_id_and_with_no_registration_vers const spy = { count: 0, args: [] }; fxa.internal.currentAccountState.getUserAccountData = () => Promise.resolve({ deviceId: credentials.deviceId }); - fxa.internal._registerOrUpdateDevice = function() { + fxa.internal._registerOrUpdateDevice = function () { spy.count += 1; spy.args.push(arguments); return Promise.resolve("wibble"); @@ -506,11 +506,11 @@ function expandHex(two_hex) { let eight_hex = two_hex + two_hex + two_hex + two_hex; let thirtytwo_hex = eight_hex + eight_hex + eight_hex + eight_hex; return thirtytwo_hex + thirtytwo_hex; -} +}; function expandBytes(two_hex) { return CommonUtils.hexToBytes(expandHex(two_hex)); -} +}; function getTestUser(name) { return { diff --git a/services/fxaccounts/tests/xpcshell/test_client.js b/services/fxaccounts/tests/xpcshell/test_client.js index 0574a3b7be5f..83f42bdf5a08 100644 --- a/services/fxaccounts/tests/xpcshell/test_client.js +++ b/services/fxaccounts/tests/xpcshell/test_client.js @@ -17,20 +17,20 @@ function run_test() { // https://wiki.mozilla.org/Identity/AttachedServices/KeyServerProtocol#.2Faccount.2Fkeys var ACCOUNT_KEYS = { - keyFetch: h("8081828384858687 88898a8b8c8d8e8f" + + keyFetch: h("8081828384858687 88898a8b8c8d8e8f"+ "9091929394959697 98999a9b9c9d9e9f"), - response: h("ee5c58845c7c9412 b11bbd20920c2fdd" + - "d83c33c9cd2c2de2 d66b222613364636" + - "c2c0f8cfbb7c6304 72c0bd88451342c6" + - "c05b14ce342c5ad4 6ad89e84464c993c" + - "3927d30230157d08 17a077eef4b20d97" + + response: h("ee5c58845c7c9412 b11bbd20920c2fdd"+ + "d83c33c9cd2c2de2 d66b222613364636"+ + "c2c0f8cfbb7c6304 72c0bd88451342c6"+ + "c05b14ce342c5ad4 6ad89e84464c993c"+ + "3927d30230157d08 17a077eef4b20d97"+ "6f7a97363faf3f06 4c003ada7d01aa70"), - kA: h("2021222324252627 28292a2b2c2d2e2f" + + kA: h("2021222324252627 28292a2b2c2d2e2f"+ "3031323334353637 38393a3b3c3d3e3f"), - wrapKB: h("4041424344454647 48494a4b4c4d4e4f" + + wrapKB: h("4041424344454647 48494a4b4c4d4e4f"+ "5051525354555657 58595a5b5c5d5e5f"), }; @@ -238,7 +238,7 @@ add_task(function* test_signUp() { try { result = yield client.signUp(unicodeUsername, unicodePassword); do_throw("Expected to catch an exception"); - } catch (expectedError) { + } catch(expectedError) { do_check_eq(101, expectedError.errno); } @@ -279,26 +279,29 @@ add_task(function* test_signIn() { response.setStatusLine(request.httpVersion, 200, "OK"); response.bodyOutputStream.write(sessionMessage_noKey, sessionMessage_noKey.length); - - } else if (jsonBody.email == "you@example.com") { + return; + } + else if (jsonBody.email == "you@example.com") { do_check_eq("keys=true", request._queryString); do_check_eq(jsonBody.authPW, "93d20ec50304d496d0707ec20d7e8c89459b6396ec5dd5b9e92809c5e42856c7"); response.setStatusLine(request.httpVersion, 200, "OK"); response.bodyOutputStream.write(sessionMessage_withKey, sessionMessage_withKey.length); - - } else if (jsonBody.email == "You@example.com") { + return; + } + else if (jsonBody.email == "You@example.com") { // Error trying to sign in with a wrong capitalization response.setStatusLine(request.httpVersion, 400, "Bad request"); response.bodyOutputStream.write(errorMessage_wrongCap, errorMessage_wrongCap.length); - - } else { + return; + } + else { // Error trying to sign in to nonexistent account response.setStatusLine(request.httpVersion, 400, "Bad request"); response.bodyOutputStream.write(errorMessage_notExistent, errorMessage_notExistent.length); - + return; } }, }); @@ -354,7 +357,7 @@ add_task(function* test_signOut() { // Error trying to sign out of nonexistent account response.setStatusLine(request.httpVersion, 400, "Bad request"); response.bodyOutputStream.write(errorMessage, errorMessage.length); - + return; }, }); @@ -366,7 +369,7 @@ add_task(function* test_signOut() { try { result = yield client.signOut("FakeSession"); do_throw("Expected to catch an exception"); - } catch (expectedError) { + } catch(expectedError) { do_check_eq(102, expectedError.errno); } @@ -393,7 +396,7 @@ add_task(function* test_recoveryEmailStatus() { // Second call gets an error trying to query a nonexistent account response.setStatusLine(request.httpVersion, 400, "Bad request"); response.bodyOutputStream.write(errorMessage, errorMessage.length); - + return; }, }); @@ -405,7 +408,7 @@ add_task(function* test_recoveryEmailStatus() { try { result = yield client.recoveryEmailStatus("some bogus session"); do_throw("Expected to catch an exception"); - } catch (expectedError) { + } catch(expectedError) { do_check_eq(102, expectedError.errno); } @@ -422,7 +425,7 @@ add_task(function* test_recoveryEmailStatusWithReason() { response.setStatusLine(request.httpVersion, 200, "OK"); response.bodyOutputStream.write(emailStatus, emailStatus.length); - + return; }, }); @@ -452,7 +455,7 @@ add_task(function* test_resendVerificationEmail() { // Second call gets an error trying to query a nonexistent account response.setStatusLine(request.httpVersion, 400, "Bad request"); response.bodyOutputStream.write(errorMessage, errorMessage.length); - + return; }, }); @@ -464,7 +467,7 @@ add_task(function* test_resendVerificationEmail() { try { result = yield client.resendVerificationEmail("some bogus session"); do_throw("Expected to catch an exception"); - } catch (expectedError) { + } catch(expectedError) { do_check_eq(102, expectedError.errno); } @@ -486,7 +489,7 @@ add_task(function* test_accountKeys() { do_check_true(request.hasHeader("Authorization")); attempt += 1; - switch (attempt) { + switch(attempt) { case 1: // First time succeeds response.setStatusLine(request.httpVersion, 200, "OK"); @@ -529,7 +532,7 @@ add_task(function* test_accountKeys() { try { result = yield client.accountKeys(ACCOUNT_KEYS.keyFetch); do_throw("Expected to catch an exception"); - } catch (expectedError) { + } catch(expectedError) { do_check_eq(expectedError.message, "failed to retrieve keys"); } @@ -537,7 +540,7 @@ add_task(function* test_accountKeys() { try { result = yield client.accountKeys(ACCOUNT_KEYS.keyFetch); do_throw("Expected to catch an exception"); - } catch (expectedError) { + } catch(expectedError) { do_check_eq(expectedError.message, "error unbundling encryption keys"); } @@ -545,7 +548,7 @@ add_task(function* test_accountKeys() { try { result = yield client.accountKeys(ACCOUNT_KEYS.keyFetch); do_throw("Expected to catch an exception"); - } catch (expectedError) { + } catch(expectedError) { do_check_eq(102, expectedError.errno); } @@ -575,7 +578,7 @@ add_task(function* test_signCertificate() { // Second attempt, trigger error response.setStatusLine(request.httpVersion, 400, "Bad request"); response.bodyOutputStream.write(errorMessage, errorMessage.length); - + return; }, }); @@ -587,7 +590,7 @@ add_task(function* test_signCertificate() { try { result = yield client.signCertificate("bogus", JSON.stringify({foo: "bar"}), 600); do_throw("Expected to catch an exception"); - } catch (expectedError) { + } catch(expectedError) { do_check_eq(102, expectedError.errno); } @@ -648,7 +651,7 @@ add_task(function* test_accountExists() { try { result = yield client.accountExists("i.break.things@example.com"); do_throw("Expected to catch an exception"); - } catch (unexpectedError) { + } catch(unexpectedError) { do_check_eq(unexpectedError.code, 500); } @@ -699,7 +702,7 @@ add_task(function* test_registerDevice() { try { yield client.registerDevice(FAKE_SESSION_TOKEN, ERROR_NAME, DEVICE_TYPE); do_throw("Expected to catch an exception"); - } catch (unexpectedError) { + } catch(unexpectedError) { do_check_eq(unexpectedError.code, 500); } @@ -743,7 +746,7 @@ add_task(function* test_updateDevice() { try { yield client.updateDevice(FAKE_SESSION_TOKEN, ERROR_ID, DEVICE_NAME); do_throw("Expected to catch an exception"); - } catch (unexpectedError) { + } catch(unexpectedError) { do_check_eq(unexpectedError.code, 500); } @@ -782,7 +785,7 @@ add_task(function* test_signOutAndDestroyDevice() { try { yield client.signOutAndDestroyDevice(FAKE_SESSION_TOKEN, ERROR_ID); do_throw("Expected to catch an exception"); - } catch (unexpectedError) { + } catch(unexpectedError) { do_check_eq(unexpectedError.code, 500); } @@ -815,7 +818,7 @@ add_task(function* test_getDeviceList() { canReturnDevices = false; yield client.getDeviceList(FAKE_SESSION_TOKEN); do_throw("Expected to catch an exception"); - } catch (unexpectedError) { + } catch(unexpectedError) { do_check_eq(unexpectedError.code, 500); } diff --git a/services/fxaccounts/tests/xpcshell/test_oauth_grant_client.js b/services/fxaccounts/tests/xpcshell/test_oauth_grant_client.js index 86378c58c9d3..244b79a5eead 100644 --- a/services/fxaccounts/tests/xpcshell/test_oauth_grant_client.js +++ b/services/fxaccounts/tests/xpcshell/test_oauth_grant_client.js @@ -20,11 +20,11 @@ const STATUS_SUCCESS = 200; * Mocked raw response from the server * @returns {Function} */ -var mockResponse = function(response) { - return function() { +var mockResponse = function (response) { + return function () { return { - setHeader() {}, - post() { + setHeader: function () {}, + post: function () { this.response = response; this.onComplete(); } @@ -38,18 +38,18 @@ var mockResponse = function(response) { * Error object * @returns {Function} */ -var mockResponseError = function(error) { - return function() { +var mockResponseError = function (error) { + return function () { return { - setHeader() {}, - post() { + setHeader: function () {}, + post: function () { this.onComplete(error); } }; }; }; -add_test(function missingParams() { +add_test(function missingParams () { let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS); try { client.getTokenFromAssertion() @@ -66,7 +66,7 @@ add_test(function missingParams() { run_next_test(); }); -add_test(function successfulResponse() { +add_test(function successfulResponse () { let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS); let response = { success: true, @@ -77,14 +77,14 @@ add_test(function successfulResponse() { client._Request = new mockResponse(response); client.getTokenFromAssertion("assertion", "scope") .then( - function(result) { + function (result) { do_check_eq(result.access_token, "http://example.com/image.jpeg"); run_next_test(); } ); }); -add_test(function successfulDestroy() { +add_test(function successfulDestroy () { let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS); let response = { success: true, @@ -96,7 +96,7 @@ add_test(function successfulDestroy() { client.destroyToken("deadbeef").then(run_next_test); }); -add_test(function parseErrorResponse() { +add_test(function parseErrorResponse () { let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS); let response = { success: true, @@ -108,7 +108,7 @@ add_test(function parseErrorResponse() { client.getTokenFromAssertion("assertion", "scope") .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsOAuthGrantClientError"); do_check_eq(e.code, STATUS_SUCCESS); do_check_eq(e.errno, ERRNO_PARSE); @@ -119,7 +119,7 @@ add_test(function parseErrorResponse() { ); }); -add_test(function serverErrorResponse() { +add_test(function serverErrorResponse () { let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS); let response = { status: 400, @@ -130,7 +130,7 @@ add_test(function serverErrorResponse() { client.getTokenFromAssertion("blah", "scope") .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsOAuthGrantClientError"); do_check_eq(e.code, 400); do_check_eq(e.errno, ERRNO_INVALID_FXA_ASSERTION); @@ -141,7 +141,7 @@ add_test(function serverErrorResponse() { ); }); -add_test(function networkErrorResponse() { +add_test(function networkErrorResponse () { let client = new FxAccountsOAuthGrantClient({ serverURL: "http://", client_id: "abc123" @@ -150,7 +150,7 @@ add_test(function networkErrorResponse() { client.getTokenFromAssertion("assertion", "scope") .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsOAuthGrantClientError"); do_check_eq(e.code, null); do_check_eq(e.errno, ERRNO_NETWORK); @@ -161,13 +161,13 @@ add_test(function networkErrorResponse() { Services.prefs.clearUserPref("identity.fxaccounts.skipDeviceRegistration")); }); -add_test(function unsupportedMethod() { +add_test(function unsupportedMethod () { let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS); return client._createRequest("/", "PUT") .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsOAuthGrantClientError"); do_check_eq(e.code, ERROR_CODE_METHOD_NOT_ALLOWED); do_check_eq(e.errno, ERRNO_NETWORK); @@ -178,13 +178,13 @@ add_test(function unsupportedMethod() { ); }); -add_test(function onCompleteRequestError() { +add_test(function onCompleteRequestError () { let client = new FxAccountsOAuthGrantClient(CLIENT_OPTIONS); client._Request = new mockResponseError(new Error("onComplete error")); client.getTokenFromAssertion("assertion", "scope") .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsOAuthGrantClientError"); do_check_eq(e.code, null); do_check_eq(e.errno, ERRNO_NETWORK); @@ -206,7 +206,7 @@ add_test(function incorrectErrno() { client.getTokenFromAssertion("blah", "scope") .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsOAuthGrantClientError"); do_check_eq(e.code, 400); do_check_eq(e.errno, ERRNO_UNKNOWN_ERROR); diff --git a/services/fxaccounts/tests/xpcshell/test_oauth_grant_client_server.js b/services/fxaccounts/tests/xpcshell/test_oauth_grant_client_server.js index a6978d549657..bd446513e89e 100644 --- a/services/fxaccounts/tests/xpcshell/test_oauth_grant_client_server.js +++ b/services/fxaccounts/tests/xpcshell/test_oauth_grant_client_server.js @@ -50,7 +50,7 @@ function promiseStopServer(server) { }); } -add_task(function* getAndRevokeToken() { +add_task(function* getAndRevokeToken () { let server = startServer(); let clientOptions = { serverURL: "http://localhost:" + server.identity.primaryPort + "/v1", diff --git a/services/fxaccounts/tests/xpcshell/test_oauth_token_storage.js b/services/fxaccounts/tests/xpcshell/test_oauth_token_storage.js index 1224531f25d4..08642846b77e 100644 --- a/services/fxaccounts/tests/xpcshell/test_oauth_token_storage.js +++ b/services/fxaccounts/tests/xpcshell/test_oauth_token_storage.js @@ -82,7 +82,7 @@ MockFxAccountsClient.prototype = { __proto__: FxAccountsClient.prototype } -function MockFxAccounts(device = {}) { +function MockFxAccounts(device={}) { return new FxAccounts({ fxAccountsClient: new MockFxAccountsClient(), newAccountState(credentials) { diff --git a/services/fxaccounts/tests/xpcshell/test_oauth_tokens.js b/services/fxaccounts/tests/xpcshell/test_oauth_tokens.js index 59d79148761e..f758bf4050cd 100644 --- a/services/fxaccounts/tests/xpcshell/test_oauth_tokens.js +++ b/services/fxaccounts/tests/xpcshell/test_oauth_tokens.js @@ -89,7 +89,7 @@ function MockFxAccounts(mockGrantClient) { storage.initialize(credentials); return new AccountState(storage); }, - _destroyOAuthToken(tokenData) { + _destroyOAuthToken: function(tokenData) { // somewhat sad duplication of _destroyOAuthToken, but hard to avoid. return mockGrantClient.destroyToken(tokenData.token).then( () => { Services.obs.notifyObservers(null, "testhelper-fxa-revoke-complete", null); @@ -156,7 +156,7 @@ MockFxAccountsOAuthGrantClient.prototype = { add_task(function* testRevoke() { let client = new MockFxAccountsOAuthGrantClient(); - let tokenOptions = { scope: "test-scope", client }; + let tokenOptions = { scope: "test-scope", client: client }; let fxa = yield createMockFxA(client); // get our first token and check we hit the mock. @@ -186,13 +186,13 @@ add_task(function* testSignOutDestroysTokens() { let fxa = yield createMockFxA(client); // get our first token and check we hit the mock. - let token1 = yield fxa.getOAuthToken({ scope: "test-scope", client }); + let token1 = yield fxa.getOAuthToken({ scope: "test-scope", client: client }); equal(client.numTokenFetches, 1); equal(client.activeTokens.size, 1); ok(token1, "got a token"); // get another - let token2 = yield fxa.getOAuthToken({ scope: "test-scope-2", client }); + let token2 = yield fxa.getOAuthToken({ scope: "test-scope-2", client: client }); equal(client.numTokenFetches, 2); equal(client.activeTokens.size, 2); ok(token2, "got a token"); @@ -222,10 +222,10 @@ add_task(function* testTokenRaces() { promiseNotification("testhelper-fxa-revoke-complete"), ]); let results = yield Promise.all([ - fxa.getOAuthToken({scope: "test-scope", client}), - fxa.getOAuthToken({scope: "test-scope", client}), - fxa.getOAuthToken({scope: "test-scope-2", client}), - fxa.getOAuthToken({scope: "test-scope-2", client}), + fxa.getOAuthToken({scope: "test-scope", client: client}), + fxa.getOAuthToken({scope: "test-scope", client: client}), + fxa.getOAuthToken({scope: "test-scope-2", client: client}), + fxa.getOAuthToken({scope: "test-scope-2", client: client}), ]); equal(client.numTokenFetches, 4, "should have fetched 4 tokens."); diff --git a/services/fxaccounts/tests/xpcshell/test_profile.js b/services/fxaccounts/tests/xpcshell/test_profile.js index 179b13c450a8..13adf8cbb50c 100644 --- a/services/fxaccounts/tests/xpcshell/test_profile.js +++ b/services/fxaccounts/tests/xpcshell/test_profile.js @@ -19,13 +19,13 @@ const STATUS_SUCCESS = 200; * Mocked raw response from the server * @returns {Function} */ -var mockResponse = function(response) { - let Request = function(requestUri) { +var mockResponse = function (response) { + let Request = function (requestUri) { // Store the request uri so tests can inspect it Request._requestUri = requestUri; return { - setHeader() {}, - head() { + setHeader: function () {}, + head: function () { this.response = response; this.onComplete(); } @@ -41,21 +41,21 @@ var mockResponse = function(response) { * Error object * @returns {Function} */ -var mockResponseError = function(error) { - return function() { +var mockResponseError = function (error) { + return function () { return { - setHeader() {}, - head() { + setHeader: function () {}, + head: function () { this.onComplete(error); } }; }; }; -var mockClient = function(fxa) { +var mockClient = function (fxa) { let options = { serverURL: "http://127.0.0.1:1111/v1", - fxa, + fxa: fxa, } return new FxAccountsProfileClient(options); }; @@ -74,7 +74,7 @@ FxaMock.prototype = { } }, - getSignedInUser() { + getSignedInUser: function () { return Promise.resolve(ACCOUNT_DATA); } }; @@ -88,7 +88,7 @@ function CreateFxAccountsProfile(fxa = null, client = null) { fxa = mockFxa(); } let options = { - fxa, + fxa: fxa, profileServerUrl: "http://127.0.0.1:1111/v1" } if (client) { @@ -103,7 +103,7 @@ add_test(function getCachedProfile() { profile._cachedProfile = { avatar: "myurl" }; return profile._getCachedProfile() - .then(function(cached) { + .then(function (cached) { do_check_eq(cached.avatar, "myurl"); run_next_test(); }); @@ -121,7 +121,7 @@ add_test(function cacheProfile_change() { */ let profile = CreateFxAccountsProfile(fxa); - makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function(subject, topic, data) { + makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function (subject, topic, data) { do_check_eq(data, ACCOUNT_DATA.uid); // do_check_true(setUserAccountDataCalled); - bug 1157529 run_next_test(); @@ -136,7 +136,7 @@ add_test(function cacheProfile_no_change() { profile._cachedProfile = { avatar: "myurl" }; // XXX - saving is disabled (but we can leave that in for now as we are // just checking it is *not* called) - fxa.setSignedInUser = function(data) { + fxa.setSignedInUser = function (data) { throw new Error("should not update account data"); }; @@ -149,12 +149,12 @@ add_test(function cacheProfile_no_change() { add_test(function fetchAndCacheProfile_ok() { let client = mockClient(mockFxa()); - client.fetchProfile = function() { + client.fetchProfile = function () { return Promise.resolve({ avatar: "myimg"}); }; let profile = CreateFxAccountsProfile(null, client); - profile._cacheProfile = function(toCache) { + profile._cacheProfile = function (toCache) { do_check_eq(toCache.avatar, "myimg"); return Promise.resolve(); }; @@ -177,7 +177,7 @@ add_task(function* fetchAndCacheProfileOnce() { }); let numFetches = 0; let client = mockClient(mockFxa()); - client.fetchProfile = function() { + client.fetchProfile = function () { numFetches += 1; return promiseProfile; }; @@ -209,12 +209,12 @@ add_task(function* fetchAndCacheProfileOnce() { // A promise that remains unresolved while we fire off 2 requests for // a profile. let rejectProfile; - let promiseProfile = new Promise((resolve, reject) => { + let promiseProfile = new Promise((resolve,reject) => { rejectProfile = reject; }); let numFetches = 0; let client = mockClient(mockFxa()); - client.fetchProfile = function() { + client.fetchProfile = function () { numFetches += 1; return promiseProfile; }; @@ -249,7 +249,7 @@ add_task(function* fetchAndCacheProfileOnce() { } // but a new request should work. - client.fetchProfile = function() { + client.fetchProfile = function () { return Promise.resolve({ avatar: "myimg"}); }; @@ -262,7 +262,7 @@ add_task(function* fetchAndCacheProfileOnce() { add_task(function* fetchAndCacheProfileAfterThreshold() { let numFetches = 0; let client = mockClient(mockFxa()); - client.fetchProfile = function() { + client.fetchProfile = function () { numFetches += 1; return Promise.resolve({ avatar: "myimg"}); }; @@ -289,7 +289,7 @@ add_task(function* fetchAndCacheProfileAfterThreshold() { add_task(function* fetchAndCacheProfileBeforeThresholdOnNotification() { let numFetches = 0; let client = mockClient(mockFxa()); - client.fetchProfile = function() { + client.fetchProfile = function () { numFetches += 1; return Promise.resolve({ avatar: "myimg"}); }; @@ -323,11 +323,11 @@ add_test(function getProfile_ok() { let didFetch = false; let profile = CreateFxAccountsProfile(); - profile._getCachedProfile = function() { + profile._getCachedProfile = function () { return Promise.resolve({ avatar: cachedUrl }); }; - profile._fetchAndCacheProfile = function() { + profile._fetchAndCacheProfile = function () { didFetch = true; return Promise.resolve(); }; @@ -343,11 +343,11 @@ add_test(function getProfile_ok() { add_test(function getProfile_no_cache() { let fetchedUrl = "newUrl"; let profile = CreateFxAccountsProfile(); - profile._getCachedProfile = function() { + profile._getCachedProfile = function () { return Promise.resolve(); }; - profile._fetchAndCacheProfile = function() { + profile._fetchAndCacheProfile = function () { return Promise.resolve({ avatar: fetchedUrl }); }; @@ -363,7 +363,7 @@ add_test(function getProfile_has_cached_fetch_deleted() { let fxa = mockFxa(); let client = mockClient(fxa); - client.fetchProfile = function() { + client.fetchProfile = function () { return Promise.resolve({ avatar: null }); }; @@ -372,7 +372,7 @@ add_test(function getProfile_has_cached_fetch_deleted() { // instead of checking this in a mocked "save" function, just check after the // observer - makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function(subject, topic, data) { + makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function (subject, topic, data) { profile.getProfile() .then(profileData => { do_check_null(profileData.avatar); @@ -391,7 +391,7 @@ function run_test() { } function makeObserver(aObserveTopic, aObserveFunc) { - let callback = function(aSubject, aTopic, aData) { + let callback = function (aSubject, aTopic, aData) { log.debug("observed " + aTopic + " " + aData); if (aTopic == aObserveTopic) { removeMe(); diff --git a/services/fxaccounts/tests/xpcshell/test_profile_client.js b/services/fxaccounts/tests/xpcshell/test_profile_client.js index 1151ffd4e977..2243da3aab55 100644 --- a/services/fxaccounts/tests/xpcshell/test_profile_client.js +++ b/services/fxaccounts/tests/xpcshell/test_profile_client.js @@ -14,13 +14,13 @@ const STATUS_SUCCESS = 200; * Mocked raw response from the server * @returns {Function} */ -var mockResponse = function(response) { - let Request = function(requestUri) { +var mockResponse = function (response) { + let Request = function (requestUri) { // Store the request uri so tests can inspect it Request._requestUri = requestUri; return { - setHeader() {}, - get() { + setHeader: function () {}, + get: function () { this.response = response; this.onComplete(); } @@ -51,18 +51,18 @@ const PROFILE_OPTIONS = { * Error object * @returns {Function} */ -var mockResponseError = function(error) { - return function() { +var mockResponseError = function (error) { + return function () { return { - setHeader() {}, - get() { + setHeader: function () {}, + get: function () { this.onComplete(error); } }; }; }; -add_test(function successfulResponse() { +add_test(function successfulResponse () { let client = new FxAccountsProfileClient(PROFILE_OPTIONS); let response = { success: true, @@ -73,7 +73,7 @@ add_test(function successfulResponse() { client._Request = new mockResponse(response); client.fetchProfile() .then( - function(result) { + function (result) { do_check_eq(client._Request._requestUri, "http://127.0.0.1:1111/v1/profile"); do_check_eq(result.email, "someone@restmail.net"); do_check_eq(result.uid, "0d5c1a89b8c54580b8e3e8adadae864a"); @@ -82,7 +82,7 @@ add_test(function successfulResponse() { ); }); -add_test(function parseErrorResponse() { +add_test(function parseErrorResponse () { let client = new FxAccountsProfileClient(PROFILE_OPTIONS); let response = { success: true, @@ -94,7 +94,7 @@ add_test(function parseErrorResponse() { client.fetchProfile() .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsProfileClientError"); do_check_eq(e.code, STATUS_SUCCESS); do_check_eq(e.errno, ERRNO_PARSE); @@ -105,7 +105,7 @@ add_test(function parseErrorResponse() { ); }); -add_test(function serverErrorResponse() { +add_test(function serverErrorResponse () { let client = new FxAccountsProfileClient(PROFILE_OPTIONS); let response = { status: 500, @@ -116,7 +116,7 @@ add_test(function serverErrorResponse() { client.fetchProfile() .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsProfileClientError"); do_check_eq(e.code, 500); do_check_eq(e.errno, 100); @@ -129,7 +129,7 @@ add_test(function serverErrorResponse() { // Test that we get a token, then if we get a 401 we revoke it, get a new one // and retry. -add_test(function server401ResponseThenSuccess() { +add_test(function server401ResponseThenSuccess () { // The last token we handed out. let lastToken = -1; // The number of times our removeCachedOAuthToken function was called. @@ -171,13 +171,13 @@ add_test(function server401ResponseThenSuccess() { // Like mockResponse but we want access to headers etc. client._Request = function(requestUri) { return { - setHeader(name, value) { + setHeader: function (name, value) { if (name == "Authorization") { numAuthHeaders++; do_check_eq(value, "Bearer " + lastToken); } }, - get() { + get: function () { this.response = responses[numRequests]; ++numRequests; this.onComplete(); @@ -202,7 +202,7 @@ add_test(function server401ResponseThenSuccess() { // Test that we get a token, then if we get a 401 we revoke it, get a new one // and retry - but we *still* get a 401 on the retry, so the caller sees that. -add_test(function server401ResponsePersists() { +add_test(function server401ResponsePersists () { // The last token we handed out. let lastToken = -1; // The number of times our removeCachedOAuthToken function was called. @@ -235,13 +235,13 @@ add_test(function server401ResponsePersists() { let numAuthHeaders = 0; client._Request = function(requestUri) { return { - setHeader(name, value) { + setHeader: function (name, value) { if (name == "Authorization") { numAuthHeaders++; do_check_eq(value, "Bearer " + lastToken); } }, - get() { + get: function () { this.response = response; ++numRequests; this.onComplete(); @@ -251,7 +251,7 @@ add_test(function server401ResponsePersists() { client.fetchProfile().then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsProfileClientError"); do_check_eq(e.code, 401); do_check_eq(e.errno, 100); @@ -266,7 +266,7 @@ add_test(function server401ResponsePersists() { ); }); -add_test(function networkErrorResponse() { +add_test(function networkErrorResponse () { let client = new FxAccountsProfileClient({ serverURL: "http://", fxa: mockFxa, @@ -274,7 +274,7 @@ add_test(function networkErrorResponse() { client.fetchProfile() .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsProfileClientError"); do_check_eq(e.code, null); do_check_eq(e.errno, ERRNO_NETWORK); @@ -284,13 +284,13 @@ add_test(function networkErrorResponse() { ); }); -add_test(function unsupportedMethod() { +add_test(function unsupportedMethod () { let client = new FxAccountsProfileClient(PROFILE_OPTIONS); return client._createRequest("/profile", "PUT") .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsProfileClientError"); do_check_eq(e.code, ERROR_CODE_METHOD_NOT_ALLOWED); do_check_eq(e.errno, ERRNO_NETWORK); @@ -301,13 +301,13 @@ add_test(function unsupportedMethod() { ); }); -add_test(function onCompleteRequestError() { +add_test(function onCompleteRequestError () { let client = new FxAccountsProfileClient(PROFILE_OPTIONS); client._Request = new mockResponseError(new Error("onComplete error")); client.fetchProfile() .then( null, - function(e) { + function (e) { do_check_eq(e.name, "FxAccountsProfileClientError"); do_check_eq(e.code, null); do_check_eq(e.errno, ERRNO_NETWORK); @@ -318,7 +318,7 @@ add_test(function onCompleteRequestError() { ); }); -add_test(function fetchProfileImage_successfulResponse() { +add_test(function fetchProfileImage_successfulResponse () { let client = new FxAccountsProfileClient(PROFILE_OPTIONS); let response = { success: true, @@ -329,7 +329,7 @@ add_test(function fetchProfileImage_successfulResponse() { client._Request = new mockResponse(response); client.fetchProfileImage() .then( - function(result) { + function (result) { do_check_eq(client._Request._requestUri, "http://127.0.0.1:1111/v1/avatar"); do_check_eq(result.avatar, "http://example.com/image.jpg"); do_check_eq(result.id, "0d5c1a89b8c54580b8e3e8adadae864a"); diff --git a/services/fxaccounts/tests/xpcshell/test_push_service.js b/services/fxaccounts/tests/xpcshell/test_push_service.js index fd0349def90f..22c811ddf544 100644 --- a/services/fxaccounts/tests/xpcshell/test_push_service.js +++ b/services/fxaccounts/tests/xpcshell/test_push_service.js @@ -106,7 +106,7 @@ add_task(function* unsubscribeFailure() { add_test(function observeLogout() { let customLog = Object.assign(mockLog, { - trace(msg) { + trace: function (msg) { if (msg === "FxAccountsPushService unsubscribe") { // logout means we unsubscribe run_next_test(); @@ -124,12 +124,12 @@ add_test(function observeLogout() { add_test(function observePushTopicVerify() { let emptyMsg = { - QueryInterface() { + QueryInterface: function() { return this; } }; let customAccounts = Object.assign(mockFxAccounts, { - checkVerificationStatus() { + checkVerificationStatus: function () { // checking verification status on push messages without data run_next_test(); } @@ -153,7 +153,7 @@ add_test(function observePushTopicDeviceConnected() { } }) }, - QueryInterface() { + QueryInterface: function() { return this; } }; @@ -182,12 +182,12 @@ add_test(function observePushTopicDeviceDisconnected() { } }) }, - QueryInterface() { + QueryInterface: function() { return this; } }; let customAccounts = Object.assign(mockFxAccounts, { - handleDeviceDisconnection() { + handleDeviceDisconnection: function () { // checking verification status on push messages without data run_next_test(); } @@ -208,7 +208,7 @@ add_test(function observePushTopicPasswordChanged() { command: ON_PASSWORD_CHANGED_NOTIFICATION }) }, - QueryInterface() { + QueryInterface: function() { return this; } }; @@ -217,7 +217,7 @@ add_test(function observePushTopicPasswordChanged() { pushService: mockPushService, }); - pushService._onPasswordChanged = function() { + pushService._onPasswordChanged = function () { run_next_test(); } @@ -231,7 +231,7 @@ add_test(function observePushTopicPasswordReset() { command: ON_PASSWORD_RESET_NOTIFICATION }) }, - QueryInterface() { + QueryInterface: function() { return this; } }; @@ -240,7 +240,7 @@ add_test(function observePushTopicPasswordReset() { pushService: mockPushService }); - pushService._onPasswordChanged = function() { + pushService._onPasswordChanged = function () { run_next_test(); } @@ -249,7 +249,7 @@ add_test(function observePushTopicPasswordReset() { add_test(function observeSubscriptionChangeTopic() { let customAccounts = Object.assign(mockFxAccounts, { - updateDeviceRegistration() { + updateDeviceRegistration: function () { // subscription change means updating the device registration run_next_test(); } diff --git a/services/fxaccounts/tests/xpcshell/test_storage_manager.js b/services/fxaccounts/tests/xpcshell/test_storage_manager.js index 49ba6a76dfd4..6a293a0ff680 100644 --- a/services/fxaccounts/tests/xpcshell/test_storage_manager.js +++ b/services/fxaccounts/tests/xpcshell/test_storage_manager.js @@ -22,7 +22,7 @@ function MockedPlainStorage(accountData) { if (accountData) { data = { version: DATA_FORMAT_VERSION, - accountData, + accountData: accountData, } } this.data = data; @@ -45,7 +45,7 @@ function MockedSecureStorage(accountData) { if (accountData) { data = { version: DATA_FORMAT_VERSION, - accountData, + accountData: accountData, } } this.data = data; @@ -55,7 +55,7 @@ function MockedSecureStorage(accountData) { MockedSecureStorage.prototype = { fetchCount: 0, locked: false, - STORAGE_LOCKED() {}, + STORAGE_LOCKED: function() {}, get: Task.async(function* (uid, email) { this.fetchCount++; if (this.locked) { diff --git a/services/fxaccounts/tests/xpcshell/test_web_channel.js b/services/fxaccounts/tests/xpcshell/test_web_channel.js index faf55a8b65e2..ce139011874b 100644 --- a/services/fxaccounts/tests/xpcshell/test_web_channel.js +++ b/services/fxaccounts/tests/xpcshell/test_web_channel.js @@ -15,7 +15,7 @@ const mockSendingContext = { eventTarget: {} }; -add_test(function() { +add_test(function () { validationHelper(undefined, "Error: Missing configuration options"); @@ -118,7 +118,7 @@ add_test(function test_profile_image_change_message() { data: { uid: "foo" } }; - makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function(subject, topic, data) { + makeObserver(ON_PROFILE_CHANGE_NOTIFICATION, function (subject, topic, data) { do_check_eq(data, "foo"); run_next_test(); }); @@ -141,7 +141,7 @@ add_test(function test_login_message() { channel_id: WEBCHANNEL_ID, content_uri: URL_STRING, helpers: { - login(accountData) { + login: function (accountData) { do_check_eq(accountData.email, 'testuser@testuser.com'); run_next_test(); return Promise.resolve(); @@ -162,7 +162,7 @@ add_test(function test_logout_message() { channel_id: WEBCHANNEL_ID, content_uri: URL_STRING, helpers: { - logout(uid) { + logout: function (uid) { do_check_eq(uid, 'foo'); run_next_test(); return Promise.resolve(); @@ -183,7 +183,7 @@ add_test(function test_delete_message() { channel_id: WEBCHANNEL_ID, content_uri: URL_STRING, helpers: { - logout(uid) { + logout: function (uid) { do_check_eq(uid, 'foo'); run_next_test(); return Promise.resolve(); @@ -204,7 +204,7 @@ add_test(function test_can_link_account_message() { channel_id: WEBCHANNEL_ID, content_uri: URL_STRING, helpers: { - shouldAllowRelink(email) { + shouldAllowRelink: function (email) { do_check_eq(email, 'testuser@testuser.com'); run_next_test(); } @@ -224,7 +224,7 @@ add_test(function test_sync_preferences_message() { channel_id: WEBCHANNEL_ID, content_uri: URL_STRING, helpers: { - openSyncPreferences(browser, entryPoint) { + openSyncPreferences: function (browser, entryPoint) { do_check_eq(entryPoint, 'fxa:verification_complete'); do_check_eq(browser, mockSendingContext.browser); run_next_test(); @@ -279,7 +279,7 @@ add_test(function test_helpers_should_allow_relink_different_email() { add_task(function* test_helpers_login_without_customize_sync() { let helpers = new FxAccountsWebChannelHelpers({ fxAccounts: { - setSignedInUser(accountData) { + setSignedInUser: function(accountData) { return new Promise(resolve => { // ensure fxAccounts is informed of the new user being signed in. do_check_eq(accountData.email, 'testuser@testuser.com'); @@ -315,7 +315,7 @@ add_task(function* test_helpers_login_without_customize_sync() { add_task(function* test_helpers_login_with_customize_sync() { let helpers = new FxAccountsWebChannelHelpers({ fxAccounts: { - setSignedInUser(accountData) { + setSignedInUser: function(accountData) { return new Promise(resolve => { // ensure fxAccounts is informed of the new user being signed in. do_check_eq(accountData.email, 'testuser@testuser.com'); @@ -345,7 +345,7 @@ add_task(function* test_helpers_login_with_customize_sync() { add_task(function* test_helpers_login_with_customize_sync_and_declined_engines() { let helpers = new FxAccountsWebChannelHelpers({ fxAccounts: { - setSignedInUser(accountData) { + setSignedInUser: function(accountData) { return new Promise(resolve => { // ensure fxAccounts is informed of the new user being signed in. do_check_eq(accountData.email, 'testuser@testuser.com'); @@ -468,7 +468,7 @@ function run_test() { } function makeObserver(aObserveTopic, aObserveFunc) { - let callback = function(aSubject, aTopic, aData) { + let callback = function (aSubject, aTopic, aData) { log.debug("observed " + aTopic + " " + aData); if (aTopic == aObserveTopic) { removeMe(); diff --git a/services/sync/Weave.js b/services/sync/Weave.js index 568d00003ba0..4d79144e32ad 100644 --- a/services/sync/Weave.js +++ b/services/sync/Weave.js @@ -71,7 +71,7 @@ WeaveService.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakReference]), - ensureLoaded() { + ensureLoaded: function () { // If we are loaded and not using FxA, load the migration module. if (!this.fxAccountsEnabled) { Cu.import("resource://services-sync/FxaMigrator.jsm"); @@ -83,7 +83,7 @@ WeaveService.prototype = { Weave.Service; }, - whenLoaded() { + whenLoaded: function() { if (this.ready) { return Promise.resolve(); } @@ -127,7 +127,7 @@ WeaveService.prototype = { return prefs.prefHasUserValue("username"); }, - observe(subject, topic, data) { + observe: function (subject, topic, data) { switch (topic) { case "app-startup": let os = Cc["@mozilla.org/observer-service;1"]. @@ -172,11 +172,11 @@ AboutWeaveLog.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule, Ci.nsISupportsWeakReference]), - getURIFlags(aURI) { + getURIFlags: function(aURI) { return 0; }, - newChannel(aURI, aLoadInfo) { + newChannel: function(aURI, aLoadInfo) { let dir = FileUtils.getDir("ProfD", ["weave", "logs"], true); let uri = Services.io.newFileURI(dir); let channel = Services.io.newChannelFromURIWithLoadInfo(uri, aLoadInfo); diff --git a/services/sync/modules-testing/fakeservices.js b/services/sync/modules-testing/fakeservices.js index 8e8df342fbec..bff45519d11b 100644 --- a/services/sync/modules-testing/fakeservices.js +++ b/services/sync/modules-testing/fakeservices.js @@ -84,7 +84,7 @@ this.FakeGUIDService = function FakeGUIDService() { Utils.makeGUID = function makeGUID() { // ensure that this always returns a unique 12 character string let nextGUID = "fake-guid-" + String(latestGUID++).padStart(2, "0"); - return nextGUID.slice(nextGUID.length - 12, nextGUID.length); + return nextGUID.slice(nextGUID.length-12, nextGUID.length); }; } diff --git a/services/sync/modules-testing/fxa_utils.js b/services/sync/modules-testing/fxa_utils.js index 4daada8f0125..70aa17b03e27 100644 --- a/services/sync/modules-testing/fxa_utils.js +++ b/services/sync/modules-testing/fxa_utils.js @@ -1,58 +1,58 @@ -"use strict"; - -this.EXPORTED_SYMBOLS = [ - "initializeIdentityWithTokenServerResponse", -]; - -var {utils: Cu} = Components; - -Cu.import("resource://gre/modules/Log.jsm"); -Cu.import("resource://services-sync/main.js"); -Cu.import("resource://services-sync/browserid_identity.js"); -Cu.import("resource://services-common/tokenserverclient.js"); -Cu.import("resource://testing-common/services/common/logging.js"); -Cu.import("resource://testing-common/services/sync/utils.js"); - -// Create a new browserid_identity object and initialize it with a -// mocked TokenServerClient which always receives the specified response. -this.initializeIdentityWithTokenServerResponse = function(response) { - // First create a mock "request" object that well' hack into the token server. - // A log for it - let requestLog = Log.repository.getLogger("testing.mock-rest"); - if (!requestLog.appenders.length) { // might as well see what it says :) - requestLog.addAppender(new Log.DumpAppender()); - requestLog.level = Log.Level.Trace; - } - - // A mock request object. - function MockRESTRequest(url) {} - MockRESTRequest.prototype = { - _log: requestLog, - setHeader() {}, - get(callback) { - this.response = response; - callback.call(this); - } - } - // The mocked TokenServer client which will get the response. - function MockTSC() { } - MockTSC.prototype = new TokenServerClient(); - MockTSC.prototype.constructor = MockTSC; - MockTSC.prototype.newRESTRequest = function(url) { - return new MockRESTRequest(url); - } - // Arrange for the same observerPrefix as browserid_identity uses. - MockTSC.prototype.observerPrefix = "weave:service"; - - // tie it all together. - Weave.Status.__authManager = Weave.Service.identity = new BrowserIDManager(); - Weave.Service._clusterManager = Weave.Service.identity.createClusterManager(Weave.Service); - let browseridManager = Weave.Service.identity; - // a sanity check - if (!(browseridManager instanceof BrowserIDManager)) { - throw new Error("sync isn't configured for browserid_identity"); - } - let mockTSC = new MockTSC() - configureFxAccountIdentity(browseridManager); - browseridManager._tokenServerClient = mockTSC; -} +"use strict"; + +this.EXPORTED_SYMBOLS = [ + "initializeIdentityWithTokenServerResponse", +]; + +var {utils: Cu} = Components; + +Cu.import("resource://gre/modules/Log.jsm"); +Cu.import("resource://services-sync/main.js"); +Cu.import("resource://services-sync/browserid_identity.js"); +Cu.import("resource://services-common/tokenserverclient.js"); +Cu.import("resource://testing-common/services/common/logging.js"); +Cu.import("resource://testing-common/services/sync/utils.js"); + +// Create a new browserid_identity object and initialize it with a +// mocked TokenServerClient which always receives the specified response. +this.initializeIdentityWithTokenServerResponse = function(response) { + // First create a mock "request" object that well' hack into the token server. + // A log for it + let requestLog = Log.repository.getLogger("testing.mock-rest"); + if (!requestLog.appenders.length) { // might as well see what it says :) + requestLog.addAppender(new Log.DumpAppender()); + requestLog.level = Log.Level.Trace; + } + + // A mock request object. + function MockRESTRequest(url) {}; + MockRESTRequest.prototype = { + _log: requestLog, + setHeader: function() {}, + get: function(callback) { + this.response = response; + callback.call(this); + } + } + // The mocked TokenServer client which will get the response. + function MockTSC() { } + MockTSC.prototype = new TokenServerClient(); + MockTSC.prototype.constructor = MockTSC; + MockTSC.prototype.newRESTRequest = function(url) { + return new MockRESTRequest(url); + } + // Arrange for the same observerPrefix as browserid_identity uses. + MockTSC.prototype.observerPrefix = "weave:service"; + + // tie it all together. + Weave.Status.__authManager = Weave.Service.identity = new BrowserIDManager(); + Weave.Service._clusterManager = Weave.Service.identity.createClusterManager(Weave.Service); + let browseridManager = Weave.Service.identity; + // a sanity check + if (!(browseridManager instanceof BrowserIDManager)) { + throw new Error("sync isn't configured for browserid_identity"); + } + let mockTSC = new MockTSC() + configureFxAccountIdentity(browseridManager); + browseridManager._tokenServerClient = mockTSC; +} diff --git a/services/sync/modules-testing/utils.js b/services/sync/modules-testing/utils.js index 1669a2167622..fa575ce09544 100644 --- a/services/sync/modules-testing/utils.js +++ b/services/sync/modules-testing/utils.js @@ -238,7 +238,7 @@ this.configureFxAccountIdentity = function(authService, fxa.internal._fxAccountsClient = mockFxAClient; let mockTSC = { // TokenServerClient - getTokenFromBrowserIDAssertion(uri, assertion, cb) { + getTokenFromBrowserIDAssertion: function(uri, assertion, cb) { config.fxaccount.token.uid = config.username; cb(null, config.fxaccount.token); }, @@ -293,7 +293,7 @@ this.configureIdentity = async function(identityOverrides, server) { setBasicCredentials(config.username, config.sync.password, config.sync.syncKey); } -this.SyncTestingInfrastructure = async function(server, username, password) { +this.SyncTestingInfrastructure = async function (server, username, password) { let ns = {}; Cu.import("resource://services-sync/service.js", ns); diff --git a/services/sync/modules/SyncedTabs.jsm b/services/sync/modules/SyncedTabs.jsm index 8c8d461a7a3e..1a69e356440e 100644 --- a/services/sync/modules/SyncedTabs.jsm +++ b/services/sync/modules/SyncedTabs.jsm @@ -181,7 +181,7 @@ let SyncedTabsInternal = { } catch (ex) { log.error("Sync failed", ex); reject(ex); - } + }; }, Ci.nsIThread.DISPATCH_NORMAL); }); }, diff --git a/services/sync/modules/addonsreconciler.js b/services/sync/modules/addonsreconciler.js index 5d39155b4c6d..a60fc8d56667 100644 --- a/services/sync/modules/addonsreconciler.js +++ b/services/sync/modules/addonsreconciler.js @@ -252,7 +252,8 @@ AddonsReconciler.prototype = { for (let [k, v] of Object.entries(record)) { if (k == "modified") { state.addons[id][k] = v.getTime(); - } else { + } + else { state.addons[id][k] = v; } } @@ -347,7 +348,7 @@ AddonsReconciler.prototype = { let installs; - AddonManager.getAllAddons(function(addons) { + AddonManager.getAllAddons(function (addons) { let ids = {}; for (let addon of addons) { @@ -426,9 +427,9 @@ AddonsReconciler.prototype = { if (!(id in this._addons)) { let record = { - id, - guid, - enabled, + id: id, + guid: guid, + enabled: enabled, installed: true, modified: now, type: addon.type, @@ -633,7 +634,8 @@ AddonsReconciler.prototype = { this.saveState(null, cb); cb.wait(); } - } catch (ex) { + } + catch (ex) { this._log.warn("Exception", ex); } }, diff --git a/services/sync/modules/addonutils.js b/services/sync/modules/addonutils.js index a15ef86fed48..95da6be0a06f 100644 --- a/services/sync/modules/addonutils.js +++ b/services/sync/modules/addonutils.js @@ -114,7 +114,7 @@ AddonUtilsInternal.prototype = { } if (options.syncGUID) { - log.info("Setting syncGUID of " + install.name + ": " + + log.info("Setting syncGUID of " + install.name +": " + options.syncGUID); install.addon.syncGUID = options.syncGUID; } @@ -127,17 +127,17 @@ AddonUtilsInternal.prototype = { install.addon.userDisabled = true; } }, - onInstallEnded(install, addon) { + onInstallEnded: function(install, addon) { install.removeListener(listener); - cb(null, {id: addon.id, install, addon}); + cb(null, {id: addon.id, install: install, addon: addon}); }, - onInstallFailed(install) { + onInstallFailed: function(install) { install.removeListener(listener); cb(new Error("Install failed: " + install.error), null); }, - onDownloadFailed(install) { + onDownloadFailed: function(install) { install.removeListener(listener); cb(new Error("Download failed: " + install.error), null); @@ -145,7 +145,8 @@ AddonUtilsInternal.prototype = { }; install.addListener(listener); install.install(); - } catch (ex) { + } + catch (ex) { this._log.error("Error installing add-on", ex); cb(ex, null); } @@ -163,7 +164,7 @@ AddonUtilsInternal.prototype = { */ uninstallAddon: function uninstallAddon(addon, cb) { let listener = { - onUninstalling(uninstalling, needsRestart) { + onUninstalling: function(uninstalling, needsRestart) { if (addon.id != uninstalling.id) { return; } @@ -179,7 +180,7 @@ AddonUtilsInternal.prototype = { AddonManager.removeAddonListener(listener); cb(null, addon); }, - onUninstalled(uninstalled) { + onUninstalled: function(uninstalled) { if (addon.id != uninstalled.id) { return; } @@ -272,7 +273,7 @@ AddonUtilsInternal.prototype = { cb(null, ourResult); } } - }; + }.bind(this); let toInstall = []; @@ -493,7 +494,7 @@ AddonUtilsInternal.prototype = { if (!addon.appDisabled) { cb(null, addon); - + return; } // Else the listener will handle invoking the callback. }, diff --git a/services/sync/modules/bookmark_validator.js b/services/sync/modules/bookmark_validator.js index eeb849648e5a..2a94ba043a02 100644 --- a/services/sync/modules/bookmark_validator.js +++ b/services/sync/modules/bookmark_validator.js @@ -337,10 +337,12 @@ class BookmarkValidator { } if (record.deleted) { deletedItemIds.add(record.id); - } else if (idToRecord.has(record.id)) { + } else { + if (idToRecord.has(record.id)) { problemData.duplicates.push(record.id); continue; } + } idToRecord.set(record.id, record); if (record.children) { @@ -766,7 +768,7 @@ class BookmarkValidator { let serverRecordCount = serverState.length; let result = self.compareServerWithClient(serverState, clientTree); let end = Date.now(); - let duration = end - start; + let duration = end-start; return { duration, version: self.version, @@ -776,7 +778,7 @@ class BookmarkValidator { }); } -} +}; BookmarkValidator.prototype.version = BOOKMARK_VALIDATOR_VERSION; diff --git a/services/sync/modules/browserid_identity.js b/services/sync/modules/browserid_identity.js index d95d6224e468..c6b4fca306ff 100644 --- a/services/sync/modules/browserid_identity.js +++ b/services/sync/modules/browserid_identity.js @@ -52,7 +52,7 @@ const PREF_SYNC_SHOW_CUSTOMIZATION = "services.sync-setup.ui.showCustomizationDi function deriveKeyBundle(kB) { let out = CryptoUtils.hkdf(kB, undefined, - "identity.mozilla.com/picl/v1/oldsync", 2 * 32); + "identity.mozilla.com/picl/v1/oldsync", 2*32); let bundle = new BulkKeyBundle(); // [encryptionKey, hmacKey] bundle.keyPair = [out.slice(0, 32), out.slice(32, 64)]; @@ -72,7 +72,7 @@ function AuthenticationError(details, source) { } AuthenticationError.prototype = { - toString() { + toString: function() { return "AuthenticationError(" + this.details + ")"; } } @@ -134,7 +134,7 @@ this.BrowserIDManager.prototype = { return this._signedInUser && this._signedInUser.deviceId; }, - initialize() { + initialize: function() { for (let topic of OBSERVER_TOPICS) { Services.obs.addObserver(this, topic, false); } @@ -157,7 +157,7 @@ this.BrowserIDManager.prototype = { * Ensure the user is logged in. Returns a promise that resolves when * the user is logged in, or is rejected if the login attempt has failed. */ - ensureLoggedIn() { + ensureLoggedIn: function() { if (!this._shouldHaveSyncKeyBundle && this.whenReadyToAuthenticate) { // We are already in the process of logging in. return this.whenReadyToAuthenticate.promise; @@ -181,7 +181,7 @@ this.BrowserIDManager.prototype = { return this.whenReadyToAuthenticate.promise; }, - finalize() { + finalize: function() { // After this is called, we can expect Service.identity != this. for (let topic of OBSERVER_TOPICS) { Services.obs.removeObserver(this, topic); @@ -190,7 +190,7 @@ this.BrowserIDManager.prototype = { this._signedInUser = null; }, - offerSyncOptions() { + offerSyncOptions: function () { // If the user chose to "Customize sync options" when signing // up with Firefox Accounts, ask them to choose what to sync. const url = "chrome://browser/content/sync/customize.xul"; @@ -203,7 +203,7 @@ this.BrowserIDManager.prototype = { return data; }, - initializeWithCurrentIdentity(isInitialSync = false) { + initializeWithCurrentIdentity: function(isInitialSync=false) { // While this function returns a promise that resolves once we've started // the auth process, that process is complete when // this.whenReadyToAuthenticate.promise resolves. @@ -284,7 +284,7 @@ this.BrowserIDManager.prototype = { }); }, - _updateSignedInUser(userData) { + _updateSignedInUser: function(userData) { // This object should only ever be used for a single user. It is an // error to update the data if the user changes (but updates are still // necessary, as each call may add more attributes to the user). @@ -295,7 +295,7 @@ this.BrowserIDManager.prototype = { this._signedInUser = userData; }, - logout() { + logout: function() { // This will be called when sync fails (or when the account is being // unlinked etc). It may have failed because we got a 401 from a sync // server, so we nuke the token. Next time sync runs and wants an @@ -304,7 +304,7 @@ this.BrowserIDManager.prototype = { this._token = null; }, - observe(subject, topic, data) { + observe: function (subject, topic, data) { this._log.debug("observed " + topic); switch (topic) { case fxAccountsCommon.ONLOGIN_NOTIFICATION: @@ -338,7 +338,7 @@ this.BrowserIDManager.prototype = { /** * Compute the sha256 of the message bytes. Return bytes. */ - _sha256(message) { + _sha256: function(message) { let hasher = Cc["@mozilla.org/security/hash;1"] .createInstance(Ci.nsICryptoHash); hasher.init(hasher.SHA256); @@ -350,14 +350,14 @@ this.BrowserIDManager.prototype = { * * Return string: hex(first16Bytes(sha256(kBbytes))) */ - _computeXClientState(kBbytes) { + _computeXClientState: function(kBbytes) { return CommonUtils.bytesAsHex(this._sha256(kBbytes).slice(0, 16), false); }, /** * Provide override point for testing token expiration. */ - _now() { + _now: function() { return this._fxaService.now() }, @@ -365,7 +365,7 @@ this.BrowserIDManager.prototype = { return this._fxaService.localtimeOffsetMsec; }, - usernameFromAccount(val) { + usernameFromAccount: function(val) { // we don't differentiate between "username" and "account" return val; }, @@ -407,7 +407,8 @@ this.BrowserIDManager.prototype = { // field directly and instead call a isSyncKeyValid() function // that we can override. return "99999999999999999999999999"; - } else { + } + else { return null; } }, @@ -423,7 +424,7 @@ this.BrowserIDManager.prototype = { /** * Resets/Drops all credentials we hold for the current user. */ - resetCredentials() { + resetCredentials: function() { this.resetSyncKey(); this._token = null; this._hashedUID = null; @@ -435,7 +436,7 @@ this.BrowserIDManager.prototype = { /** * Resets/Drops the sync key we hold for the current user. */ - resetSyncKey() { + resetSyncKey: function() { this._syncKey = null; this._syncKeyBundle = null; this._syncKeyUpdated = true; @@ -448,14 +449,14 @@ this.BrowserIDManager.prototype = { * allows us to avoid a network request for when we actually need the * migration info. */ - prefetchMigrationSentinel(service) { + prefetchMigrationSentinel: function(service) { // nothing to do here until we decide to migrate away from FxA. }, /** * Return credentials hosts for this identity only. */ - _getSyncCredentialsHosts() { + _getSyncCredentialsHosts: function() { return Utils.getSyncCredentialsHostsFxA(); }, @@ -485,7 +486,7 @@ this.BrowserIDManager.prototype = { // Do we currently have keys, or do we have enough that we should be able // to successfully fetch them? - _canFetchKeys() { + _canFetchKeys: function() { let userData = this._signedInUser; // a keyFetchToken means we can almost certainly grab them. // kA and kB means we already have them. @@ -498,7 +499,7 @@ this.BrowserIDManager.prototype = { * Returns a promise that resolves with the current auth state after * attempting to unlock. */ - unlockAndVerifyAuthState() { + unlockAndVerifyAuthState: function() { if (this._canFetchKeys()) { log.debug("unlockAndVerifyAuthState already has (or can fetch) sync keys"); return Promise.resolve(STATUS_OK); @@ -533,13 +534,13 @@ this.BrowserIDManager.prototype = { * Do we have a non-null, not yet expired token for the user currently * signed in? */ - hasValidToken() { + hasValidToken: function() { // If pref is set to ignore cached authentication credentials for debugging, // then return false to force the fetching of a new token. let ignoreCachedAuthCredentials = false; try { ignoreCachedAuthCredentials = Svc.Prefs.get("debug.ignoreCachedAuthCredentials"); - } catch (e) { + } catch(e) { // Pref doesn't exist } if (ignoreCachedAuthCredentials) { @@ -572,7 +573,7 @@ this.BrowserIDManager.prototype = { // Refresh the sync token for our user. Returns a promise that resolves // with a token (which may be null in one sad edge-case), or rejects with an // error. - _fetchTokenForUser() { + _fetchTokenForUser: function() { // tokenServerURI is mis-named - convention is uri means nsISomething... let tokenServerURI = this._tokenServerUrl; let log = this._log; @@ -606,7 +607,7 @@ this.BrowserIDManager.prototype = { let getToken = assertion => { log.debug("Getting a token"); let deferred = Promise.defer(); - let cb = function(err, token) { + let cb = function (err, token) { if (err) { return deferred.reject(err); } @@ -693,7 +694,7 @@ this.BrowserIDManager.prototype = { // Returns a promise that is resolved when we have a valid token for the // current user stored in this._token. When resolved, this._token is valid. - _ensureValidToken() { + _ensureValidToken: function() { if (this.hasValidToken()) { this._log.debug("_ensureValidToken already has one"); return Promise.resolve(); @@ -722,14 +723,14 @@ this.BrowserIDManager.prototype = { ); }, - getResourceAuthenticator() { + getResourceAuthenticator: function () { return this._getAuthenticationHeader.bind(this); }, /** * Obtain a function to be used for adding auth to RESTRequest instances. */ - getRESTRequestAuthenticator() { + getRESTRequestAuthenticator: function() { return this._addAuthenticationHeader.bind(this); }, @@ -737,7 +738,7 @@ this.BrowserIDManager.prototype = { * @return a Hawk HTTP Authorization Header, lightly wrapped, for the .uri * of a RESTRequest or AsyncResponse object. */ - _getAuthenticationHeader(httpObject, method) { + _getAuthenticationHeader: function(httpObject, method) { let cb = Async.makeSpinningCallback(); this._ensureValidToken().then(cb, cb); // Note that in failure states we return null, causing the request to be @@ -767,14 +768,14 @@ this.BrowserIDManager.prototype = { let options = { now: this._now(), localtimeOffsetMsec: this._localtimeOffsetMsec, - credentials, + credentials: credentials, }; let headerValue = CryptoUtils.computeHAWK(httpObject.uri, method, options); return {headers: {authorization: headerValue.field}}; }, - _addAuthenticationHeader(request, method) { + _addAuthenticationHeader: function(request, method) { let header = this._getAuthenticationHeader(request, method); if (!header) { return null; @@ -783,7 +784,7 @@ this.BrowserIDManager.prototype = { return request; }, - createClusterManager(service) { + createClusterManager: function(service) { return new BrowserIDClusterManager(service); }, @@ -808,7 +809,7 @@ function BrowserIDClusterManager(service) { BrowserIDClusterManager.prototype = { __proto__: ClusterManager.prototype, - _findCluster() { + _findCluster: function() { let endPointFromIdentityToken = function() { // The only reason (in theory ;) that we can end up with a null token // is when this.identity._canFetchKeys() returned false. In turn, this @@ -851,7 +852,7 @@ BrowserIDClusterManager.prototype = { }.bind(this); let cb = Async.makeSpinningCallback(); - promiseClusterURL().then(function(clusterURL) { + promiseClusterURL().then(function (clusterURL) { cb(null, clusterURL); }).then( null, err => { @@ -879,7 +880,7 @@ BrowserIDClusterManager.prototype = { return cb.wait(); }, - getUserBaseURL() { + getUserBaseURL: function() { // Legacy Sync and FxA Sync construct the userBaseURL differently. Legacy // Sync appends path components onto an empty path, and in FxA Sync the // token server constructs this for us in an opaque manner. Since the diff --git a/services/sync/modules/collection_validator.js b/services/sync/modules/collection_validator.js index d8daa6ed0d29..41141bba30ad 100644 --- a/services/sync/modules/collection_validator.js +++ b/services/sync/modules/collection_validator.js @@ -163,7 +163,7 @@ class CollectionValidator { if (combined) { combined.client = record; } else { - allRecords.set(id, { client: record, server: null }); + allRecords.set(id, { client: record, server: null }); } } diff --git a/services/sync/modules/engines.js b/services/sync/modules/engines.js index e97645836e68..8d49cd2b0445 100644 --- a/services/sync/modules/engines.js +++ b/services/sync/modules/engines.js @@ -105,7 +105,7 @@ Tracker.prototype = { }, // Should be called by service everytime a sync has been done for an engine - resetScore() { + resetScore: function () { this._score = 0; }, @@ -123,12 +123,12 @@ Tracker.prototype = { // being processed, or that shouldn't be synced. // But note: not persisted to disk - ignoreID(id) { + ignoreID: function (id) { this.unignoreID(id); this._ignored.push(id); }, - unignoreID(id) { + unignoreID: function (id) { let index = this._ignored.indexOf(id); if (index != -1) this._ignored.splice(index, 1); @@ -140,7 +140,7 @@ Tracker.prototype = { this._saveChangedIDs(); }, - addChangedID(id, when) { + addChangedID: function (id, when) { if (!id) { this._log.warn("Attempted to add undefined ID to tracker"); return false; @@ -163,7 +163,7 @@ Tracker.prototype = { return true; }, - removeChangedID(...ids) { + removeChangedID: function (...ids) { if (!ids.length || this.ignoreAll) { return false; } @@ -185,7 +185,7 @@ Tracker.prototype = { return true; }, - clearChangedIDs() { + clearChangedIDs: function () { this._log.trace("Clearing changed ID list"); this._storage.data = {}; this._saveChangedIDs(); @@ -198,13 +198,13 @@ Tracker.prototype = { _isTracking: false, // Override these in your subclasses. - startTracking() { + startTracking: function () { }, - stopTracking() { + stopTracking: function () { }, - engineIsEnabled() { + engineIsEnabled: function () { if (!this.engine) { // Can't tell -- we must be running in a test! return true; @@ -212,7 +212,7 @@ Tracker.prototype = { return this.engine.enabled; }, - onEngineEnabledChanged(engineEnabled) { + onEngineEnabledChanged: function (engineEnabled) { if (engineEnabled == this._isTracking) { return; } @@ -227,7 +227,7 @@ Tracker.prototype = { } }, - observe(subject, topic, data) { + observe: function (subject, topic, data) { switch (topic) { case "weave:engine:start-tracking": if (!this.engineIsEnabled()) { @@ -250,7 +250,7 @@ Tracker.prototype = { if (data == PREFS_BRANCH + "engine." + this.engine.prefName) { this.onEngineEnabledChanged(this.engine.enabled); } - + return; } } }; @@ -317,7 +317,7 @@ Store.prototype = { * @param records Array of records to apply * @return Array of record IDs which did not apply cleanly */ - applyIncomingBatch(records) { + applyIncomingBatch: function (records) { let failed = []; for (let record of records) { try { @@ -336,7 +336,7 @@ Store.prototype = { this.engine._noteApplyFailure(); failed.push(record.id); } - } + }; return failed; }, @@ -353,7 +353,7 @@ Store.prototype = { * @param record * Record to apply */ - applyIncoming(record) { + applyIncoming: function (record) { if (record.deleted) this.remove(record); else if (!this.itemExists(record.id)) @@ -373,7 +373,7 @@ Store.prototype = { * @param record * The store record to create an item from */ - create(record) { + create: function (record) { throw "override create in a subclass"; }, @@ -386,7 +386,7 @@ Store.prototype = { * @param record * The store record to delete an item from */ - remove(record) { + remove: function (record) { throw "override remove in a subclass"; }, @@ -399,7 +399,7 @@ Store.prototype = { * @param record * The record to use to update an item from */ - update(record) { + update: function (record) { throw "override update in a subclass"; }, @@ -413,7 +413,7 @@ Store.prototype = { * string record ID * @return boolean indicating whether record exists locally */ - itemExists(id) { + itemExists: function (id) { throw "override itemExists in a subclass"; }, @@ -431,7 +431,7 @@ Store.prototype = { * constructor for the newly-created record. * @return record type for this engine */ - createRecord(id, collection) { + createRecord: function (id, collection) { throw "override createRecord in a subclass"; }, @@ -443,7 +443,7 @@ Store.prototype = { * @param newID * string new record ID */ - changeItemID(oldID, newID) { + changeItemID: function (oldID, newID) { throw "override changeItemID in a subclass"; }, @@ -453,7 +453,7 @@ Store.prototype = { * @return Object with ID strings as keys and values of true. The values * are ignored. */ - getAllIDs() { + getAllIDs: function () { throw "override getAllIDs in a subclass"; }, @@ -467,7 +467,7 @@ Store.prototype = { * can be thought of as clearing out all state and restoring the "new * browser" state. */ - wipe() { + wipe: function () { throw "override wipe in a subclass"; } }; @@ -483,7 +483,7 @@ this.EngineManager = function EngineManager(service) { this._log.level = Log.Level[Svc.Prefs.get("log.logger.service.engines", "Debug")]; } EngineManager.prototype = { - get(name) { + get: function (name) { // Return an array of engines if we have an array of names if (Array.isArray(name)) { let engines = []; @@ -506,7 +506,7 @@ EngineManager.prototype = { return engine; }, - getAll() { + getAll: function () { let engines = []; for (let [, engine] of Object.entries(this._engines)) { engines.push(engine); @@ -517,7 +517,7 @@ EngineManager.prototype = { /** * N.B., does not pay attention to the declined list. */ - getEnabled() { + getEnabled: function () { return this.getAll() .filter((engine) => engine.enabled) .sort((a, b) => a.syncPriority - b.syncPriority); @@ -527,37 +527,37 @@ EngineManager.prototype = { return this.getEnabled().map(e => e.name); }, - persistDeclined() { + persistDeclined: function () { Svc.Prefs.set("declinedEngines", [...this._declined].join(",")); }, /** * Returns an array. */ - getDeclined() { + getDeclined: function () { return [...this._declined]; }, - setDeclined(engines) { + setDeclined: function (engines) { this._declined = new Set(engines); this.persistDeclined(); }, - isDeclined(engineName) { + isDeclined: function (engineName) { return this._declined.has(engineName); }, /** * Accepts a Set or an array. */ - decline(engines) { + decline: function (engines) { for (let e of engines) { this._declined.add(e); } this.persistDeclined(); }, - undecline(engines) { + undecline: function (engines) { for (let e of engines) { this._declined.delete(e); } @@ -569,7 +569,7 @@ EngineManager.prototype = { * * This is useful after initial customization during setup. */ - declineDisabled() { + declineDisabled: function () { for (let e of this.getAll()) { if (!e.enabled) { this._log.debug("Declining disabled engine " + e.name); @@ -587,7 +587,7 @@ EngineManager.prototype = { * Engine object used to get an instance of the engine * @return The engine object if anything failed */ - register(engineObject) { + register: function (engineObject) { if (Array.isArray(engineObject)) { return engineObject.map(this.register, this); } @@ -610,7 +610,7 @@ EngineManager.prototype = { } }, - unregister(val) { + unregister: function (val) { let name = val; if (val instanceof Engine) { name = val.name; @@ -618,7 +618,7 @@ EngineManager.prototype = { delete this._engines[name]; }, - clear() { + clear: function () { for (let name in this._engines) { delete this._engines[name]; } @@ -685,7 +685,7 @@ Engine.prototype = { return tracker; }, - sync() { + sync: function () { if (!this.enabled) { return; } @@ -700,7 +700,7 @@ Engine.prototype = { /** * Get rid of any local meta-data. */ - resetClient() { + resetClient: function () { if (!this._resetClient) { throw "engine does not implement _resetClient method"; } @@ -708,7 +708,7 @@ Engine.prototype = { this._notify("reset-client", this.name, this._resetClient)(); }, - _wipeClient() { + _wipeClient: function () { this.resetClient(); this._log.debug("Deleting all local data"); this._tracker.ignoreAll = true; @@ -717,7 +717,7 @@ Engine.prototype = { this._tracker.clearChangedIDs(); }, - wipeClient() { + wipeClient: function () { this._notify("wipe-client", this.name, this._wipeClient)(); }, @@ -726,7 +726,7 @@ Engine.prototype = { * must have a `validate(engine)` method that returns a promise to an object * with a getSummary method). Otherwise return null. */ - getValidator() { + getValidator: function () { return null; } }; @@ -810,7 +810,7 @@ SyncEngine.prototype = { // Store the value as a string to keep floating point precision Svc.Prefs.set(this.name + ".lastSync", value.toString()); }, - resetLastSync() { + resetLastSync: function () { this._log.debug("Resetting " + this.name + " last sync time"); Svc.Prefs.reset(this.name + ".lastSync"); Svc.Prefs.set(this.name + ".lastSync", "0"); @@ -831,12 +831,12 @@ SyncEngine.prototype = { return; } this._toFetch = val; - Utils.namedTimer(function() { + Utils.namedTimer(function () { Utils.jsonSave("toFetch/" + this.name, this, val, cb); }, 0, this, "_toFetchDelay"); }, - loadToFetch() { + loadToFetch: function () { // Initialize to empty if there's no file. this._toFetch = []; Utils.jsonLoad("toFetch/" + this.name, this, function(toFetch) { @@ -862,12 +862,12 @@ SyncEngine.prototype = { return; } this._previousFailed = val; - Utils.namedTimer(function() { + Utils.namedTimer(function () { Utils.jsonSave("failed/" + this.name, this, val, cb); }, 0, this, "_previousFailedDelay"); }, - loadPreviousFailed() { + loadPreviousFailed: function () { // Initialize to empty if there's no file this._previousFailed = []; Utils.jsonLoad("failed/" + this.name, this, function(previousFailed) { @@ -892,12 +892,12 @@ SyncEngine.prototype = { * Returns a changeset for this sync. Engine implementations can override this * method to bypass the tracker for certain or all changed items. */ - getChangedIDs() { + getChangedIDs: function () { return this._tracker.changedIDs; }, // Create a new record using the store and add in crypto fields. - _createRecord(id) { + _createRecord: function (id) { let record = this._store.createRecord(id, this.name); record.id = id; record.collection = this.name; @@ -905,7 +905,7 @@ SyncEngine.prototype = { }, // Any setup that needs to happen at the beginning of each sync. - _syncStartup() { + _syncStartup: function () { // Determine if we need to wipe on outdated versions let metaGlobal = this.service.recordManager.get(this.metaURL); @@ -942,7 +942,7 @@ SyncEngine.prototype = { this._log.debug("Engine syncIDs: " + [engineData.syncID, this.syncID]); this.syncID = engineData.syncID; this._resetClient(); - } + }; // Delete any existing data and reupload on bad version or missing meta. // No crypto component here...? We could regenerate per-collection keys... @@ -978,7 +978,7 @@ SyncEngine.prototype = { * A tiny abstraction to make it easier to test incoming record * application. */ - itemSource() { + itemSource: function () { return new Collection(this.engineURL, this._recordObj, this.service); }, @@ -987,7 +987,7 @@ SyncEngine.prototype = { * In the most awful and untestable way possible. * This now accepts something that makes testing vaguely less impossible. */ - _processIncoming(newitems) { + _processIncoming: function (newitems) { this._log.trace("Downloading & applying server changes"); // Figure out how many total items to fetch this sync; do less on mobile. @@ -1281,11 +1281,11 @@ SyncEngine.prototype = { return false; }, - _noteApplyFailure() { + _noteApplyFailure: function () { // here would be a good place to record telemetry... }, - _noteApplyNewFailure() { + _noteApplyNewFailure: function () { // here would be a good place to record telemetry... }, @@ -1295,7 +1295,7 @@ SyncEngine.prototype = { * * @return GUID of the similar item; falsy otherwise */ - _findDupe(item) { + _findDupe: function (item) { // By default, assume there's no dupe items for the engine }, @@ -1309,7 +1309,7 @@ SyncEngine.prototype = { return true; }, - _deleteId(id) { + _deleteId: function (id) { this._tracker.removeChangedID(id); this._noteDeletedId(id); }, @@ -1344,7 +1344,7 @@ SyncEngine.prototype = { * @return boolean * Truthy if incoming record should be applied. False if not. */ - _reconcile(item) { + _reconcile: function (item) { if (this._log.level <= Log.Level.Trace) { this._log.trace("Incoming: " + item); } @@ -1512,7 +1512,7 @@ SyncEngine.prototype = { }, // Upload outgoing records. - _uploadOutgoing() { + _uploadOutgoing: function () { this._log.trace("Uploading local changes to server."); let modifiedIDs = this._modified.ids(); @@ -1612,7 +1612,7 @@ SyncEngine.prototype = { // Any cleanup necessary. // Save the current snapshot so as to calculate changes at next sync - _syncFinish() { + _syncFinish: function () { this._log.trace("Finishing up sync"); this._tracker.resetScore(); @@ -1639,7 +1639,7 @@ SyncEngine.prototype = { } }, - _syncCleanup() { + _syncCleanup: function () { if (!this._modified) { return; } @@ -1652,7 +1652,7 @@ SyncEngine.prototype = { } }, - _sync() { + _sync: function () { try { this._syncStartup(); Observers.notify("weave:engine:sync:status", "process-incoming"); @@ -1665,7 +1665,7 @@ SyncEngine.prototype = { } }, - canDecrypt() { + canDecrypt: function () { // Report failure even if there's nothing to decrypt let canDecrypt = false; @@ -1679,7 +1679,7 @@ SyncEngine.prototype = { test.recordHandler = function recordHandler(record) { record.decrypt(key); canDecrypt = true; - }; + }.bind(this); // Any failure fetching/decrypting will just result in false try { @@ -1695,13 +1695,13 @@ SyncEngine.prototype = { return canDecrypt; }, - _resetClient() { + _resetClient: function () { this.resetLastSync(); this.previousFailed = []; this.toFetch = []; }, - wipeServer() { + wipeServer: function () { let response = this.service.resource(this.engineURL).delete(); if (response.status != 200 && response.status != 404) { throw response; @@ -1709,7 +1709,7 @@ SyncEngine.prototype = { this._resetClient(); }, - removeClientData() { + removeClientData: function () { // Implement this method in engines that store client specific data // on the server. }, @@ -1730,7 +1730,7 @@ SyncEngine.prototype = { * * All return values will be part of the kRecoveryStrategy enumeration. */ - handleHMACMismatch(item, mayRetry) { + handleHMACMismatch: function (item, mayRetry) { // By default we either try again, or bail out noisily. return (this.service.handleHMACEvent() && mayRetry) ? SyncEngine.kRecoveryStrategy.retry : diff --git a/services/sync/modules/engines/addons.js b/services/sync/modules/engines/addons.js index 8dcad7bbd06a..6dab6065e245 100644 --- a/services/sync/modules/engines/addons.js +++ b/services/sync/modules/engines/addons.js @@ -503,7 +503,7 @@ AddonsStore.prototype = { } }, - /** ************************************************************************* + /*************************************************************************** * Functions below are unique to this store and not part of the Store API * ***************************************************************************/ @@ -732,7 +732,7 @@ AddonsTracker.prototype = { this.score += SCORE_INCREMENT_XLARGE; }, - startTracking() { + startTracking: function() { if (this.engine.enabled) { this.reconciler.startListening(); } @@ -740,7 +740,7 @@ AddonsTracker.prototype = { this.reconciler.addChangeListener(this); }, - stopTracking() { + stopTracking: function() { this.reconciler.removeChangeListener(this); this.reconciler.stopListening(); }, diff --git a/services/sync/modules/engines/bookmarks.js b/services/sync/modules/engines/bookmarks.js index 49d4bbb2245b..223fd5ce27d6 100644 --- a/services/sync/modules/engines/bookmarks.js +++ b/services/sync/modules/engines/bookmarks.js @@ -312,7 +312,7 @@ BookmarksEngine.prototype = { let guidMap = {}; let tree = Async.promiseSpinningly(PlacesUtils.promiseBookmarksTree("")); - function* walkBookmarksTree(tree, parent = null) { + function* walkBookmarksTree(tree, parent=null) { if (tree) { // Skip root node if (parent) { @@ -362,7 +362,7 @@ BookmarksEngine.prototype = { key = "s" + node.index; break; default: - this._log.error("Unknown place type: '" + placeType + "'"); + this._log.error("Unknown place type: '"+placeType+"'"); continue; } @@ -522,7 +522,7 @@ BookmarksEngine.prototype = { return false; }, - _processIncoming(newitems) { + _processIncoming: function (newitems) { try { SyncEngine.prototype._processIncoming.call(this, newitems); } finally { @@ -785,7 +785,7 @@ BookmarksStore.prototype = { }, _stmts: {}, - _getStmt(query) { + _getStmt: function(query) { if (query in this._stmts) { return this._stmts[query]; } @@ -866,7 +866,7 @@ function BookmarksTracker(name, engine) { BookmarksTracker.prototype = { __proto__: Tracker.prototype, - // `_ignore` checks the change source for each observer notification, so we + //`_ignore` checks the change source for each observer notification, so we // don't want to let the engine ignore all changes during a sync. get ignoreAll() { return false; @@ -880,14 +880,14 @@ BookmarksTracker.prototype = { // in Places. persistChangedIDs: false, - startTracking() { + startTracking: function() { PlacesUtils.bookmarks.addObserver(this, true); Svc.Obs.add("bookmarks-restore-begin", this); Svc.Obs.add("bookmarks-restore-success", this); Svc.Obs.add("bookmarks-restore-failed", this); }, - stopTracking() { + stopTracking: function() { PlacesUtils.bookmarks.removeObserver(this); Svc.Obs.remove("bookmarks-restore-begin", this); Svc.Obs.remove("bookmarks-restore-success", this); @@ -1018,7 +1018,7 @@ BookmarksTracker.prototype = { this._upScore(); }, - onItemRemoved(itemId, parentId, index, type, uri, + onItemRemoved: function (itemId, parentId, index, type, uri, guid, parentGuid, source) { if (IGNORED_SOURCES.includes(source)) { return; @@ -1095,7 +1095,7 @@ BookmarksTracker.prototype = { return; this._log.trace("onItemChanged: " + itemId + - (", " + property + (isAnno ? " (anno)" : "")) + + (", " + property + (isAnno? " (anno)" : "")) + (value ? (" = \"" + value + "\"") : "")); this._upScore(); }, @@ -1112,16 +1112,16 @@ BookmarksTracker.prototype = { this._upScore(); }, - onBeginUpdateBatch() { + onBeginUpdateBatch: function () { ++this._batchDepth; }, - onEndUpdateBatch() { + onEndUpdateBatch: function () { if (--this._batchDepth === 0 && this._batchSawScoreIncrement) { this.score += SCORE_INCREMENT_XLARGE; this._batchSawScoreIncrement = false; } }, - onItemVisited() {} + onItemVisited: function () {} }; class BookmarksChangeset extends Changeset { diff --git a/services/sync/modules/engines/clients.js b/services/sync/modules/engines/clients.js index 3535dd0e06ff..8ddd115b5ced 100644 --- a/services/sync/modules/engines/clients.js +++ b/services/sync/modules/engines/clients.js @@ -490,8 +490,8 @@ ClientEngine.prototype = { } let action = { - command, - args, + command: command, + args: args, flowID: flowID || Utils.makeGUID(), // used for telemetry. }; @@ -705,7 +705,7 @@ ClientStore.prototype = { fxAccounts.getDeviceId().then(id => cb(null, id), cb); try { record.fxaDeviceId = cb.wait(); - } catch (error) { + } catch(error) { this._log.warn("failed to get fxa device id", error); } record.name = this.engine.localName; diff --git a/services/sync/modules/engines/extension-storage.js b/services/sync/modules/engines/extension-storage.js index 1231412d05e6..792b629df77f 100644 --- a/services/sync/modules/engines/extension-storage.js +++ b/services/sync/modules/engines/extension-storage.js @@ -43,7 +43,7 @@ ExtensionStorageEngine.prototype = { syncPriority: 10, allowSkippedRecord: false, - _sync() { + _sync: function () { return Async.promiseSpinningly(ExtensionStorageSync.syncAll()); }, @@ -68,15 +68,15 @@ function ExtensionStorageTracker(name, engine) { ExtensionStorageTracker.prototype = { __proto__: Tracker.prototype, - startTracking() { + startTracking: function () { Svc.Obs.add("ext.storage.sync-changed", this); }, - stopTracking() { + stopTracking: function () { Svc.Obs.remove("ext.storage.sync-changed", this); }, - observe(subject, topic, data) { + observe: function (subject, topic, data) { Tracker.prototype.observe.call(this, subject, topic, data); if (this.ignoreAll) { @@ -94,15 +94,15 @@ ExtensionStorageTracker.prototype = { // Override a bunch of methods which don't do anything for us. // This is a performance hack. - ignoreID() { + ignoreID: function() { }, - unignoreID() { + unignoreID: function() { }, - addChangedID() { + addChangedID: function() { }, - removeChangedID() { + removeChangedID: function() { }, - clearChangedIDs() { + clearChangedIDs: function() { }, }; @@ -221,7 +221,7 @@ class KeyRingEncryptionRemoteTransformer extends EncryptionRemoteTransformer { let kB = Utils.hexToBytes(user.kB); let keyMaterial = CryptoUtils.hkdf(kB, undefined, - "identity.mozilla.com/picl/v1/chrome.storage.sync", 2 * 32); + "identity.mozilla.com/picl/v1/chrome.storage.sync", 2*32); let bundle = new BulkKeyBundle(); // [encryptionKey, hmacKey] bundle.keyPair = [keyMaterial.slice(0, 32), keyMaterial.slice(32, 64)]; diff --git a/services/sync/modules/engines/forms.js b/services/sync/modules/engines/forms.js index 9d1282b2bbe3..43f79d4f7e2c 100644 --- a/services/sync/modules/engines/forms.js +++ b/services/sync/modules/engines/forms.js @@ -37,7 +37,7 @@ var FormWrapper = { _getEntryCols: ["fieldname", "value"], _guidCols: ["guid"], - _promiseSearch(terms, searchData) { + _promiseSearch: function(terms, searchData) { return new Promise(resolve => { let results = []; let callbacks = { @@ -53,17 +53,17 @@ var FormWrapper = { }, // Do a "sync" search by spinning the event loop until it completes. - _searchSpinningly(terms, searchData) { + _searchSpinningly: function(terms, searchData) { return Async.promiseSpinningly(this._promiseSearch(terms, searchData)); }, - _updateSpinningly(changes) { + _updateSpinningly: function(changes) { if (!Svc.FormHistory.enabled) { return; // update isn't going to do anything. } let cb = Async.makeSpinningCallback(); let callbacks = { - handleCompletion(reason) { + handleCompletion: function(reason) { cb(); } }; @@ -71,27 +71,27 @@ var FormWrapper = { return cb.wait(); }, - getEntry(guid) { - let results = this._searchSpinningly(this._getEntryCols, {guid}); + getEntry: function (guid) { + let results = this._searchSpinningly(this._getEntryCols, {guid: guid}); if (!results.length) { return null; } return {name: results[0].fieldname, value: results[0].value}; }, - getGUID(name, value) { + getGUID: function (name, value) { // Query for the provided entry. - let query = { fieldname: name, value }; + let query = { fieldname: name, value: value }; let results = this._searchSpinningly(this._guidCols, query); return results.length ? results[0].guid : null; }, - hasGUID(guid) { + hasGUID: function (guid) { // We could probably use a count function here, but searchSpinningly exists... - return this._searchSpinningly(this._guidCols, {guid}).length != 0; + return this._searchSpinningly(this._guidCols, {guid: guid}).length != 0; }, - replaceGUID(oldGUID, newGUID) { + replaceGUID: function (oldGUID, newGUID) { let changes = { op: "update", guid: oldGUID, @@ -129,7 +129,7 @@ function FormStore(name, engine) { FormStore.prototype = { __proto__: Store.prototype, - _processChange(change) { + _processChange: function (change) { // If this._changes is defined, then we are applying a batch, so we // can defer it. if (this._changes) { @@ -141,7 +141,7 @@ FormStore.prototype = { FormWrapper._updateSpinningly(change); }, - applyIncomingBatch(records) { + applyIncomingBatch: function (records) { // We collect all the changes to be made then apply them all at once. this._changes = []; let failures = Store.prototype.applyIncomingBatch.call(this, records); @@ -152,7 +152,7 @@ FormStore.prototype = { return failures; }, - getAllIDs() { + getAllIDs: function () { let results = FormWrapper._searchSpinningly(["guid"], []) let guids = {}; for (let result of results) { @@ -161,15 +161,15 @@ FormStore.prototype = { return guids; }, - changeItemID(oldID, newID) { + changeItemID: function (oldID, newID) { FormWrapper.replaceGUID(oldID, newID); }, - itemExists(id) { + itemExists: function (id) { return FormWrapper.hasGUID(id); }, - createRecord(id, collection) { + createRecord: function (id, collection) { let record = new FormRec(collection, id); let entry = FormWrapper.getEntry(id); if (entry != null) { @@ -181,7 +181,7 @@ FormStore.prototype = { return record; }, - create(record) { + create: function (record) { this._log.trace("Adding form record for " + record.name); let change = { op: "add", @@ -191,7 +191,7 @@ FormStore.prototype = { this._processChange(change); }, - remove(record) { + remove: function (record) { this._log.trace("Removing form record: " + record.id); let change = { op: "remove", @@ -200,11 +200,11 @@ FormStore.prototype = { this._processChange(change); }, - update(record) { + update: function (record) { this._log.trace("Ignoring form record update request!"); }, - wipe() { + wipe: function () { let change = { op: "remove" }; @@ -222,15 +222,15 @@ FormTracker.prototype = { Ci.nsIObserver, Ci.nsISupportsWeakReference]), - startTracking() { + startTracking: function() { Svc.Obs.add("satchel-storage-changed", this); }, - stopTracking() { + stopTracking: function() { Svc.Obs.remove("satchel-storage-changed", this); }, - observe(subject, topic, data) { + observe: function (subject, topic, data) { Tracker.prototype.observe.call(this, subject, topic, data); if (this.ignoreAll) { return; @@ -245,7 +245,7 @@ FormTracker.prototype = { } }, - trackEntry(guid) { + trackEntry: function (guid) { this.addChangedID(guid); this.score += SCORE_INCREMENT_MEDIUM; }, @@ -302,4 +302,4 @@ class FormValidator extends CollectionValidator { return res; } -} +} \ No newline at end of file diff --git a/services/sync/modules/engines/history.js b/services/sync/modules/engines/history.js index 00817895ff83..acb82ec9d914 100644 --- a/services/sync/modules/engines/history.js +++ b/services/sync/modules/engines/history.js @@ -45,7 +45,7 @@ HistoryEngine.prototype = { syncPriority: 7, - _processIncoming(newitems) { + _processIncoming: function (newitems) { // We want to notify history observers that a batch operation is underway // so they don't do lots of work for each incoming record. let observers = PlacesUtils.history.getObservers(); @@ -134,7 +134,7 @@ HistoryStore.prototype = { }, _stmts: {}, - _getStmt(query) { + _getStmt: function(query) { if (query in this._stmts) { return this._stmts[query]; } @@ -292,7 +292,7 @@ HistoryStore.prototype = { return failed; } - let updatePlacesCallback = { + let updatePlacesCallback = { handleResult: function handleResult() {}, handleError: function handleError(resultCode, placeInfo) { failed.push(placeInfo.guid); @@ -306,7 +306,7 @@ HistoryStore.prototype = { /** * Converts a Sync history record to a mozIPlaceInfo. - * + * * Throws if an invalid record is encountered (invalid URI, etc.), * returns true if the record is to be applied, false otherwise * (no visits to add, etc.), @@ -420,7 +420,7 @@ HistoryStore.prototype = { wipe: function HistStore_wipe() { let cb = Async.makeSyncCallback(); - PlacesUtils.history.clear().then(result => { cb(null, result) }, err => { cb(err) }); + PlacesUtils.history.clear().then(result => {cb(null, result)}, err => {cb(err)}); return Async.waitForSyncCallback(cb); } }; @@ -431,12 +431,12 @@ function HistoryTracker(name, engine) { HistoryTracker.prototype = { __proto__: Tracker.prototype, - startTracking() { + startTracking: function() { this._log.info("Adding Places observer."); PlacesUtils.history.addObserver(this, true); }, - stopTracking() { + stopTracking: function() { this._log.info("Removing Places observer."); PlacesUtils.history.removeObserver(this); }, @@ -446,7 +446,7 @@ HistoryTracker.prototype = { Ci.nsISupportsWeakReference ]), - onDeleteAffectsGUID(uri, guid, reason, source, increment) { + onDeleteAffectsGUID: function (uri, guid, reason, source, increment) { if (this.ignoreAll || reason == Ci.nsINavHistoryObserver.REASON_EXPIRED) { return; } @@ -456,15 +456,15 @@ HistoryTracker.prototype = { } }, - onDeleteVisits(uri, visitTime, guid, reason) { + onDeleteVisits: function (uri, visitTime, guid, reason) { this.onDeleteAffectsGUID(uri, guid, reason, "onDeleteVisits", SCORE_INCREMENT_SMALL); }, - onDeleteURI(uri, guid, reason) { + onDeleteURI: function (uri, guid, reason) { this.onDeleteAffectsGUID(uri, guid, reason, "onDeleteURI", SCORE_INCREMENT_XLARGE); }, - onVisit(uri, vid, time, session, referrer, trans, guid) { + onVisit: function (uri, vid, time, session, referrer, trans, guid) { if (this.ignoreAll) { this._log.trace("ignoreAll: ignoring visit for " + guid); return; @@ -476,7 +476,7 @@ HistoryTracker.prototype = { } }, - onClearHistory() { + onClearHistory: function () { this._log.trace("onClearHistory"); // Note that we're going to trigger a sync, but none of the cleared // pages are tracked, so the deletions will not be propagated. @@ -484,9 +484,9 @@ HistoryTracker.prototype = { this.score += SCORE_INCREMENT_XLARGE; }, - onBeginUpdateBatch() {}, - onEndUpdateBatch() {}, - onPageChanged() {}, - onTitleChanged() {}, - onBeforeDeleteURI() {}, + onBeginUpdateBatch: function () {}, + onEndUpdateBatch: function () {}, + onPageChanged: function () {}, + onTitleChanged: function () {}, + onBeforeDeleteURI: function () {}, }; diff --git a/services/sync/modules/engines/passwords.js b/services/sync/modules/engines/passwords.js index 5215e3cb8aab..51db49a0a877 100644 --- a/services/sync/modules/engines/passwords.js +++ b/services/sync/modules/engines/passwords.js @@ -41,7 +41,7 @@ PasswordEngine.prototype = { syncPriority: 2, - _syncFinish() { + _syncFinish: function () { SyncEngine.prototype._syncFinish.call(this); // Delete the Weave credentials from the server once. @@ -78,7 +78,7 @@ PasswordEngine.prototype = { } }, - _findDupe(item) { + _findDupe: function (item) { let login = this._store._nsLoginInfoFromRecord(item); if (!login) { return; @@ -104,14 +104,14 @@ function PasswordStore(name, engine) { PasswordStore.prototype = { __proto__: Store.prototype, - _newPropertyBag() { + _newPropertyBag: function () { return Cc["@mozilla.org/hash-property-bag;1"].createInstance(Ci.nsIWritablePropertyBag2); }, /** * Return an instance of nsILoginInfo (and, implicitly, nsILoginMetaInfo). */ - _nsLoginInfoFromRecord(record) { + _nsLoginInfoFromRecord: function (record) { function nullUndefined(x) { return (x == undefined) ? null : x; } @@ -144,7 +144,7 @@ PasswordStore.prototype = { return info; }, - _getLoginFromGUID(id) { + _getLoginFromGUID: function (id) { let prop = this._newPropertyBag(); prop.setPropertyAsAUTF8String("guid", id); @@ -160,7 +160,7 @@ PasswordStore.prototype = { return null; }, - getAllIDs() { + getAllIDs: function () { let items = {}; let logins = Services.logins.getAllLogins({}); @@ -177,7 +177,7 @@ PasswordStore.prototype = { return items; }, - changeItemID(oldID, newID) { + changeItemID: function (oldID, newID) { this._log.trace("Changing item ID: " + oldID + " to " + newID); let oldLogin = this._getLoginFromGUID(oldID); @@ -196,11 +196,11 @@ PasswordStore.prototype = { Services.logins.modifyLogin(oldLogin, prop); }, - itemExists(id) { + itemExists: function (id) { return !!this._getLoginFromGUID(id); }, - createRecord(id, collection) { + createRecord: function (id, collection) { let record = new LoginRec(collection, id); let login = this._getLoginFromGUID(id); @@ -225,7 +225,7 @@ PasswordStore.prototype = { return record; }, - create(record) { + create: function (record) { let login = this._nsLoginInfoFromRecord(record); if (!login) { return; @@ -236,12 +236,12 @@ PasswordStore.prototype = { "formSubmitURL: " + JSON.stringify(login.formSubmitURL)); try { Services.logins.addLogin(login); - } catch (ex) { + } catch(ex) { this._log.debug(`Adding record ${record.id} resulted in exception`, ex); } }, - remove(record) { + remove: function (record) { this._log.trace("Removing login " + record.id); let loginItem = this._getLoginFromGUID(record.id); @@ -253,7 +253,7 @@ PasswordStore.prototype = { Services.logins.removeLogin(loginItem); }, - update(record) { + update: function (record) { let loginItem = this._getLoginFromGUID(record.id); if (!loginItem) { this._log.debug("Skipping update for unknown item: " + record.hostname); @@ -268,12 +268,12 @@ PasswordStore.prototype = { try { Services.logins.modifyLogin(loginItem, newinfo); - } catch (ex) { + } catch(ex) { this._log.debug(`Modifying record ${record.id} resulted in exception; not modifying`, ex); } }, - wipe() { + wipe: function () { Services.logins.removeAllLogins(); }, }; @@ -286,15 +286,15 @@ function PasswordTracker(name, engine) { PasswordTracker.prototype = { __proto__: Tracker.prototype, - startTracking() { + startTracking: function () { Svc.Obs.add("passwordmgr-storage-changed", this); }, - stopTracking() { + stopTracking: function () { Svc.Obs.remove("passwordmgr-storage-changed", this); }, - observe(subject, topic, data) { + observe: function (subject, topic, data) { Tracker.prototype.observe.call(this, subject, topic, data); if (this.ignoreAll) { diff --git a/services/sync/modules/engines/prefs.js b/services/sync/modules/engines/prefs.js index e80d564422a7..eaff28c1a02a 100644 --- a/services/sync/modules/engines/prefs.js +++ b/services/sync/modules/engines/prefs.js @@ -44,7 +44,7 @@ PrefsEngine.prototype = { syncPriority: 1, allowSkippedRecord: false, - getChangedIDs() { + getChangedIDs: function () { // No need for a proper timestamp (no conflict resolution needed). let changedIDs = {}; if (this._tracker.modified) @@ -52,12 +52,12 @@ PrefsEngine.prototype = { return changedIDs; }, - _wipeClient() { + _wipeClient: function () { SyncEngine.prototype._wipeClient.call(this); this.justWiped = true; }, - _reconcile(item) { + _reconcile: function (item) { // Apply the incoming item if we don't care about the local data if (this.justWiped) { this.justWiped = false; @@ -70,7 +70,7 @@ PrefsEngine.prototype = { function PrefStore(name, engine) { Store.call(this, name, engine); - Svc.Obs.add("profile-before-change", function() { + Svc.Obs.add("profile-before-change", function () { this.__prefs = null; }, this); } @@ -85,7 +85,7 @@ PrefStore.prototype = { return this.__prefs; }, - _getSyncPrefs() { + _getSyncPrefs: function () { let syncPrefs = Cc["@mozilla.org/preferences-service;1"] .getService(Ci.nsIPrefService) .getBranch(PREF_SYNC_PREFS_PREFIX) @@ -95,12 +95,12 @@ PrefStore.prototype = { return controlPrefs.concat(syncPrefs); }, - _isSynced(pref) { + _isSynced: function (pref) { return pref.startsWith(PREF_SYNC_PREFS_PREFIX) || this._prefs.get(PREF_SYNC_PREFS_PREFIX + pref, false); }, - _getAllPrefs() { + _getAllPrefs: function () { let values = {}; for (let pref of this._getSyncPrefs()) { if (this._isSynced(pref)) { @@ -111,7 +111,7 @@ PrefStore.prototype = { return values; }, - _updateLightWeightTheme(themeID) { + _updateLightWeightTheme (themeID) { let themeObject = null; if (themeID) { themeObject = LightweightThemeManager.getUsedTheme(themeID); @@ -119,7 +119,7 @@ PrefStore.prototype = { LightweightThemeManager.currentTheme = themeObject; }, - _setAllPrefs(values) { + _setAllPrefs: function (values) { let selectedThemeIDPref = "lightweightThemes.selectedThemeID"; let selectedThemeIDBefore = this._prefs.get(selectedThemeIDPref, null); let selectedThemeIDAfter = selectedThemeIDBefore; @@ -148,7 +148,7 @@ PrefStore.prototype = { } else { try { this._prefs.set(pref, value); - } catch (ex) { + } catch(ex) { this._log.trace("Failed to set pref: " + pref + ": " + ex); } } @@ -161,22 +161,22 @@ PrefStore.prototype = { } }, - getAllIDs() { + getAllIDs: function () { /* We store all prefs in just one WBO, with just one GUID */ let allprefs = {}; allprefs[PREFS_GUID] = true; return allprefs; }, - changeItemID(oldID, newID) { + changeItemID: function (oldID, newID) { this._log.trace("PrefStore GUID is constant!"); }, - itemExists(id) { + itemExists: function (id) { return (id === PREFS_GUID); }, - createRecord(id, collection) { + createRecord: function (id, collection) { let record = new PrefRec(collection, id); if (id == PREFS_GUID) { @@ -188,15 +188,15 @@ PrefStore.prototype = { return record; }, - create(record) { + create: function (record) { this._log.trace("Ignoring create request"); }, - remove(record) { + remove: function (record) { this._log.trace("Ignoring remove request"); }, - update(record) { + update: function (record) { // Silently ignore pref updates that are for other apps. if (record.id != PREFS_GUID) return; @@ -205,7 +205,7 @@ PrefStore.prototype = { this._setAllPrefs(record.value); }, - wipe() { + wipe: function () { this._log.trace("Ignoring wipe request"); } }; @@ -238,16 +238,16 @@ PrefTracker.prototype = { return this.__prefs; }, - startTracking() { + startTracking: function () { Services.prefs.addObserver("", this, false); }, - stopTracking() { + stopTracking: function () { this.__prefs = null; Services.prefs.removeObserver("", this); }, - observe(subject, topic, data) { + observe: function (subject, topic, data) { Tracker.prototype.observe.call(this, subject, topic, data); switch (topic) { diff --git a/services/sync/modules/engines/tabs.js b/services/sync/modules/engines/tabs.js index 32a53c90c4de..69874e1051e6 100644 --- a/services/sync/modules/engines/tabs.js +++ b/services/sync/modules/engines/tabs.js @@ -51,7 +51,7 @@ TabEngine.prototype = { syncPriority: 3, - getChangedIDs() { + getChangedIDs: function () { // No need for a proper timestamp (no conflict resolution needed). let changedIDs = {}; if (this._tracker.modified) @@ -60,22 +60,22 @@ TabEngine.prototype = { }, // API for use by Sync UI code to give user choices of tabs to open. - getAllClients() { + getAllClients: function () { return this._store._remoteClients; }, - getClientById(id) { + getClientById: function (id) { return this._store._remoteClients[id]; }, - _resetClient() { + _resetClient: function () { SyncEngine.prototype._resetClient.call(this); this._store.wipe(); this._tracker.modified = true; this.hasSyncedThisSession = false; }, - removeClientData() { + removeClientData: function () { let url = this.engineURL + "/" + this.service.clientsEngine.localID; this.service.resource(url).delete(); }, @@ -83,7 +83,7 @@ TabEngine.prototype = { /** * Return a Set of open URLs. */ - getOpenURLs() { + getOpenURLs: function () { let urls = new Set(); for (let entry of this._store.getAllTabs()) { urls.add(entry.urlHistory[0]); @@ -91,7 +91,7 @@ TabEngine.prototype = { return urls; }, - _reconcile(item) { + _reconcile: function (item) { // Skip our own record. // TabStore.itemExists tests only against our local client ID. if (this._store.itemExists(item.id)) { @@ -115,24 +115,24 @@ function TabStore(name, engine) { TabStore.prototype = { __proto__: Store.prototype, - itemExists(id) { + itemExists: function (id) { return id == this.engine.service.clientsEngine.localID; }, - getWindowEnumerator() { + getWindowEnumerator: function () { return Services.wm.getEnumerator("navigator:browser"); }, - shouldSkipWindow(win) { + shouldSkipWindow: function (win) { return win.closed || PrivateBrowsingUtils.isWindowPrivate(win); }, - getTabState(tab) { + getTabState: function (tab) { return JSON.parse(Svc.Session.getTabState(tab)); }, - getAllTabs(filter) { + getAllTabs: function (filter) { let filteredUrls = new RegExp(Svc.Prefs.get("engine.tabs.filteredUrls"), "i"); let allTabs = []; @@ -200,12 +200,12 @@ TabStore.prototype = { return allTabs; }, - createRecord(id, collection) { + createRecord: function (id, collection) { let record = new TabSetRecord(collection, id); record.clientName = this.engine.service.clientsEngine.localName; // Sort tabs in descending-used order to grab the most recently used - let tabs = this.getAllTabs(true).sort(function(a, b) { + let tabs = this.getAllTabs(true).sort(function (a, b) { return b.lastUsed - a.lastUsed; }); @@ -225,7 +225,7 @@ TabStore.prototype = { } this._log.trace("Created tabs " + tabs.length + " of " + origLength); - tabs.forEach(function(tab) { + tabs.forEach(function (tab) { this._log.trace("Wrapping tab: " + JSON.stringify(tab)); }, this); @@ -233,7 +233,7 @@ TabStore.prototype = { return record; }, - getAllIDs() { + getAllIDs: function () { // Don't report any tabs if all windows are in private browsing for // first syncs. let ids = {}; @@ -259,18 +259,18 @@ TabStore.prototype = { return ids; }, - wipe() { + wipe: function () { this._remoteClients = {}; }, - create(record) { + create: function (record) { this._log.debug("Adding remote tabs from " + record.clientName); this._remoteClients[record.id] = Object.assign({}, record.cleartext, { lastModified: record.modified }); }, - update(record) { + update: function (record) { this._log.trace("Ignoring tab updates as local ones win"); }, }; @@ -290,13 +290,13 @@ TabTracker.prototype = { QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]), - clearChangedIDs() { + clearChangedIDs: function () { this.modified = false; }, _topics: ["pageshow", "TabOpen", "TabClose", "TabSelect"], - _registerListenersForWindow(window) { + _registerListenersForWindow: function (window) { this._log.trace("Registering tab listeners in window"); for (let topic of this._topics) { window.addEventListener(topic, this.onTab, false); @@ -308,11 +308,11 @@ TabTracker.prototype = { } }, - _unregisterListeners(event) { + _unregisterListeners: function (event) { this._unregisterListenersForWindow(event.target); }, - _unregisterListenersForWindow(window) { + _unregisterListenersForWindow: function (window) { this._log.trace("Removing tab listeners in window"); window.removeEventListener("unload", this._unregisterListeners, false); for (let topic of this._topics) { @@ -323,7 +323,7 @@ TabTracker.prototype = { } }, - startTracking() { + startTracking: function () { Svc.Obs.add("domwindowopened", this); let wins = Services.wm.getEnumerator("navigator:browser"); while (wins.hasMoreElements()) { @@ -331,7 +331,7 @@ TabTracker.prototype = { } }, - stopTracking() { + stopTracking: function () { Svc.Obs.remove("domwindowopened", this); let wins = Services.wm.getEnumerator("navigator:browser"); while (wins.hasMoreElements()) { @@ -339,7 +339,7 @@ TabTracker.prototype = { } }, - observe(subject, topic, data) { + observe: function (subject, topic, data) { Tracker.prototype.observe.call(this, subject, topic, data); switch (topic) { @@ -356,7 +356,7 @@ TabTracker.prototype = { } }, - onTab(event) { + onTab: function (event) { if (event.originalTarget.linkedBrowser) { let browser = event.originalTarget.linkedBrowser; if (PrivateBrowsingUtils.isBrowserPrivate(browser) && @@ -378,7 +378,7 @@ TabTracker.prototype = { }, // web progress listeners. - onLocationChange(webProgress, request, location, flags) { + onLocationChange: function (webProgress, request, location, flags) { // We only care about top-level location changes which are not in the same // document. if (webProgress.isTopLevel && diff --git a/services/sync/modules/identity.js b/services/sync/modules/identity.js index e6760ba9b1cd..b4da8c0bb240 100644 --- a/services/sync/modules/identity.js +++ b/services/sync/modules/identity.js @@ -87,18 +87,18 @@ IdentityManager.prototype = { /** * Initialize the identity provider. */ - initialize() { + initialize: function() { // Nothing to do for this identity provider. }, - finalize() { + finalize: function() { // Nothing to do for this identity provider. }, /** * Called whenever Service.logout() is called. */ - logout() { + logout: function() { // nothing to do for this identity provider. }, @@ -106,7 +106,7 @@ IdentityManager.prototype = { * Ensure the user is logged in. Returns a promise that resolves when * the user is logged in, or is rejected if the login attempt has failed. */ - ensureLoggedIn() { + ensureLoggedIn: function() { // nothing to do for this identity provider return Promise.resolve(); }, @@ -169,7 +169,7 @@ IdentityManager.prototype = { /** * Resets/Drops all credentials we hold for the current user. */ - resetCredentials() { + resetCredentials: function() { this.basicPassword = null; this.resetSyncKey(); }, @@ -177,7 +177,7 @@ IdentityManager.prototype = { /** * Resets/Drops the sync key we hold for the current user. */ - resetSyncKey() { + resetSyncKey: function() { this.syncKey = null; // syncKeyBundle cleared as a result of setting syncKey. }, @@ -372,7 +372,7 @@ IdentityManager.prototype = { * Returns a promise that resolves with the current auth state after * attempting to unlock. */ - unlockAndVerifyAuthState() { + unlockAndVerifyAuthState: function() { // Try to fetch the passphrase - this will prompt for MP unlock as a // side-effect... try { @@ -441,7 +441,7 @@ IdentityManager.prototype = { * allows us to avoid a network request for when we actually need the * migration info. */ - prefetchMigrationSentinel(service) { + prefetchMigrationSentinel: function(service) { // Try and fetch the migration sentinel - it will end up in the recordManager // cache. try { @@ -495,7 +495,7 @@ IdentityManager.prototype = { /** * Return credentials hosts for this identity only. */ - _getSyncCredentialsHosts() { + _getSyncCredentialsHosts: function() { return Utils.getSyncCredentialsHostsLegacy(); }, @@ -584,12 +584,12 @@ IdentityManager.prototype = { request.setHeader("authorization", "Basic " + btoa(up)); }, - createClusterManager(service) { + createClusterManager: function(service) { Cu.import("resource://services-sync/stages/cluster.js"); return new ClusterManager(service); }, - offerSyncOptions() { + offerSyncOptions: function () { // Do nothing for Sync 1.1. return {accepted: true}; }, diff --git a/services/sync/modules/jpakeclient.js b/services/sync/modules/jpakeclient.js index 6e22ad54e8e3..625dc91b6c39 100644 --- a/services/sync/modules/jpakeclient.js +++ b/services/sync/modules/jpakeclient.js @@ -24,8 +24,8 @@ const JPAKE_VERIFY_VALUE = "0123456789ABCDEF"; /** * Client to exchange encrypted data using the J-PAKE algorithm. * The exchange between two clients of this type looks like this: - * - * + * + * * Mobile Server Desktop * =================================================================== * | @@ -59,26 +59,26 @@ const JPAKE_VERIFY_VALUE = "0123456789ABCDEF"; * decrypt credentials | * delete session ----------------->| * start syncing | - * - * + * + * * Create a client object like so: - * + * * let client = new JPAKEClient(controller); - * + * * The 'controller' object must implement the following methods: - * + * * displayPIN(pin) -- Called when a PIN has been generated and is ready to * be displayed to the user. Only called on the client where the pairing * was initiated with 'receiveNoPIN()'. - * + * * onPairingStart() -- Called when the pairing has started and messages are * being sent back and forth over the channel. Only called on the client * where the pairing was initiated with 'receiveNoPIN()'. - * + * * onPaired() -- Called when the device pairing has been established and * we're ready to send the credentials over. To do that, the controller * must call 'sendAndComplete()' while the channel is active. - * + * * onComplete(data) -- Called after transfer has been completed. On * the sending side this is called with no parameter and as soon as the * data has been uploaded. This does not mean the receiving side has @@ -86,28 +86,28 @@ const JPAKE_VERIFY_VALUE = "0123456789ABCDEF"; * * onAbort(error) -- Called whenever an error is encountered. All errors lead * to an abort and the process has to be started again on both sides. - * + * * To start the data transfer on the receiving side, call - * + * * client.receiveNoPIN(); - * + * * This will allocate a new channel on the server, generate a PIN, have it * displayed and then do the transfer once the protocol has been completed * with the sending side. - * + * * To initiate the transfer from the sending side, call - * + * * client.pairWithPIN(pin, true); - * + * * Once the pairing has been established, the controller's 'onPaired()' method * will be called. To then transmit the data, call - * + * * client.sendAndComplete(data); - * + * * To abort the process, call - * + * * client.abort(); - * + * * Note that after completion or abort, the 'client' instance may not be reused. * You will have to create a new one in case you'd like to restart the process. */ @@ -141,7 +141,7 @@ JPAKEClient.prototype = { /** * Initiate pairing and receive data without providing a PIN. The PIN will * be generated and passed on to the controller to be displayed to the user. - * + * * This is typically called on mobile devices where typing is tedious. */ receiveNoPIN: function receiveNoPIN() { @@ -185,10 +185,10 @@ JPAKEClient.prototype = { /** * Initiate pairing based on the PIN entered by the user. - * + * * This is typically called on desktop devices where typing is easier than * on mobile. - * + * * @param pin * 12 character string (in human-friendly base32) containing the PIN * entered by the user. @@ -208,7 +208,7 @@ JPAKEClient.prototype = { this._chain(this._computeStepOne, this._getStep, - function(callback) { + function (callback) { // Ensure that the other client can deal with a delay for // the last message if that's requested by the caller. if (!expectDelay) { @@ -230,7 +230,7 @@ JPAKEClient.prototype = { /** * Send data after a successful pairing. - * + * * @param obj * Object containing the data to send. It will be serialized as JSON. */ @@ -249,7 +249,7 @@ JPAKEClient.prototype = { * Abort the current pairing. The channel on the server will be deleted * if the abort wasn't due to a network or server error. The controller's * 'onAbort()' method is notified in all cases. - * + * * @param error [optional] * Error constant indicating the reason for the abort. Defaults to * user abort. @@ -350,7 +350,7 @@ JPAKEClient.prototype = { } else { request.setHeader("If-None-Match", "*"); } - request.put(this._outgoing, Utils.bind2(this, function(error) { + request.put(this._outgoing, Utils.bind2(this, function (error) { if (this._finished) { return; } @@ -369,7 +369,7 @@ JPAKEClient.prototype = { // There's no point in returning early here since the next step will // always be a GET so let's pause for twice the poll interval. this._my_etag = request.response.headers["etag"]; - Utils.namedTimer(function() { callback(); }, this._pollInterval * 2, + Utils.namedTimer(function () { callback(); }, this._pollInterval * 2, this, "_pollTimer"); })); }, @@ -383,7 +383,7 @@ JPAKEClient.prototype = { request.setHeader("If-None-Match", this._my_etag); } - request.get(Utils.bind2(this, function(error) { + request.get(Utils.bind2(this, function (error) { if (this._finished) { return; } @@ -445,7 +445,7 @@ JPAKEClient.prototype = { let request = this._newRequest(this._serverURL + "report"); request.setHeader("X-KeyExchange-Cid", this._channel); request.setHeader("X-KeyExchange-Log", reason); - request.post("", Utils.bind2(this, function(error) { + request.post("", Utils.bind2(this, function (error) { if (error) { this._log.warn("Report failed: " + error); } else if (request.response.status != 200) { @@ -572,7 +572,7 @@ JPAKEClient.prototype = { } this._outgoing = {type: this._my_signerid + "3", version: KEYEXCHANGE_VERSION, - payload: {ciphertext, IV: iv}}; + payload: {ciphertext: ciphertext, IV: iv}}; this._log.trace("Generated message " + this._outgoing.type); callback(); }, @@ -601,7 +601,7 @@ JPAKEClient.prototype = { this._log.debug("Verified pairing!"); this._paired = true; - Utils.nextTick(function() { this.controller.onPaired(); }, this); + Utils.nextTick(function () { this.controller.onPaired(); }, this); callback(); }, @@ -619,7 +619,7 @@ JPAKEClient.prototype = { } this._outgoing = {type: this._my_signerid + "3", version: KEYEXCHANGE_VERSION, - payload: {ciphertext, IV: iv, hmac}}; + payload: {ciphertext: ciphertext, IV: iv, hmac: hmac}}; this._log.trace("Generated message " + this._outgoing.type); callback(); }, @@ -647,7 +647,7 @@ JPAKEClient.prototype = { this._log.trace("Decrypting data."); let cleartext; - try { + try { cleartext = Svc.Crypto.decrypt(step3.ciphertext, this._crypto_key, step3.IV); } catch (ex) { @@ -671,7 +671,7 @@ JPAKEClient.prototype = { _complete: function _complete() { this._log.debug("Exchange completed."); this._finished = true; - Utils.nextTick(function() { this.controller.onComplete(this._newData); }, + Utils.nextTick(function () { this.controller.onComplete(this._newData); }, this); } @@ -710,8 +710,8 @@ this.SendCredentialsController = // this device's sync configuration, in case that happens while we // haven't finished the first sync yet. Services.obs.addObserver(this, "weave:service:sync:finish", false); - Services.obs.addObserver(this, "weave:service:sync:error", false); - Services.obs.addObserver(this, "weave:service:start-over", false); + Services.obs.addObserver(this, "weave:service:sync:error", false); + Services.obs.addObserver(this, "weave:service:start-over", false); } SendCredentialsController.prototype = { diff --git a/services/sync/modules/main.js b/services/sync/modules/main.js index 4231fbfbe6b4..af3399e7adcc 100644 --- a/services/sync/modules/main.js +++ b/services/sync/modules/main.js @@ -22,7 +22,7 @@ function lazyImport(module, dest, props) { return dest[prop] = ns[prop]; }; } - props.forEach(function(prop) { dest.__defineGetter__(prop, getter(prop)); }); + props.forEach(function (prop) { dest.__defineGetter__(prop, getter(prop)); }); } for (let mod in lazies) { diff --git a/services/sync/modules/policies.js b/services/sync/modules/policies.js index f61ace9c38ca..3e317196ef96 100644 --- a/services/sync/modules/policies.js +++ b/services/sync/modules/policies.js @@ -133,7 +133,7 @@ SyncScheduler.prototype = { observe: function observe(subject, topic, data) { this._log.trace("Handling " + topic); - switch (topic) { + switch(topic) { case "weave:engine:score:updated": if (Status.login == LOGIN_SUCCEEDED) { Utils.namedTimer(this.calculateScore, SCORE_UPDATE_DELAY, this, @@ -584,7 +584,7 @@ ErrorHandler.prototype = { observe: function observe(subject, topic, data) { this._log.trace("Handling " + topic); - switch (topic) { + switch(topic) { case "weave:engine:sync:applied": if (subject.newFailed) { // An engine isn't able to apply one or more incoming records. @@ -656,7 +656,7 @@ ErrorHandler.prototype = { // engine, Status.service will be SYNC_FAILED_PARTIAL despite // Status.sync being SYNC_SUCCEEDED. // *facepalm* - if (Status.sync == SYNC_SUCCEEDED && + if (Status.sync == SYNC_SUCCEEDED && Status.service == STATUS_OK) { // Great. Let's clear our mid-sync 401 note. this._log.trace("Clearing lastSyncReassigned."); @@ -843,7 +843,7 @@ ErrorHandler.prototype = { return Svc.Prefs.set("errorhandler.alert.earliestNext", msec / 1000); }, - clearServerAlerts() { + clearServerAlerts: function () { // If we have any outstanding alerts, apparently they're no longer relevant. Svc.Prefs.resetBranch("errorhandler.alert"); }, @@ -857,7 +857,7 @@ ErrorHandler.prototype = { * "message": // Logged in Sync logs. * } */ - handleServerAlert(xwa) { + handleServerAlert: function (xwa) { if (!xwa.code) { this._log.warn("Got structured X-Weave-Alert, but no alert code."); return; @@ -895,7 +895,7 @@ ErrorHandler.prototype = { * * This method also looks for "side-channel" warnings. */ - checkServerError(resp) { + checkServerError: function (resp) { switch (resp.status) { case 200: case 404: diff --git a/services/sync/modules/record.js b/services/sync/modules/record.js index 455de746385a..f7a69d9ef1eb 100644 --- a/services/sync/modules/record.js +++ b/services/sync/modules/record.js @@ -65,7 +65,7 @@ WBORecord.prototype = { // Take a base URI string, with trailing slash, and return the URI of this // WBO based on collection and ID. - uri(base) { + uri: function(base) { if (this.collection && this.id) { let url = Utils.makeURI(base + this.collection + "/" + this.id); url.QueryInterface(Ci.nsIURL); @@ -80,7 +80,7 @@ WBORecord.prototype = { try { // The payload is likely to be JSON, but if not, keep it as a string this.payload = JSON.parse(this.payload); - } catch (ex) {} + } catch(ex) {} }, toJSON: function toJSON() { @@ -95,11 +95,11 @@ WBORecord.prototype = { toString: function toString() { return "{ " + - "id: " + this.id + " " + - "index: " + this.sortindex + " " + - "modified: " + this.modified + " " + - "ttl: " + this.ttl + " " + - "payload: " + JSON.stringify(this.payload) + + "id: " + this.id + " " + + "index: " + this.sortindex + " " + + "modified: " + this.modified + " " + + "ttl: " + this.ttl + " " + + "payload: " + JSON.stringify(this.payload) + " }"; } }; @@ -186,11 +186,11 @@ CryptoWrapper.prototype = { let payload = this.deleted ? "DELETED" : JSON.stringify(this.cleartext); return "{ " + - "id: " + this.id + " " + - "index: " + this.sortindex + " " + - "modified: " + this.modified + " " + - "ttl: " + this.ttl + " " + - "payload: " + payload + " " + + "id: " + this.id + " " + + "index: " + this.sortindex + " " + + "modified: " + this.modified + " " + + "ttl: " + this.ttl + " " + + "payload: " + payload + " " + "collection: " + (this.collection || "undefined") + " }"; }, @@ -330,7 +330,7 @@ CollectionKeyManager.prototype = { let last; changed = changed.filter(x => (x != last) && (last = x)); return {same: changed.length == 0, - changed}; + changed: changed}; }, get isClear() { @@ -344,7 +344,7 @@ CollectionKeyManager.prototype = { this._default = null; }, - keyForCollection(collection) { + keyForCollection: function(collection) { if (collection && this._collections[collection]) return this._collections[collection]; @@ -356,7 +356,7 @@ CollectionKeyManager.prototype = { * over it and generate random keys for each collection. * Create a WBO for the given data. */ - _makeWBO(collections, defaultBundle) { + _makeWBO: function(collections, defaultBundle) { let wbo = new CryptoWrapper(CRYPTO_COLLECTION, KEYS_WBO); let c = {}; for (let k in collections) { @@ -374,19 +374,19 @@ CollectionKeyManager.prototype = { /** * Create a WBO for the current keys. */ - asWBO(collection, id) { + asWBO: function(collection, id) { return this._makeWBO(this._collections, this._default); }, /** * Compute a new default key, and new keys for any specified collections. */ - newKeys(collections) { + newKeys: function(collections) { let newDefaultKeyBundle = this.newDefaultKeyBundle(); let newColls = {}; if (collections) { - collections.forEach(function(c) { + collections.forEach(function (c) { let b = new BulkKeyBundle(c); b.generateRandom(); newColls[c] = b; @@ -399,7 +399,7 @@ CollectionKeyManager.prototype = { * Generates new keys, but does not replace our local copy. Use this to * verify an upload before storing. */ - generateNewKeysWBO(collections) { + generateNewKeysWBO: function(collections) { let newDefaultKey, newColls; [newDefaultKey, newColls] = this.newKeys(collections); @@ -459,7 +459,7 @@ CollectionKeyManager.prototype = { // Take the fetched info/collections WBO, checking the change // time of the crypto collection. - updateNeeded(info_collections) { + updateNeeded: function(info_collections) { this._log.info("Testing for updateNeeded. Last modified: " + this.lastModified); @@ -630,7 +630,7 @@ Collection.prototype = { if (this._offset) args.push("offset=" + encodeURIComponent(this._offset)); - this.uri.query = (args.length > 0) ? '?' + args.join('&') : ''; + this.uri.query = (args.length > 0)? '?' + args.join('&') : ''; }, // get full items @@ -975,7 +975,7 @@ PostQueue.prototype = { headers.push(["x-if-unmodified-since", this.lastModified]); - this.log.info(`Posting ${this.numQueued} records of ${this.queued.length + 1} bytes with batch=${batch}`); + this.log.info(`Posting ${this.numQueued} records of ${this.queued.length+1} bytes with batch=${batch}`); let queued = this.queued + "]"; if (finalBatchPost) { this.bytesAlreadyBatched = 0; diff --git a/services/sync/modules/resource.js b/services/sync/modules/resource.js index 3757df2c23be..bf7066b9f2de 100644 --- a/services/sync/modules/resource.js +++ b/services/sync/modules/resource.js @@ -229,7 +229,7 @@ AsyncResource.prototype = { let action = channel.requestMethod; this._log.trace("Channel: " + channel); - this._log.trace("Action: " + action); + this._log.trace("Action: " + action); // Process status and success first. This way a problem with headers // doesn't fail to include accurate status information. @@ -256,7 +256,7 @@ AsyncResource.prototype = { if (this._log.level <= Log.Level.Trace) this._log.trace(action + " body: " + data); - } catch (ex) { + } catch(ex) { // Got a response, but an exception occurred during processing. // This shouldn't occur. this._log.warn("Caught unexpected exception in _oncomplete", ex); @@ -464,7 +464,8 @@ ChannelListener.prototype = { // Save the latest server timestamp when possible. try { AsyncResource.serverTime = channel.getResponseHeader("X-Weave-Timestamp") - 0; - } catch (ex) {} + } + catch(ex) {} this._log.trace("onStartRequest: " + channel.requestMethod + " " + channel.URI.spec); @@ -597,11 +598,11 @@ function ChannelNotificationListener(headersToCopy) { ChannelNotificationListener.prototype = { _logName: "Sync.Resource", - getInterface(aIID) { + getInterface: function(aIID) { return this.QueryInterface(aIID); }, - QueryInterface(aIID) { + QueryInterface: function(aIID) { if (aIID.equals(Ci.nsIBadCertListener2) || aIID.equals(Ci.nsIInterfaceRequestor) || aIID.equals(Ci.nsISupports) || diff --git a/services/sync/modules/service.js b/services/sync/modules/service.js index 82cfef68b77f..b5f390453366 100644 --- a/services/sync/modules/service.js +++ b/services/sync/modules/service.js @@ -303,7 +303,8 @@ Sync11Service.prototype = { if (keysChanged.length) { // Collection keys only. Reset individual engines. this.resetClient(keysChanged); - } else { + } + else { // Default key changed: wipe it all. this.resetClient(); } @@ -542,7 +543,7 @@ Sync11Service.prototype = { * Perform the info fetch as part of a login or key fetch, or * inside engine sync. */ - _fetchInfo(url) { + _fetchInfo: function (url) { let infoURL = url || this.infoURL; this._log.trace("In _fetchInfo: " + infoURL); @@ -618,19 +619,22 @@ Sync11Service.prototype = { if (cryptoResp.success) { let keysChanged = this.handleFetchedKeys(syncKeyBundle, cryptoKeys); return true; - } else if (cryptoResp.status == 404) { + } + else if (cryptoResp.status == 404) { // On failure, ask to generate new keys and upload them. // Fall through to the behavior below. this._log.warn("Got 404 for crypto/keys, but 'crypto' in info/collections. Regenerating."); cryptoKeys = null; - } else { + } + else { // Some other problem. this.status.login = LOGIN_FAILED_SERVER_ERROR; this.errorHandler.checkServerError(cryptoResp); this._log.warn("Got status " + cryptoResp.status + " fetching crypto keys."); return false; } - } catch (ex) { + } + catch (ex) { this._log.warn("Got exception \"" + ex + "\" fetching cryptoKeys."); // TODO: Um, what exceptions might we get here? Should we re-throw any? @@ -638,14 +642,16 @@ Sync11Service.prototype = { if (Utils.isHMACMismatch(ex)) { this.status.login = LOGIN_FAILED_INVALID_PASSPHRASE; this.status.sync = CREDENTIALS_CHANGED; - } else { + } + else { // In the absence of further disambiguation or more precise // failure constants, just report failure. this.status.login = LOGIN_FAILED; } return false; } - } else { + } + else { this._log.info("... 'crypto' is not a reported collection. Generating new keys."); } @@ -662,7 +668,8 @@ Sync11Service.prototype = { // Last-ditch case. return false; - } else { + } + else { // No update needed: we're good! return true; } @@ -881,7 +888,7 @@ Sync11Service.prototype = { for (let engine of [this.clientsEngine].concat(this.engineManager.getAll())) { try { engine.removeClientData(); - } catch (ex) { + } catch(ex) { this._log.warn(`Deleting client data for ${engine.name} failed`, ex); } } @@ -1155,7 +1162,7 @@ Sync11Service.prototype = { this.metaModified = infoResponse.obj.meta; } - let remoteVersion = (meta && meta.payload.storageVersion) ? + let remoteVersion = (meta && meta.payload.storageVersion)? meta.payload.storageVersion : ""; this._log.debug(["Weave Version:", WEAVE_VERSION, "Local Storage:", @@ -1195,11 +1202,13 @@ Sync11Service.prototype = { this._log.info("Wiped server; incompatible metadata: " + remoteVersion); return true; - } else if (remoteVersion > STORAGE_VERSION) { + } + else if (remoteVersion > STORAGE_VERSION) { this.status.sync = VERSION_OUT_OF_DATE; this._log.warn("Upgrade required to access newer storage version."); return false; - } else if (meta.payload.syncID != this.syncID) { + } + else if (meta.payload.syncID != this.syncID) { this._log.info("Sync IDs differ. Local is " + this.syncID + ", remote is " + meta.payload.syncID); this.resetClient(); @@ -1225,7 +1234,8 @@ Sync11Service.prototype = { } return true; - } else { + } + else { if (!this.upgradeSyncKey(meta.payload.syncID)) { this._log.warn("Failed to upgrade sync key. Failing remote setup."); return false; @@ -1285,7 +1295,7 @@ Sync11Service.prototype = { let dateStr = Utils.formatTimestamp(new Date()); this._log.debug("User-Agent: " + Utils.userAgent); this._log.info("Starting sync at " + dateStr); - this._catch(function() { + this._catch(function () { // Make sure we're logged in. if (this._shouldLogin()) { this._log.debug("In sync: should login."); @@ -1293,7 +1303,8 @@ Sync11Service.prototype = { this._log.debug("Not syncing: login returned false."); return; } - } else { + } + else { this._log.trace("In sync: no need to login."); } return this._lockedSync(engineNamesToSync); @@ -1355,7 +1366,7 @@ Sync11Service.prototype = { /** * Upload meta/global, throwing the response on failure. */ - uploadMetaGlobal(meta) { + uploadMetaGlobal: function (meta) { this._log.debug("Uploading meta/global: " + JSON.stringify(meta)); // It would be good to set the X-If-Unmodified-Since header to `timestamp` @@ -1377,7 +1388,7 @@ Sync11Service.prototype = { * * Returns a promise that resolves with the sentinel, or null. */ - getFxAMigrationSentinel() { + getFxAMigrationSentinel: function() { if (this._shouldLogin()) { this._log.debug("In getFxAMigrationSentinel: should login."); if (!this.login()) { @@ -1423,7 +1434,7 @@ Sync11Service.prototype = { * Returns a promise that resolves with a boolean which indicates if the * sentinel was successfully written. */ - setFxAMigrationSentinel(sentinel) { + setFxAMigrationSentinel: function(sentinel) { if (this._shouldLogin()) { this._log.debug("In setFxAMigrationSentinel: should login."); if (!this.login()) { diff --git a/services/sync/modules/stages/declined.js b/services/sync/modules/stages/declined.js index 089d6832f5e7..ff8a141812d7 100644 --- a/services/sync/modules/stages/declined.js +++ b/services/sync/modules/stages/declined.js @@ -21,14 +21,14 @@ Cu.import("resource://gre/modules/Preferences.jsm"); -this.DeclinedEngines = function(service) { +this.DeclinedEngines = function (service) { this._log = Log.repository.getLogger("Sync.Declined"); this._log.level = Log.Level[new Preferences(PREFS_BRANCH).get("log.logger.declined")]; this.service = service; } this.DeclinedEngines.prototype = { - updateDeclined(meta, engineManager = this.service.engineManager) { + updateDeclined: function (meta, engineManager=this.service.engineManager) { let enabled = new Set(engineManager.getEnabled().map(e => e.name)); let known = new Set(engineManager.getAll().map(e => e.name)); let remoteDeclined = new Set(meta.payload.declined || []); @@ -62,9 +62,9 @@ this.DeclinedEngines.prototype = { if (undecided.size) { let subject = { declined: newDeclined, - enabled, - known, - undecided, + enabled: enabled, + known: known, + undecided: undecided, }; CommonUtils.nextTick(() => { Observers.notify("weave:engines:notdeclined", subject); diff --git a/services/sync/modules/stages/enginesync.js b/services/sync/modules/stages/enginesync.js index 580f3ded852d..b22307f4218a 100644 --- a/services/sync/modules/stages/enginesync.js +++ b/services/sync/modules/stages/enginesync.js @@ -131,7 +131,8 @@ EngineSynchronizer.prototype = { this.onComplete(new Error("Remote setup failed after processing commands.")); return; } - } finally { + } + finally { // Always immediately attempt to push back the local client (now // without commands). // Note that we don't abort here; if there's a 401 because we've @@ -318,7 +319,8 @@ EngineSynchronizer.prototype = { _syncEngine: function _syncEngine(engine) { try { engine.sync(); - } catch (e) { + } + catch(e) { if (e.status == 401) { // Maybe a 401, cluster update perhaps needed? // We rely on ErrorHandler observing the sync failure notification to @@ -339,7 +341,7 @@ EngineSynchronizer.prototype = { return true; }, - _updateEnabledFromMeta(meta, numClients, engineManager = this.service.engineManager) { + _updateEnabledFromMeta: function (meta, numClients, engineManager=this.service.engineManager) { this._log.info("Updating enabled engines: " + numClients + " clients."); @@ -443,7 +445,7 @@ EngineSynchronizer.prototype = { this.service._ignorePrefObserver = false; }, - _updateEnabledEngines() { + _updateEnabledEngines: function () { let meta = this.service.recordManager.get(this.service.metaURL); let numClients = this.service.scheduler.numClients; let engineManager = this.service.engineManager; diff --git a/services/sync/modules/status.js b/services/sync/modules/status.js index e7c9f7956beb..100bc79652cb 100644 --- a/services/sync/modules/status.js +++ b/services/sync/modules/status.js @@ -98,9 +98,9 @@ this.Status = { // value, so we can't trivially debug-print Status as JSON. toString: function toString() { return ""; + ", sync: " + Status.sync + ">"; }, checkSetup: function checkSetup() { diff --git a/services/sync/modules/telemetry.js b/services/sync/modules/telemetry.js index a3e74c629c41..46893b70d105 100644 --- a/services/sync/modules/telemetry.js +++ b/services/sync/modules/telemetry.js @@ -598,10 +598,12 @@ class SyncTelemetryImpl { if (extra) { event.push(extra); } - } else if (extra) { + } else { + if (extra) { event.push(null); // a null for the empty value. event.push(extra); } + } this.events.push(event); } diff --git a/services/sync/modules/userapi.js b/services/sync/modules/userapi.js index a33ce4bec4f9..e906440bd1df 100644 --- a/services/sync/modules/userapi.js +++ b/services/sync/modules/userapi.js @@ -114,7 +114,7 @@ UserAPI10Client.prototype = { request.put(body); }, - _getRequest: function _getRequest(username, path, password = null) { + _getRequest: function _getRequest(username, path, password=null) { let url = this.baseURI + username + path; let request = new RESTRequest(url); @@ -135,13 +135,13 @@ UserAPI10Client.prototype = { let body = request.response.body; if (body == "0") { cb(null, false); - + return; } else if (body == "1") { cb(null, true); - + return; } else { cb(new Error("Unknown response from server: " + body), null); - + return; } }, @@ -178,7 +178,7 @@ UserAPI10Client.prototype = { } cb(error, null); - + return; }, _onChangePassword: function _onChangePassword(cb, request, error) { @@ -218,7 +218,7 @@ UserAPI10Client.prototype = { error.body = response.body; cb(error, null); - + return; }, }; Object.freeze(UserAPI10Client.prototype); diff --git a/services/sync/modules/util.js b/services/sync/modules/util.js index 6c0d475756a0..7deb0f18e93b 100644 --- a/services/sync/modules/util.js +++ b/services/sync/modules/util.js @@ -93,7 +93,8 @@ this.Utils = { return function WrappedCatch() { try { return func.call(thisArg); - } catch (ex) { + } + catch(ex) { thisArg._log.debug("Exception calling " + (func.name || "anonymous function"), ex); if (exceptionCallback) { return exceptionCallback.call(thisArg, ex); @@ -118,7 +119,8 @@ this.Utils = { try { return func.call(thisArg); - } finally { + } + finally { thisArg.unlock(); } }; @@ -164,7 +166,8 @@ this.Utils = { let ret = func.call(thisArg); notify("finish", ret); return ret; - } catch (ex) { + } + catch(ex) { notify("error", ex); throw ex; } @@ -204,14 +207,14 @@ this.Utils = { // Create a getter if it doesn't exist yet if (!prot.__lookupGetter__(prop)) { - prot.__defineGetter__(prop, function() { + prot.__defineGetter__(prop, function () { return this[defer][prop]; }); } // Create a setter if it doesn't exist yet if (!prot.__lookupSetter__(prop)) { - prot.__defineSetter__(prop, function(val) { + prot.__defineSetter__(prop, function (val) { this[defer][prop] = val; }); } @@ -361,9 +364,11 @@ this.Utils = { if (e instanceof OS.File.Error && e.becauseNoSuchFile) { // Ignore non-existent files, but explicitly return null. json = null; - } else if (that._log) { + } else { + if (that._log) { that._log.debug("Failed to load json", e); } + } } if (callback) { @@ -497,7 +502,7 @@ this.Utils = { * take user input for account/username, cleaning up appropriately. */ - isPassphrase(s) { + isPassphrase: function(s) { if (s) { return /^[abcdefghijkmnpqrstuvwxyz23456789]{26}$/.test(Utils.normalizePassphrase(s)); } @@ -527,7 +532,7 @@ this.Utils = { return data + "-"; // Hyphenate it. - let y = data.substr(0, 1); + let y = data.substr(0,1); let z = data.substr(1).replace(/(.{1,5})/g, "-$1"); // Correct length? We're done. @@ -624,7 +629,7 @@ this.Utils = { try { sdr.encryptString("bacon"); return true; - } catch (e) {} + } catch(e) {} return false; }, @@ -649,7 +654,7 @@ this.Utils = { * In general, these hosts will not have their passwords synced, will be * reset when we drop sync credentials, etc. */ - getSyncCredentialsHosts() { + getSyncCredentialsHosts: function() { let result = new Set(this.getSyncCredentialsHostsLegacy()); for (let host of this.getSyncCredentialsHostsFxA()) { result.add(host); @@ -660,7 +665,7 @@ this.Utils = { /* * Get the "legacy" identity hosts. */ - getSyncCredentialsHostsLegacy() { + getSyncCredentialsHostsLegacy: function() { // the legacy sync host return new Set([PWDMGR_HOST]); }, @@ -668,7 +673,7 @@ this.Utils = { /* * Get the FxA identity hosts. */ - getSyncCredentialsHostsFxA() { + getSyncCredentialsHostsFxA: function() { let result = new Set(); // the FxA host result.add(FxAccountsCommon.FXA_PWDMGR_HOST); @@ -779,7 +784,7 @@ this.Str = {}; XPCOMUtils.defineLazyGetter(Str, lazy, Utils.lazyStrings(lazy)); }); -Svc.Obs.add("xpcom-shutdown", function() { +Svc.Obs.add("xpcom-shutdown", function () { for (let name in Svc) delete Svc[name]; }); diff --git a/services/sync/services-sync.js b/services/sync/services-sync.js index 5645a5e1006f..f4167c1ce795 100644 --- a/services/sync/services-sync.js +++ b/services/sync/services-sync.js @@ -13,13 +13,13 @@ pref("services.sync.syncKeyHelpURL", "https://services.mozilla.com/help/synckey" pref("services.sync.lastversion", "firstrun"); pref("services.sync.sendVersionInfo", true); -pref("services.sync.scheduler.eolInterval", 604800); // 1 week -pref("services.sync.scheduler.idleInterval", 3600); // 1 hour -pref("services.sync.scheduler.activeInterval", 600); // 10 minutes -pref("services.sync.scheduler.immediateInterval", 90); // 1.5 minutes -pref("services.sync.scheduler.idleTime", 300); // 5 minutes +pref("services.sync.scheduler.eolInterval", 604800); // 1 week +pref("services.sync.scheduler.idleInterval", 3600); // 1 hour +pref("services.sync.scheduler.activeInterval", 600); // 10 minutes +pref("services.sync.scheduler.immediateInterval", 90); // 1.5 minutes +pref("services.sync.scheduler.idleTime", 300); // 5 minutes -pref("services.sync.scheduler.fxa.singleDeviceInterval", 3600); // 1 hour +pref("services.sync.scheduler.fxa.singleDeviceInterval", 3600); // 1 hour pref("services.sync.scheduler.sync11.singleDeviceInterval", 86400); // 1 day pref("services.sync.errorhandler.networkFailureReportTimeout", 1209600); // 2 weeks diff --git a/services/sync/tests/tps/mozmill_sanity.js b/services/sync/tests/tps/mozmill_sanity.js index c9c9391aa80c..fbaed8f257ae 100644 --- a/services/sync/tests/tps/mozmill_sanity.js +++ b/services/sync/tests/tps/mozmill_sanity.js @@ -21,7 +21,7 @@ var testTestStep = function() { TPS.Sync(ACTIONS.ACTION_SYNC_WIPE_CLIENT); } -var teardownTest = function() { +var teardownTest = function () { assert.ok(true, "teardownTest passes"); } diff --git a/services/sync/tests/tps/test_bug563989.js b/services/sync/tests/tps/test_bug563989.js index 99daf7522f86..faf63de659c2 100644 --- a/services/sync/tests/tps/test_bug563989.js +++ b/services/sync/tests/tps/test_bug563989.js @@ -82,7 +82,7 @@ Phase('phase1', [ [Sync], ]); -// Sync to profile2 and verify that the bookmarks are present. Delete +// Sync to profile2 and verify that the bookmarks are present. Delete // some bookmarks, and verify that they're not present, but don't sync again. Phase('phase2', [ [Sync], diff --git a/services/sync/tests/tps/test_bug575423.js b/services/sync/tests/tps/test_bug575423.js index 961e8186e3d7..d187c487815b 100644 --- a/services/sync/tests/tps/test_bug575423.js +++ b/services/sync/tests/tps/test_bug575423.js @@ -58,10 +58,10 @@ var history2 = [ { uri: "http://www.google.com/language_tools?hl=en", title: "Language Tools", visits: [ - { type: 1, + { type: 1, date: 0 }, - { type: 2, + { type: 2, date: -40 } ] diff --git a/services/sync/tests/tps/test_formdata.js b/services/sync/tests/tps/test_formdata.js index 86db93ab9cdb..decb58dd89cb 100644 --- a/services/sync/tests/tps/test_formdata.js +++ b/services/sync/tests/tps/test_formdata.js @@ -80,7 +80,7 @@ Phase('phase2', [ Phase('phase3', [ [Sync], [Formdata.delete, formdata_delete], -// [Formdata.verifyNot, formdata_delete], +//[Formdata.verifyNot, formdata_delete], [Formdata.verify, formdata2], // add new data after the first Sync, ensuring the tracker works. [Formdata.add, formdata_new], diff --git a/services/sync/tests/tps/test_sync.js b/services/sync/tests/tps/test_sync.js index c74a40c67423..c9dd89cb5abb 100644 --- a/services/sync/tests/tps/test_sync.js +++ b/services/sync/tests/tps/test_sync.js @@ -32,7 +32,7 @@ var bookmarks_initial = { title: "Bugzilla", keyword: "bz", changes: { - keyword: "bugzilla" + keyword: "bugzilla" } }, { folder: "foldera" }, diff --git a/services/sync/tests/unit/fake_login_manager.js b/services/sync/tests/unit/fake_login_manager.js index cae126514c37..6f3148c45a7d 100644 --- a/services/sync/tests/unit/fake_login_manager.js +++ b/services/sync/tests/unit/fake_login_manager.js @@ -27,9 +27,9 @@ function FakeLoginManager(fakeLogins) { // Use a fake nsILoginManager object. delete Services.logins; Services.logins = { - removeAllLogins() { self.fakeLogins = []; }, - getAllLogins() { return self.fakeLogins; }, - addLogin(login) { + removeAllLogins: function() { self.fakeLogins = []; }, + getAllLogins: function() { return self.fakeLogins; }, + addLogin: function(login) { getTestLogger().info("nsILoginManager.addLogin() called " + "with hostname '" + login.hostname + "'."); self.fakeLogins.push(login); diff --git a/services/sync/tests/unit/head_helpers.js b/services/sync/tests/unit/head_helpers.js index 30f0120d9dcf..5b35ad3293ae 100644 --- a/services/sync/tests/unit/head_helpers.js +++ b/services/sync/tests/unit/head_helpers.js @@ -37,7 +37,7 @@ XPCOMUtils.defineLazyGetter(this, 'SyncPingValidator', function() { }); var provider = { - getFile(prop, persistent) { + getFile: function(prop, persistent) { persistent.value = true; switch (prop) { case "ExtPrefDL": @@ -157,7 +157,7 @@ function installAddon(name) { */ function uninstallAddon(addon) { let cb = Async.makeSyncCallback(); - let listener = {onUninstalled(uninstalled) { + let listener = {onUninstalled: function(uninstalled) { if (uninstalled.id == addon.id) { AddonManager.removeAddonListener(listener); cb(uninstalled); @@ -169,7 +169,7 @@ function uninstallAddon(addon) { Async.waitForSyncCallback(cb); } -function generateNewKeys(collectionKeys, collections = null) { +function generateNewKeys(collectionKeys, collections=null) { let wbo = collectionKeys.generateNewKeysWBO(collections); let modified = new_timestamp(); collectionKeys.setContents(wbo.cleartext, modified); @@ -179,12 +179,12 @@ function generateNewKeys(collectionKeys, collections = null) { // These reflect part of the internal structure of TabEngine, // and stub part of Service.wm. -function mockShouldSkipWindow(win) { +function mockShouldSkipWindow (win) { return win.closed || win.mockIsPrivate; } -function mockGetTabState(tab) { +function mockGetTabState (tab) { return tab; } @@ -204,7 +204,7 @@ function mockGetWindowEnumerator(url, numWindows, numTabs, indexes, moreURLs) { closed: false, mockIsPrivate: false, gBrowser: { - tabs, + tabs: tabs, }, }; elements.push(win); @@ -229,7 +229,7 @@ function mockGetWindowEnumerator(url, numWindows, numTabs, indexes, moreURLs) { tabs: [], }, }); - + elements.push({ closed: false, mockIsPrivate: true, @@ -239,10 +239,10 @@ function mockGetWindowEnumerator(url, numWindows, numTabs, indexes, moreURLs) { }); return { - hasMoreElements() { + hasMoreElements: function () { return elements.length; }, - getNext() { + getNext: function () { return elements.shift(); }, }; @@ -450,7 +450,7 @@ function promiseOneObserver(topic, callback) { return new Promise((resolve, reject) => { let observer = function(subject, data) { Svc.Obs.remove(topic, observer); - resolve({ subject, data }); + resolve({ subject: subject, data: data }); } Svc.Obs.add(topic, observer) }); diff --git a/services/sync/tests/unit/head_http_server.js b/services/sync/tests/unit/head_http_server.js index 95df42a0aed8..26f62310c323 100644 --- a/services/sync/tests/unit/head_http_server.js +++ b/services/sync/tests/unit/head_http_server.js @@ -72,17 +72,17 @@ ServerWBO.prototype = { return JSON.parse(this.payload); }, - get() { + get: function() { return JSON.stringify(this, ["id", "modified", "payload"]); }, - put(input) { + put: function(input) { input = JSON.parse(input); this.payload = input.payload; this.modified = new_timestamp(); }, - delete() { + delete: function() { delete this.payload; delete this.modified; }, @@ -90,7 +90,7 @@ ServerWBO.prototype = { // This handler sets `newModified` on the response body if the collection // timestamp has changed. This allows wrapper handlers to extract information // that otherwise would exist only in the body stream. - handler() { + handler: function() { let self = this; return function(request, response) { @@ -98,7 +98,7 @@ ServerWBO.prototype = { var status = "OK"; var body; - switch (request.method) { + switch(request.method) { case "GET": if (self.payload) { body = self.get(); @@ -216,8 +216,8 @@ ServerCollection.prototype = { * * @return an array of the payloads of each stored WBO. */ - payloads() { - return this.wbos().map(function(wbo) { + payloads: function () { + return this.wbos().map(function (wbo) { return JSON.parse(JSON.parse(wbo.payload).ciphertext); }); }, @@ -267,13 +267,13 @@ ServerCollection.prototype = { delete this._wbos[id]; }, - _inResultSet(wbo, options) { + _inResultSet: function(wbo, options) { return wbo.payload && (!options.ids || (options.ids.indexOf(wbo.id) != -1)) && (!options.newer || (wbo.modified > options.newer)); }, - count(options) { + count: function(options) { options = options || {}; let c = 0; for (let [id, wbo] of Object.entries(this._wbos)) { @@ -284,7 +284,7 @@ ServerCollection.prototype = { return c; }, - get(options) { + get: function(options) { let result; if (options.full) { let data = []; @@ -330,7 +330,7 @@ ServerCollection.prototype = { return result; }, - post(input) { + post: function(input) { input = JSON.parse(input); let success = []; let failed = {}; @@ -355,11 +355,11 @@ ServerCollection.prototype = { } } return {modified: new_timestamp(), - success, - failed}; + success: success, + failed: failed}; }, - delete(options) { + delete: function(options) { let deleted = []; for (let [id, wbo] of Object.entries(this._wbos)) { if (this._inResultSet(wbo, options)) { @@ -373,7 +373,7 @@ ServerCollection.prototype = { // This handler sets `newModified` on the response body if the collection // timestamp has changed. - handler() { + handler: function() { let self = this; return function(request, response) { @@ -407,7 +407,7 @@ ServerCollection.prototype = { options.offset = parseInt(options.offset, 10); } - switch (request.method) { + switch(request.method) { case "GET": body = self.get(options, request); // see http://moz-services-docs.readthedocs.io/en/latest/storage/apis-1.5.html @@ -506,7 +506,7 @@ function track_collections_helper() { */ function info_collections(request, response) { let body = "Error."; - switch (request.method) { + switch(request.method) { case "GET": body = JSON.stringify(collections); break; @@ -528,9 +528,9 @@ function track_collections_helper() { "update_collection": update_collection}; } -// ===========================================================================// +//===========================================================================// // httpd.js-based Sync server. // -// ===========================================================================// +//===========================================================================// /** * In general, the preferred way of using SyncServer is to directly introspect @@ -655,7 +655,7 @@ SyncServer.prototype = { throw new Error("User already exists."); } this.users[username] = { - password, + password: password, collections: {} }; return this.user(username); @@ -763,16 +763,16 @@ SyncServer.prototype = { let collection = this.getCollection.bind(this, username); let createCollection = this.createCollection.bind(this, username); let createContents = this.createContents.bind(this, username); - let modified = function(collectionName) { + let modified = function (collectionName) { return collection(collectionName).timestamp; } let deleteCollections = this.deleteCollections.bind(this, username); return { - collection, - createCollection, - createContents, - deleteCollections, - modified + collection: collection, + createCollection: createCollection, + createContents: createContents, + deleteCollections: deleteCollections, + modified: modified }; }, diff --git a/services/sync/tests/unit/test_addon_utils.js b/services/sync/tests/unit/test_addon_utils.js index a048e10ae32f..998c8dbe1461 100644 --- a/services/sync/tests/unit/test_addon_utils.js +++ b/services/sync/tests/unit/test_addon_utils.js @@ -19,7 +19,7 @@ prefs.set("extensions.getAddons.get.url", loadAddonTestFunctions(); startupManager(); -function createAndStartHTTPServer(port = HTTP_PORT) { +function createAndStartHTTPServer(port=HTTP_PORT) { try { let server = new HttpServer(); @@ -81,7 +81,7 @@ add_test(function test_ignore_untrusted_source_uris() { for (let s of bad) { let sourceURI = ioService.newURI(s); - let addon = {sourceURI, name: "bad", id: "bad"}; + let addon = {sourceURI: sourceURI, name: "bad", id: "bad"}; let canInstall = AddonUtils.canInstallAddon(addon); do_check_false(canInstall, "Correctly rejected a bad URL"); @@ -89,7 +89,7 @@ add_test(function test_ignore_untrusted_source_uris() { for (let s of good) { let sourceURI = ioService.newURI(s); - let addon = {sourceURI, name: "good", id: "good"}; + let addon = {sourceURI: sourceURI, name: "good", id: "good"}; let canInstall = AddonUtils.canInstallAddon(addon); do_check_true(canInstall, "Correctly accepted a good URL"); @@ -115,12 +115,12 @@ add_test(function test_source_uri_rewrite() { installCalled = true; - AddonUtils.getInstallFromSearchResult(addon, function(error, install) { + AddonUtils.getInstallFromSearchResult(addon, function (error, install) { do_check_null(error); do_check_eq(SERVER_ADDRESS + "/require.xpi?src=sync", install.sourceURI.spec); - cb(null, {id: addon.id, addon, install}); + cb(null, {id: addon.id, addon: addon, install: install}); }, false); }; diff --git a/services/sync/tests/unit/test_addons_engine.js b/services/sync/tests/unit/test_addons_engine.js index 4f180d3db7dc..048635f15890 100644 --- a/services/sync/tests/unit/test_addons_engine.js +++ b/services/sync/tests/unit/test_addons_engine.js @@ -183,7 +183,7 @@ add_task(async function test_disabled_install_semantics() { let now = Date.now() / 1000; let record = encryptPayload({ - id, + id: id, applicationID: Services.appinfo.ID, addonID: ADDON_ID, enabled: false, diff --git a/services/sync/tests/unit/test_addons_store.js b/services/sync/tests/unit/test_addons_store.js index 2af7e12ed4fc..aef8b01d8f74 100644 --- a/services/sync/tests/unit/test_addons_store.js +++ b/services/sync/tests/unit/test_addons_store.js @@ -55,9 +55,9 @@ var reconciler = engine._reconciler; */ function createRecordForThisApp(id, addonId, enabled, deleted) { return { - id, + id: id, addonID: addonId, - enabled, + enabled: enabled, deleted: !!deleted, applicationID: Services.appinfo.ID, source: "amo" @@ -443,7 +443,7 @@ add_test(function test_create_bad_install() { // to be tricky to distinguish a 404 from other transient network errors // where we do want the addon to end up in |failed|. // This is being tracked in bug 1284778. - // do_check_eq(0, failed.length); + //do_check_eq(0, failed.length); let addon = getAddonFromAddonManagerByID(id); do_check_eq(null, addon); diff --git a/services/sync/tests/unit/test_addons_tracker.js b/services/sync/tests/unit/test_addons_tracker.js index 55b64d414537..01bf37ab9eee 100644 --- a/services/sync/tests/unit/test_addons_tracker.js +++ b/services/sync/tests/unit/test_addons_tracker.js @@ -125,14 +125,14 @@ add_test(function test_track_user_disable() { let cb = Async.makeSyncCallback(); let listener = { - onDisabled(disabled) { + onDisabled: function(disabled) { _("onDisabled"); if (disabled.id == addon.id) { AddonManager.removeAddonListener(listener); cb(); } }, - onDisabling(disabling) { + onDisabling: function(disabling) { _("onDisabling add-on"); } }; diff --git a/services/sync/tests/unit/test_bookmark_batch_fail.js b/services/sync/tests/unit/test_bookmark_batch_fail.js index 57ad88f6138f..cf52fefb70ae 100644 --- a/services/sync/tests/unit/test_bookmark_batch_fail.js +++ b/services/sync/tests/unit/test_bookmark_batch_fail.js @@ -15,7 +15,8 @@ function run_test() { _("Try calling the sync that should throw right away"); engine._sync(); do_throw("Should have failed sync!"); - } catch (ex) { + } + catch(ex) { _("Making sure what we threw ended up as the exception:", ex); do_check_eq(ex, "FAIL!"); } diff --git a/services/sync/tests/unit/test_bookmark_duping.js b/services/sync/tests/unit/test_bookmark_duping.js index cea77c59755c..02aed3318810 100644 --- a/services/sync/tests/unit/test_bookmark_duping.js +++ b/services/sync/tests/unit/test_bookmark_duping.js @@ -107,7 +107,7 @@ async function validate(collection, expectedFailures = []) { let summary = problems.getSummary().filter(prob => prob.count != 0); // split into 2 arrays - expected and unexpected. - let isInExpectedFailures = elt => { + let isInExpectedFailures = elt => { for (let i = 0; i < expectedFailures.length; i++) { if (elt.name == expectedFailures[i].name && elt.count == expectedFailures[i].count) { return true; diff --git a/services/sync/tests/unit/test_bookmark_engine.js b/services/sync/tests/unit/test_bookmark_engine.js index 7cf8a463b17d..81614b4da892 100644 --- a/services/sync/tests/unit/test_bookmark_engine.js +++ b/services/sync/tests/unit/test_bookmark_engine.js @@ -346,7 +346,7 @@ add_task(async function test_processIncoming_error_orderChildren() { let error; try { await sync_engine_and_validate_telem(engine, true) - } catch (ex) { + } catch(ex) { error = ex; } ok(!!error); @@ -419,7 +419,7 @@ add_task(async function test_restorePromptsReupload() { let error; try { await sync_engine_and_validate_telem(engine, false); - } catch (ex) { + } catch(ex) { error = ex; _("Got error: " + Log.exceptionStr(ex)); } @@ -427,7 +427,7 @@ add_task(async function test_restorePromptsReupload() { _("Verify that there's only one bookmark on the server, and it's Thunderbird."); // Of course, there's also the Bookmarks Toolbar and Bookmarks Menu... - let wbos = collection.keys(function(id) { + let wbos = collection.keys(function (id) { return ["menu", "toolbar", "mobile", "unfiled", folder1_guid].indexOf(id) == -1; }); do_check_eq(wbos.length, 1); @@ -463,7 +463,7 @@ add_task(async function test_restorePromptsReupload() { _("Sync again. This'll wipe bookmarks from the server."); try { await sync_engine_and_validate_telem(engine, false); - } catch (ex) { + } catch(ex) { error = ex; _("Got error: " + Log.exceptionStr(ex)); } @@ -472,15 +472,15 @@ add_task(async function test_restorePromptsReupload() { _("Verify that there's only one bookmark on the server, and it's Firefox."); // Of course, there's also the Bookmarks Toolbar and Bookmarks Menu... let payloads = server.user("foo").collection("bookmarks").payloads(); - let bookmarkWBOs = payloads.filter(function(wbo) { + let bookmarkWBOs = payloads.filter(function (wbo) { return wbo.type == "bookmark"; }); - let folderWBOs = payloads.filter(function(wbo) { + let folderWBOs = payloads.filter(function (wbo) { return ((wbo.type == "folder") && - (wbo.id != "menu") && - (wbo.id != "toolbar") && - (wbo.id != "unfiled") && - (wbo.id != "mobile")); + (wbo.id != "menu") && + (wbo.id != "toolbar") && + (wbo.id != "unfiled") && + (wbo.id != "mobile")); }); do_check_eq(bookmarkWBOs.length, 1); @@ -716,7 +716,7 @@ add_task(async function test_misreconciled_root() { let rec = new FakeRecord(BookmarkFolder, to_apply); let encrypted = encryptPayload(rec.cleartext); - encrypted.decrypt = function() { + encrypted.decrypt = function () { for (let x in rec) { encrypted[x] = rec[x]; } @@ -727,7 +727,7 @@ add_task(async function test_misreconciled_root() { getBatched() { return this.get(); }, - get() { + get: function () { this.recordHandler(encrypted); return {success: true} }, diff --git a/services/sync/tests/unit/test_bookmark_smart_bookmarks.js b/services/sync/tests/unit/test_bookmark_smart_bookmarks.js index 43796f7fa957..d87e9e757af4 100644 --- a/services/sync/tests/unit/test_bookmark_smart_bookmarks.js +++ b/services/sync/tests/unit/test_bookmark_smart_bookmarks.js @@ -111,7 +111,7 @@ add_task(async function test_annotation_uploaded() { try { await sync_engine_and_validate_telem(engine, false); - let wbos = collection.keys(function(id) { + let wbos = collection.keys(function (id) { return ["menu", "toolbar", "mobile", "unfiled"].indexOf(id) == -1; }); do_check_eq(wbos.length, 1); diff --git a/services/sync/tests/unit/test_bookmark_store.js b/services/sync/tests/unit/test_bookmark_store.js index e0f76d7af168..47296fe836b0 100644 --- a/services/sync/tests/unit/test_bookmark_store.js +++ b/services/sync/tests/unit/test_bookmark_store.js @@ -108,7 +108,7 @@ add_test(function test_bookmark_create() { let error; try { PlacesUtils.annotations.getItemAnnotation(id, "bookmarkProperties/description"); - } catch (ex) { + } catch(ex) { error = ex; } do_check_eq(error.result, Cr.NS_ERROR_NOT_AVAILABLE); @@ -144,7 +144,7 @@ add_test(function test_bookmark_update() { store.applyIncoming(record); _("Verify that the values have been cleared."); - do_check_throws(function() { + do_check_throws(function () { PlacesUtils.annotations.getItemAnnotation( bmk1_id, "bookmarkProperties/description"); }, Cr.NS_ERROR_NOT_AVAILABLE); @@ -261,7 +261,7 @@ add_task(async function test_deleted() { let error; try { PlacesUtils.bookmarks.getBookmarkURI(bmk1_id); - } catch (ex) { + } catch(ex) { error = ex; } do_check_eq(error.result, Cr.NS_ERROR_ILLEGAL_VALUE); @@ -361,7 +361,7 @@ add_test(function test_orphan() { let error; try { PlacesUtils.annotations.getItemAnnotation(bmk1_id, PARENT_ANNO); - } catch (ex) { + } catch(ex) { error = ex; } do_check_eq(error.result, Cr.NS_ERROR_NOT_AVAILABLE); @@ -424,7 +424,7 @@ add_test(function test_empty_query_doesnt_die() { delete record.folderName; store.applyIncoming(record); - + run_next_test(); }); diff --git a/services/sync/tests/unit/test_bookmark_tracker.js b/services/sync/tests/unit/test_bookmark_tracker.js index e6c3cc696877..4d791d87f032 100644 --- a/services/sync/tests/unit/test_bookmark_tracker.js +++ b/services/sync/tests/unit/test_bookmark_tracker.js @@ -216,7 +216,7 @@ add_task(async function test_batch_tracking() { await startTracking(); PlacesUtils.bookmarks.runInBatchMode({ - runBatched() { + runBatched: function() { let folder = PlacesUtils.bookmarks.createFolder( PlacesUtils.bookmarks.bookmarksMenuFolder, "Test Folder", PlacesUtils.bookmarks.DEFAULT_INDEX); @@ -240,10 +240,10 @@ add_task(async function test_nested_batch_tracking() { await startTracking(); PlacesUtils.bookmarks.runInBatchMode({ - runBatched() { + runBatched: function() { PlacesUtils.bookmarks.runInBatchMode({ - runBatched() { + runBatched: function() { let folder = PlacesUtils.bookmarks.createFolder( PlacesUtils.bookmarks.bookmarksMenuFolder, "Test Folder", PlacesUtils.bookmarks.DEFAULT_INDEX); @@ -276,7 +276,7 @@ add_task(async function test_tracker_sql_batching() { await startTracking(); PlacesUtils.bookmarks.runInBatchMode({ - runBatched() { + runBatched: function() { for (let i = 0; i < numItems; i++) { let syncBmkID = PlacesUtils.bookmarks.insertBookmark( PlacesUtils.bookmarks.unfiledBookmarksFolder, diff --git a/services/sync/tests/unit/test_bookmark_validator.js b/services/sync/tests/unit/test_bookmark_validator.js index 48dbd8825b52..48ebfd8df317 100644 --- a/services/sync/tests/unit/test_bookmark_validator.js +++ b/services/sync/tests/unit/test_bookmark_validator.js @@ -105,7 +105,7 @@ add_test(function test_isr_duplicatesAndMissingIDs() { run_next_test(); }); -add_test(function test_isr_duplicateChildren() { +add_test(function test_isr_duplicateChildren() { let c = inspectServerRecords([ {id: 'A', type: 'folder', parentid: 'places', children: ['B', 'B']}, {id: 'B', type: 'bookmark', parentid: 'A'}, diff --git a/services/sync/tests/unit/test_browserid_identity.js b/services/sync/tests/unit/test_browserid_identity.js index 18a696d27142..01a22111b1d0 100644 --- a/services/sync/tests/unit/test_browserid_identity.js +++ b/services/sync/tests/unit/test_browserid_identity.js @@ -46,7 +46,7 @@ function MockFxAccounts() { let fxa = new FxAccounts({ _now_is: Date.now(), - now() { + now: function () { return this._now_is; }, @@ -67,7 +67,7 @@ function run_test() { Log.repository.getLogger("Sync.Identity").level = Log.Level.Trace; Log.repository.getLogger("Sync.BrowserIDManager").level = Log.Level.Trace; run_next_test(); -} +}; add_test(function test_initial_state() { _("Verify initial state"); @@ -387,7 +387,7 @@ add_test(function test_sha256() { "ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8"] ]; let bidUser = new BrowserIDManager(); - for (let [input, output] of vectors) { + for (let [input,output] of vectors) { do_check_eq(CommonUtils.bytesAsHex(bidUser._sha256(input)), output); } run_next_test(); @@ -705,7 +705,7 @@ add_task(async function test_getKeysMissing() { // Mock a fxAccounts object that returns no keys let fxa = new FxAccounts({ - fetchAndUnwrapKeys() { + fetchAndUnwrapKeys: function () { return Promise.resolve({}); }, fxAccountsClient: new MockFxAccountsClient(), @@ -757,7 +757,7 @@ add_task(async function test_signedInUserMissing() { configureFxAccountIdentity(browseridManager, identityConfig); let fxa = new FxAccounts({ - fetchAndUnwrapKeys() { + fetchAndUnwrapKeys: function () { return Promise.resolve({}); }, fxAccountsClient: new MockFxAccountsClient(), @@ -795,14 +795,14 @@ async function initializeIdentityWithHAWKResponseFactory(config, cbGetResponse) this._uri = uri; this._credentials = credentials; this._extra = extra; - } + }; MockRESTRequest.prototype = { - setHeader() {}, - post(data, callback) { + setHeader: function() {}, + post: function(data, callback) { this.response = cbGetResponse("post", data, this._uri, this._credentials, this._extra); callback.call(this); }, - get(callback) { + get: function(callback) { // Skip /status requests (browserid_identity checks if the account still // exists after an auth error) if (this._uri.startsWith("http://mockedserver:9999/account/status")) { @@ -858,7 +858,7 @@ function getTimestamp(hawkAuthHeader) { return parseInt(/ts="(\d+)"/.exec(hawkAuthHeader)[1], 10) * SECOND_MS; } -function getTimestampDelta(hawkAuthHeader, now = Date.now()) { +function getTimestampDelta(hawkAuthHeader, now=Date.now()) { return Math.abs(getTimestamp(hawkAuthHeader) - now); } @@ -868,11 +868,11 @@ function mockTokenServer(func) { requestLog.addAppender(new Log.DumpAppender()); requestLog.level = Log.Level.Trace; } - function MockRESTRequest(url) {} + function MockRESTRequest(url) {}; MockRESTRequest.prototype = { _log: requestLog, - setHeader() {}, - get(callback) { + setHeader: function() {}, + get: function(callback) { this.response = func(); callback.call(this); } diff --git a/services/sync/tests/unit/test_clients_engine.js b/services/sync/tests/unit/test_clients_engine.js index 8a95b93e5c1a..1244eb9bbdca 100644 --- a/services/sync/tests/unit/test_clients_engine.js +++ b/services/sync/tests/unit/test_clients_engine.js @@ -61,10 +61,10 @@ add_task(async function test_bad_hmac() { let deletedItems = []; let callback = { __proto__: SyncServerCallback, - onItemDeleted(username, coll, wboID) { + onItemDeleted: function (username, coll, wboID) { deletedItems.push(coll + "/" + wboID); }, - onCollectionDeleted(username, coll) { + onCollectionDeleted: function (username, coll) { deletedCollections.push(coll); } } @@ -1452,7 +1452,7 @@ add_task(async function test_command_sync() { engine._notifyCollectionChanged = (ids) => (notifiedIds = ids); _("Syncing."); engine._sync(); - deepEqual(notifiedIds, ["fxa-fake-guid-00", "fxa-fake-guid-01"]); + deepEqual(notifiedIds, ["fxa-fake-guid-00","fxa-fake-guid-01"]); ok(!notifiedIds.includes(engine.getClientFxaDeviceId(engine.localID)), "We never notify the local device"); diff --git a/services/sync/tests/unit/test_collections_recovery.js b/services/sync/tests/unit/test_collections_recovery.js index 7d5011b45e7a..dde230a44ec4 100644 --- a/services/sync/tests/unit/test_collections_recovery.js +++ b/services/sync/tests/unit/test_collections_recovery.js @@ -13,7 +13,7 @@ add_identity_test(this, async function test_missing_crypto_collection() { let empty = false; function maybe_empty(handler) { - return function(request, response) { + return function (request, response) { if (empty) { let body = "{}"; response.setStatusLine(request.httpVersion, 200, "OK"); @@ -27,7 +27,7 @@ add_identity_test(this, async function test_missing_crypto_collection() { let handlers = { "/1.1/johndoe/info/collections": maybe_empty(johnHelper.handler), "/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()), - "/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()) + "/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()) }; let collections = ["clients", "bookmarks", "forms", "history", "passwords", "prefs", "tabs"]; diff --git a/services/sync/tests/unit/test_corrupt_keys.js b/services/sync/tests/unit/test_corrupt_keys.js index d37bb183574b..f64f11912965 100644 --- a/services/sync/tests/unit/test_corrupt_keys.js +++ b/services/sync/tests/unit/test_corrupt_keys.js @@ -99,11 +99,11 @@ add_task(async function test_locally_changed_keys() { let history = johndoe.createCollection("history"); for (let i = 0; i < 5; i++) { let id = 'record-no--' + i; - let modified = Date.now() / 1000 - 60 * (i + 10); + let modified = Date.now()/1000 - 60*(i+10); let w = new CryptoWrapper("history", "id"); w.cleartext = { - id, + id: id, histUri: "http://foo/bar?" + id, title: id, sortindex: i, @@ -160,7 +160,7 @@ add_task(async function test_locally_changed_keys() { let w = new CryptoWrapper("history", "id"); w.cleartext = { - id, + id: id, histUri: "http://foo/bar?" + id, title: id, sortindex: i, diff --git a/services/sync/tests/unit/test_engine.js b/services/sync/tests/unit/test_engine.js index b8c71f934dc5..7b93a82d8681 100644 --- a/services/sync/tests/unit/test_engine.js +++ b/services/sync/tests/unit/test_engine.js @@ -14,7 +14,7 @@ function SteamStore(engine) { SteamStore.prototype = { __proto__: Store.prototype, - wipe() { + wipe: function() { this.wasWiped = true; } }; @@ -36,11 +36,11 @@ SteamEngine.prototype = { _storeObj: SteamStore, _trackerObj: SteamTracker, - _resetClient() { + _resetClient: function () { this.wasReset = true; }, - _sync() { + _sync: function () { this.wasSynced = true; } }; @@ -48,12 +48,12 @@ SteamEngine.prototype = { var engineObserver = { topics: [], - observe(subject, topic, data) { + observe: function(subject, topic, data) { do_check_eq(data, "steam"); this.topics.push(topic); }, - reset() { + reset: function() { this.topics = []; } }; @@ -82,7 +82,7 @@ add_task(async function test_score() { try { engine.score = 10; - } catch (ex) { + } catch(ex) { // Setting an attribute that has a getter produces an error in // Firefox <= 3.6 and is ignored in later versions. Either way, // the attribute's value won't change. diff --git a/services/sync/tests/unit/test_engine_abort.js b/services/sync/tests/unit/test_engine_abort.js index 9483f05982ad..5981cfc10ce0 100644 --- a/services/sync/tests/unit/test_engine_abort.js +++ b/services/sync/tests/unit/test_engine_abort.js @@ -14,7 +14,7 @@ add_task(async function test_processIncoming_abort() { let collection = new ServerCollection(); let id = Utils.makeGUID(); - let payload = encryptPayload({id, denomination: "Record No. " + id}); + let payload = encryptPayload({id: id, denomination: "Record No. " + id}); collection.insert(id, payload); let server = sync_httpd_setup({ @@ -30,7 +30,7 @@ add_task(async function test_processIncoming_abort() { meta_global.payload.engines = {rotary: {version: engine.version, syncID: engine.syncID}}; _("Fake applyIncoming to abort."); - engine._store.applyIncoming = function(record) { + engine._store.applyIncoming = function (record) { let ex = {code: Engine.prototype.eEngineAbortApplyIncoming, cause: "Nooo"}; _("Throwing: " + JSON.stringify(ex)); diff --git a/services/sync/tests/unit/test_errorhandler_1.js b/services/sync/tests/unit/test_errorhandler_1.js index 39d09f078f40..a4cf613ce2f9 100644 --- a/services/sync/tests/unit/test_errorhandler_1.js +++ b/services/sync/tests/unit/test_errorhandler_1.js @@ -90,7 +90,7 @@ add_identity_test(this, async function test_401_logout() { do_check_false(Service.isLoggedIn); // Clean up. - Utils.nextTick(function() { + Utils.nextTick(function () { Service.startOver(); server.stop(deferred.resolve); }); @@ -371,7 +371,7 @@ add_identity_test(this, async function test_shouldReportError_master_password() // Monkey patch Service.verifyLogin to imitate // master password being locked. Service._verifyLogin = Service.verifyLogin; - Service.verifyLogin = function() { + Service.verifyLogin = function () { Status.login = MASTER_PASSWORD_LOCKED; return false; }; diff --git a/services/sync/tests/unit/test_errorhandler_2.js b/services/sync/tests/unit/test_errorhandler_2.js index f150e4ac6dd4..efa1f97ec9ce 100644 --- a/services/sync/tests/unit/test_errorhandler_2.js +++ b/services/sync/tests/unit/test_errorhandler_2.js @@ -135,7 +135,7 @@ add_task(async function test_sync_prolonged_server_maintenance_error() { clean(); }); -add_identity_test(this, async function test_info_collections_login_prolonged_server_maintenance_error() { +add_identity_test(this, async function test_info_collections_login_prolonged_server_maintenance_error(){ // Test info/collections prolonged server maintenance errors are reported. let server = EHTestsCommon.sync_httpd_setup(); await EHTestsCommon.setUp(server); @@ -167,7 +167,7 @@ add_identity_test(this, async function test_info_collections_login_prolonged_ser await promiseStopServer(server); }); -add_identity_test(this, async function test_meta_global_login_prolonged_server_maintenance_error() { +add_identity_test(this, async function test_meta_global_login_prolonged_server_maintenance_error(){ // Test meta/global prolonged server maintenance errors are reported. let server = EHTestsCommon.sync_httpd_setup(); await EHTestsCommon.setUp(server); @@ -199,7 +199,7 @@ add_identity_test(this, async function test_meta_global_login_prolonged_server_m await promiseStopServer(server); }); -add_identity_test(this, async function test_download_crypto_keys_login_prolonged_server_maintenance_error() { +add_identity_test(this, async function test_download_crypto_keys_login_prolonged_server_maintenance_error(){ // Test crypto/keys prolonged server maintenance errors are reported. let server = EHTestsCommon.sync_httpd_setup(); await EHTestsCommon.setUp(server); @@ -232,7 +232,7 @@ add_identity_test(this, async function test_download_crypto_keys_login_prolonged await promiseStopServer(server); }); -add_identity_test(this, async function test_upload_crypto_keys_login_prolonged_server_maintenance_error() { +add_identity_test(this, async function test_upload_crypto_keys_login_prolonged_server_maintenance_error(){ // Test crypto/keys prolonged server maintenance errors are reported. let server = EHTestsCommon.sync_httpd_setup(); @@ -264,7 +264,7 @@ add_identity_test(this, async function test_upload_crypto_keys_login_prolonged_s await promiseStopServer(server); }); -add_identity_test(this, async function test_wipeServer_login_prolonged_server_maintenance_error() { +add_identity_test(this, async function test_wipeServer_login_prolonged_server_maintenance_error(){ // Test that we report prolonged server maintenance errors that occur whilst // wiping the server. let server = EHTestsCommon.sync_httpd_setup(); @@ -297,7 +297,7 @@ add_identity_test(this, async function test_wipeServer_login_prolonged_server_ma await promiseStopServer(server); }); -add_identity_test(this, async function test_wipeRemote_prolonged_server_maintenance_error() { +add_identity_test(this, async function test_wipeRemote_prolonged_server_maintenance_error(){ // Test that we report prolonged server maintenance errors that occur whilst // wiping all remote devices. let server = EHTestsCommon.sync_httpd_setup(); @@ -532,7 +532,7 @@ add_identity_test(this, async function test_wipeServer_login_syncAndReportErrors await promiseStopServer(server); }); -add_identity_test(this, async function test_wipeRemote_syncAndReportErrors_server_maintenance_error() { +add_identity_test(this, async function test_wipeRemote_syncAndReportErrors_server_maintenance_error(){ // Test that we report prolonged server maintenance errors that occur whilst // wiping all remote devices. let server = EHTestsCommon.sync_httpd_setup(); diff --git a/services/sync/tests/unit/test_errorhandler_eol.js b/services/sync/tests/unit/test_errorhandler_eol.js index 26722766d05c..ea35d6f55b37 100644 --- a/services/sync/tests/unit/test_errorhandler_eol.js +++ b/services/sync/tests/unit/test_errorhandler_eol.js @@ -28,7 +28,7 @@ function handler513(request, response) { } function handler200(eolCode) { - return function(request, response) { + return function (request, response) { let statusCode = 200; let status = "OK"; let body = "{\"meta\": 123456789010}"; diff --git a/services/sync/tests/unit/test_errorhandler_filelog.js b/services/sync/tests/unit/test_errorhandler_filelog.js index 1d4d39c379f5..993a478fd6c7 100644 --- a/services/sync/tests/unit/test_errorhandler_filelog.js +++ b/services/sync/tests/unit/test_errorhandler_filelog.js @@ -88,7 +88,7 @@ function readFile(file, callback) { NetUtil.asyncFetch({ uri: NetUtil.newURI(file), loadUsingSystemPrincipal: true - }, function(inputStream, statusCode, request) { + }, function (inputStream, statusCode, request) { let data = NetUtil.readInputStreamToString(inputStream, inputStream.available()); callback(statusCode, data); @@ -114,14 +114,14 @@ add_test(function test_logOnSuccess_true() { do_check_false(entries.hasMoreElements()); // Ensure the log message was actually written to file. - readFile(logfile, function(error, data) { + readFile(logfile, function (error, data) { do_check_true(Components.isSuccessCode(error)); do_check_neq(data.indexOf(MESSAGE), -1); // Clean up. try { logfile.remove(false); - } catch (ex) { + } catch(ex) { dump("Couldn't delete file: " + ex + "\n"); // Stupid Windows box. } @@ -181,14 +181,14 @@ add_test(function test_sync_error_logOnError_true() { do_check_false(entries.hasMoreElements()); // Ensure the log message was actually written to file. - readFile(logfile, function(error, data) { + readFile(logfile, function (error, data) { do_check_true(Components.isSuccessCode(error)); do_check_neq(data.indexOf(MESSAGE), -1); // Clean up. try { logfile.remove(false); - } catch (ex) { + } catch(ex) { dump("Couldn't delete file: " + ex + "\n"); // Stupid Windows box. } @@ -248,14 +248,14 @@ add_test(function test_login_error_logOnError_true() { do_check_false(entries.hasMoreElements()); // Ensure the log message was actually written to file. - readFile(logfile, function(error, data) { + readFile(logfile, function (error, data) { do_check_true(Components.isSuccessCode(error)); do_check_neq(data.indexOf(MESSAGE), -1); // Clean up. try { logfile.remove(false); - } catch (ex) { + } catch(ex) { dump("Couldn't delete file: " + ex + "\n"); // Stupid Windows box. } @@ -293,14 +293,14 @@ add_test(function test_errorLog_dumpAddons() { do_check_false(entries.hasMoreElements()); // Ensure we logged some addon list (which is probably empty) - readFile(logfile, function(error, data) { + readFile(logfile, function (error, data) { do_check_true(Components.isSuccessCode(error)); do_check_neq(data.indexOf("Addons installed"), -1); // Clean up. try { logfile.remove(false); - } catch (ex) { + } catch(ex) { dump("Couldn't delete file: " + ex + "\n"); // Stupid Windows box. } @@ -344,7 +344,7 @@ add_test(function test_logErrorCleanup_age() { let entries = logsdir.directoryEntries; do_check_true(entries.hasMoreElements()); let logfile = entries.getNext().QueryInterface(Ci.nsILocalFile); - do_check_true(oldLogs.every(function(e) { + do_check_true(oldLogs.every(function (e) { return e != logfile.leafName; })); do_check_false(entries.hasMoreElements()); @@ -352,7 +352,7 @@ add_test(function test_logErrorCleanup_age() { // Clean up. try { logfile.remove(false); - } catch (ex) { + } catch(ex) { dump("Couldn't delete file: " + ex + "\n"); // Stupid Windows box. } diff --git a/services/sync/tests/unit/test_errorhandler_sync_checkServerError.js b/services/sync/tests/unit/test_errorhandler_sync_checkServerError.js index 561c55f4b82a..d10728b061b5 100644 --- a/services/sync/tests/unit/test_errorhandler_sync_checkServerError.js +++ b/services/sync/tests/unit/test_errorhandler_sync_checkServerError.js @@ -42,13 +42,13 @@ function sync_httpd_setup() { let keysWBO = new ServerWBO("keys"); let globalWBO = new ServerWBO("global", {storageVersion: STORAGE_VERSION, syncID: Utils.makeGUID(), - engines}); + engines: engines}); let handlers = { "/1.1/johndoe/info/collections": collectionsHelper.handler, - "/1.1/johndoe/storage/meta/global": upd("meta", globalWBO.handler()), + "/1.1/johndoe/storage/meta/global": upd("meta", globalWBO.handler()), "/1.1/johndoe/storage/clients": upd("clients", clientsColl.handler()), - "/1.1/johndoe/storage/crypto/keys": upd("crypto", keysWBO.handler()) + "/1.1/johndoe/storage/crypto/keys": upd("crypto", keysWBO.handler()) }; return httpd_setup(handlers); } @@ -106,7 +106,7 @@ add_identity_test(this, async function test_backoff503() { headers: {"retry-after": BACKOFF}}; let backoffInterval; - Svc.Obs.add("weave:service:backoff:interval", function(subject) { + Svc.Obs.add("weave:service:backoff:interval", function (subject) { backoffInterval = subject; }); diff --git a/services/sync/tests/unit/test_extension_storage_crypto.js b/services/sync/tests/unit/test_extension_storage_crypto.js index c6b88791605d..f93e4970dcd9 100644 --- a/services/sync/tests/unit/test_extension_storage_crypto.js +++ b/services/sync/tests/unit/test_extension_storage_crypto.js @@ -20,7 +20,8 @@ function* throwsGen(constraint, f) { let exception; try { yield* f(); - } catch (e) { + } + catch (e) { threw = true; exception = e; } @@ -56,7 +57,7 @@ class StaticKeyEncryptionRemoteTransformer extends EncryptionRemoteTransformer { } } const BORING_KB = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; -const STRETCHED_KEY = CryptoUtils.hkdf(BORING_KB, undefined, `testing storage.sync encryption`, 2 * 32); +const STRETCHED_KEY = CryptoUtils.hkdf(BORING_KB, undefined, `testing storage.sync encryption`, 2*32); const KEY_BUNDLE = { sha256HMACHasher: Utils.makeHMACHasher(Ci.nsICryptoHMAC.SHA256, Utils.makeHMACKey(STRETCHED_KEY.slice(0, 32))), encryptionKeyB64: btoa(STRETCHED_KEY.slice(32, 64)), @@ -72,7 +73,7 @@ add_task(function* test_encryption_transformer_roundtrip() { ]; for (let data of POSSIBLE_DATAS) { - const record = {data, id: "key-some_2D_key", key: "some-key"}; + const record = {data: data, id: "key-some_2D_key", key: "some-key"}; deepEqual(record, yield transformer.decode(yield transformer.encode(record))); } diff --git a/services/sync/tests/unit/test_forms_tracker.js b/services/sync/tests/unit/test_forms_tracker.js index 08912e36183a..f14e208b3835 100644 --- a/services/sync/tests/unit/test_forms_tracker.js +++ b/services/sync/tests/unit/test_forms_tracker.js @@ -17,10 +17,10 @@ function run_test() { Log.repository.rootLogger.addAppender(new Log.DumpAppender()); function addEntry(name, value) { - engine._store.create({name, value}); + engine._store.create({name: name, value: value}); } function removeEntry(name, value) { - guid = engine._findDupe({name, value}); + guid = engine._findDupe({name: name, value: value}); engine._store.remove({id: guid}); } diff --git a/services/sync/tests/unit/test_fxa_migration.js b/services/sync/tests/unit/test_fxa_migration.js index 606cdf51edd3..e73b23e380fe 100644 --- a/services/sync/tests/unit/test_fxa_migration.js +++ b/services/sync/tests/unit/test_fxa_migration.js @@ -46,7 +46,7 @@ function configureLegacySync() { // ideally we'd only do this while a legacy user is configured, but WTH. response.setHeader("x-weave-alert", JSON.stringify({code: "soft-eol"})); } - let server = new SyncServer({onRequest}); + let server = new SyncServer({onRequest: onRequest}); server.registerUser(USER, "password"); server.createContents(USER, contents); server.start(); diff --git a/services/sync/tests/unit/test_fxa_node_reassignment.js b/services/sync/tests/unit/test_fxa_node_reassignment.js index 87b872a47861..552d8bab97eb 100644 --- a/services/sync/tests/unit/test_fxa_node_reassignment.js +++ b/services/sync/tests/unit/test_fxa_node_reassignment.js @@ -80,7 +80,7 @@ function prepareServer(cbAfterTokenFetch) { let numReassigns = 0; return configureIdentity(config).then(() => { Service.identity._tokenServerClient = { - getTokenFromBrowserIDAssertion(uri, assertion, cb) { + getTokenFromBrowserIDAssertion: function(uri, assertion, cb) { // Build a new URL with trailing zeros for the SYNC_VERSION part - this // will still be seen as equivalent by the test server, but different // by sync itself. @@ -144,7 +144,7 @@ async function syncAndExpectNodeReassignment(server, firstNotification, between, // Make absolutely sure that any event listeners are done with their work // before we proceed. - waitForZeroTimer(function() { + waitForZeroTimer(function () { _("Second sync nextTick."); do_check_eq(numTokenRequests, numTokenRequestsBefore + 1, "fetched a new token"); Service.startOver(); @@ -161,7 +161,7 @@ async function syncAndExpectNodeReassignment(server, firstNotification, between, if (Service.isLoggedIn) { _("Making request to " + url + " which should 401"); let request = new RESTRequest(url); - request.get(function() { + request.get(function () { do_check_eq(request.response.status, 401); Utils.nextTick(onwards); }); diff --git a/services/sync/tests/unit/test_history_engine.js b/services/sync/tests/unit/test_history_engine.js index e7c987c46fdf..4c043a28116f 100644 --- a/services/sync/tests/unit/test_history_engine.js +++ b/services/sync/tests/unit/test_history_engine.js @@ -28,7 +28,7 @@ add_task(async function test_processIncoming_mobile_history_batched() { let collection = new ServerCollection(); collection.get_log = []; collection._get = collection.get; - collection.get = function(options) { + collection.get = function (options) { this.get_log.push(options); return this._get(options); }; @@ -44,9 +44,9 @@ add_task(async function test_processIncoming_mobile_history_batched() { let visitType = Ci.nsINavHistoryService.TRANSITION_LINK; for (var i = 0; i < 234; i++) { let id = 'record-no' + ("00" + i).slice(-3); - let modified = Date.now() / 1000 - 60 * (i + 10); + let modified = Date.now()/1000 - 60*(i+10); let payload = encryptPayload({ - id, + id: id, histUri: "http://foo/bar?" + id, title: id, sortindex: i, diff --git a/services/sync/tests/unit/test_hmac_error.js b/services/sync/tests/unit/test_hmac_error.js index 516a9437c989..5bddd6a3cb20 100644 --- a/services/sync/tests/unit/test_hmac_error.js +++ b/services/sync/tests/unit/test_hmac_error.js @@ -9,9 +9,9 @@ Cu.import("resource://testing-common/services/sync/utils.js"); // Track HMAC error counts. var hmacErrorCount = 0; -(function() { +(function () { let hHE = Service.handleHMACEvent; - Service.handleHMACEvent = function() { + Service.handleHMACEvent = function () { hmacErrorCount++; return hHE.call(Service); }; @@ -37,7 +37,7 @@ function shared_setup() { syncID: Service.clientsEngine.syncID}}; // Common server objects. - let global = new ServerWBO("global", {engines}); + let global = new ServerWBO("global", {engines: engines}); let keysWBO = new ServerWBO("keys"); let rotaryColl = new ServerCollection({}, true); let clientsColl = new ServerCollection({}, true); @@ -52,7 +52,7 @@ add_task(async function hmac_error_during_404() { // Hand out 404s for crypto/keys. let keysHandler = keysWBO.handler(); let key404Counter = 0; - let keys404Handler = function(request, response) { + let keys404Handler = function (request, response) { if (key404Counter > 0) { let body = "Not Found"; response.setStatusLine(request.httpVersion, 404, body); @@ -123,7 +123,7 @@ add_task(async function hmac_error_during_node_reassignment() { let should401 = false; function upd401(coll, handler) { - return function(request, response) { + return function (request, response) { if (should401 && (request.method != "DELETE")) { on401(); should401 = false; diff --git a/services/sync/tests/unit/test_httpd_sync_server.js b/services/sync/tests/unit/test_httpd_sync_server.js index ba2893e65372..943dbfd738f6 100644 --- a/services/sync/tests/unit/test_httpd_sync_server.js +++ b/services/sync/tests/unit/test_httpd_sync_server.js @@ -15,7 +15,7 @@ add_test(function test_creation() { __proto__: SyncServerCallback, }); do_check_true(!!server); // Just so we have a check. - server.start(null, function() { + server.start(null, function () { _("Started on " + server.port); server.stop(run_next_test); }); @@ -77,14 +77,14 @@ add_test(function test_basic_http() { let server = new SyncServer(); server.registerUser("john", "password"); do_check_true(server.userExists("john")); - server.start(null, function() { + server.start(null, function () { _("Started on " + server.port); - Utils.nextTick(function() { + Utils.nextTick(function () { let req = localRequest(server, "/1.1/john/storage/crypto/keys"); _("req is " + req); - req.get(function(err) { + req.get(function (err) { do_check_eq(null, err); - Utils.nextTick(function() { + Utils.nextTick(function () { server.stop(run_next_test); }); }); @@ -103,16 +103,16 @@ add_test(function test_info_collections() { } server.registerUser("john", "password"); - server.start(null, function() { - Utils.nextTick(function() { + server.start(null, function () { + Utils.nextTick(function () { let req = localRequest(server, "/1.1/john/info/collections"); - req.get(function(err) { + req.get(function (err) { // Initial info/collections fetch is empty. do_check_eq(null, err); responseHasCorrectHeaders(this.response); do_check_eq(this.response.body, "{}"); - Utils.nextTick(function() { + Utils.nextTick(function () { // When we PUT something to crypto/keys, "crypto" appears in the response. function cb(err) { do_check_eq(null, err); @@ -121,7 +121,7 @@ add_test(function test_info_collections() { _("PUT response body: " + JSON.stringify(putResponseBody)); req = localRequest(server, "/1.1/john/info/collections"); - req.get(function(err) { + req.get(function (err) { do_check_eq(null, err); responseHasCorrectHeaders(this.response); let expectedColl = server.getCollection("john", "crypto"); @@ -130,7 +130,7 @@ add_test(function test_info_collections() { do_check_true(modified > 0); do_check_eq(putResponseBody, modified); do_check_eq(JSON.parse(this.response.body).crypto, modified); - Utils.nextTick(function() { + Utils.nextTick(function () { server.stop(run_next_test); }); }); @@ -163,7 +163,7 @@ add_test(function test_storage_request() { function retrieveWBONotExists(next) { let req = localRequest(server, keysURL); - req.get(function(err) { + req.get(function (err) { _("Body is " + this.response.body); _("Modified is " + this.response.newModified); do_check_eq(null, err); @@ -174,7 +174,7 @@ add_test(function test_storage_request() { } function retrieveWBOExists(next) { let req = localRequest(server, foosURL); - req.get(function(err) { + req.get(function (err) { _("Body is " + this.response.body); _("Modified is " + this.response.newModified); let parsedBody = JSON.parse(this.response.body); @@ -186,11 +186,11 @@ add_test(function test_storage_request() { } function deleteWBONotExists(next) { let req = localRequest(server, keysURL); - server.callback.onItemDeleted = function(username, collection, wboID) { + server.callback.onItemDeleted = function (username, collection, wboID) { do_throw("onItemDeleted should not have been called."); }; - req.delete(function(err) { + req.delete(function (err) { _("Body is " + this.response.body); _("Modified is " + this.response.newModified); do_check_eq(this.response.status, 200); @@ -200,7 +200,7 @@ add_test(function test_storage_request() { } function deleteWBOExists(next) { let req = localRequest(server, foosURL); - server.callback.onItemDeleted = function(username, collection, wboID) { + server.callback.onItemDeleted = function (username, collection, wboID) { _("onItemDeleted called for " + collection + "/" + wboID); delete server.callback.onItemDeleted; do_check_eq(username, "john"); @@ -209,7 +209,7 @@ add_test(function test_storage_request() { Utils.nextTick(next); }; - req.delete(function(err) { + req.delete(function (err) { _("Body is " + this.response.body); _("Modified is " + this.response.newModified); do_check_eq(this.response.status, 200); @@ -220,7 +220,7 @@ add_test(function test_storage_request() { let now = server.timestamp(); _("Timestamp: " + now); let req = localRequest(server, storageURL); - req.delete(function(err) { + req.delete(function (err) { _("Body is " + this.response.body); _("Modified is " + this.response.newModified); let parsedBody = JSON.parse(this.response.body); @@ -232,7 +232,7 @@ add_test(function test_storage_request() { function getStorageFails(next) { _("Testing that GET on /storage fails."); let req = localRequest(server, storageURL); - req.get(function(err) { + req.get(function (err) { do_check_eq(this.response.status, 405); do_check_eq(this.response.headers["allow"], "DELETE"); Utils.nextTick(next); @@ -241,7 +241,7 @@ add_test(function test_storage_request() { function getMissingCollectionWBO(next) { _("Testing that fetching a WBO from an on-existent collection 404s."); let req = localRequest(server, storageURL + "/foobar/baz"); - req.get(function(err) { + req.get(function (err) { do_check_eq(this.response.status, 404); Utils.nextTick(next); }); @@ -269,13 +269,13 @@ add_test(function test_x_weave_records() { crypto: {foos: {foo: "bar"}, bars: {foo: "baz"}} }); - server.start(null, function() { + server.start(null, function () { let wbo = localRequest(server, "/1.1/john/storage/crypto/foos"); - wbo.get(function(err) { + wbo.get(function (err) { // WBO fetches don't have one. do_check_false("x-weave-records" in this.response.headers); let col = localRequest(server, "/1.1/john/storage/crypto"); - col.get(function(err) { + col.get(function (err) { // Collection fetches do. do_check_eq(this.response.headers["x-weave-records"], "2"); server.stop(run_next_test); diff --git a/services/sync/tests/unit/test_interval_triggers.js b/services/sync/tests/unit/test_interval_triggers.js index d680c341e529..1bd4e7f5b28d 100644 --- a/services/sync/tests/unit/test_interval_triggers.js +++ b/services/sync/tests/unit/test_interval_triggers.js @@ -63,7 +63,7 @@ add_identity_test(this, async function test_successful_sync_adjustSyncInterval() function onSyncFinish() { _("Sync success."); syncSuccesses++; - } + }; Svc.Obs.add("weave:service:sync:finish", onSyncFinish); let server = sync_httpd_setup(); @@ -148,7 +148,7 @@ add_identity_test(this, async function test_successful_sync_adjustSyncInterval() do_check_eq(syncSuccesses, 8); do_check_false(scheduler.idle); do_check_true(scheduler.numClients > 1); - do_check_false(scheduler.hasIncomingItems); // gets reset to false + do_check_false(scheduler.hasIncomingItems); //gets reset to false do_check_eq(scheduler.syncInterval, scheduler.immediateInterval); Svc.Obs.remove("weave:service:sync:finish", onSyncFinish); @@ -253,7 +253,7 @@ add_identity_test(this, async function test_unsuccessful_sync_adjustSyncInterval do_check_eq(syncFailures, 8); do_check_false(scheduler.idle); do_check_true(scheduler.numClients > 1); - do_check_false(scheduler.hasIncomingItems); // gets reset to false + do_check_false(scheduler.hasIncomingItems); //gets reset to false do_check_eq(scheduler.syncInterval, scheduler.immediateInterval); Service.startOver(); @@ -334,7 +334,7 @@ add_identity_test(this, async function test_bug671378_scenario() { function onSyncFinish() { _("Sync success."); syncSuccesses++; - } + }; Svc.Obs.add("weave:service:sync:finish", onSyncFinish); // After first sync call, syncInterval & syncTimer are singleDeviceInterval. @@ -410,7 +410,7 @@ add_test(function test_adjust_timer_larger_syncInterval() { do_check_neq(scheduler.nextSync, 0); do_check_true(scheduler.syncTimer.delay <= scheduler.activeInterval); - // SyncSchedule. + //SyncSchedule. Service.startOver(); run_next_test(); }); @@ -434,7 +434,7 @@ add_test(function test_adjust_timer_smaller_syncInterval() { do_check_neq(scheduler.nextSync, 0); do_check_true(scheduler.syncTimer.delay <= scheduler.activeInterval); - // SyncSchedule. + //SyncSchedule. Service.startOver(); run_next_test(); }); diff --git a/services/sync/tests/unit/test_jpakeclient.js b/services/sync/tests/unit/test_jpakeclient.js index 63892fee47c1..783edb460373 100644 --- a/services/sync/tests/unit/test_jpakeclient.js +++ b/services/sync/tests/unit/test_jpakeclient.js @@ -550,7 +550,7 @@ add_test(function test_error_delayNotSupported() { add_test(function test_sendAndComplete_notPaired() { let snd = new JPAKEClient({__proto__: BaseController}); - do_check_throws(function() { + do_check_throws(function () { snd.sendAndComplete(DATA); }); run_next_test(); diff --git a/services/sync/tests/unit/test_keys.js b/services/sync/tests/unit/test_keys.js index 3231680a0956..a828b619cd94 100644 --- a/services/sync/tests/unit/test_keys.js +++ b/services/sync/tests/unit/test_keys.js @@ -154,7 +154,7 @@ add_test(function test_keymanager() { // Encryption key is stored in base64 for WeaveCrypto convenience. do_check_eq(encryptKey, new SyncKeyBundle(username, testKey).encryptionKey); - do_check_eq(hmacKey, new SyncKeyBundle(username, testKey).hmacKey); + do_check_eq(hmacKey, new SyncKeyBundle(username, testKey).hmacKey); // Test with the same KeyBundle for both. let obj = new SyncKeyBundle(username, testKey); @@ -192,7 +192,7 @@ add_test(function test_collections_manager() { "default": [default_key64, default_hmac64], "collections": {"bookmarks": [bookmarks_key64, bookmarks_hmac64]}, }; - storage_keys.modified = Date.now() / 1000; + storage_keys.modified = Date.now()/1000; storage_keys.id = "keys"; log.info("Encrypting storage keys..."); @@ -264,7 +264,7 @@ add_test(function test_collections_manager() { do_check_true(collectionKeys.updateNeeded(info_collections)); info_collections["crypto"] = 5000; do_check_false(collectionKeys.updateNeeded(info_collections)); - info_collections["crypto"] = 1 + (Date.now() / 1000); // Add one in case computers are fast! + info_collections["crypto"] = 1 + (Date.now()/1000); // Add one in case computers are fast! do_check_true(collectionKeys.updateNeeded(info_collections)); collectionKeys.lastModified = null; diff --git a/services/sync/tests/unit/test_node_reassignment.js b/services/sync/tests/unit/test_node_reassignment.js index 21b606f97e45..065c3fee7b2e 100644 --- a/services/sync/tests/unit/test_node_reassignment.js +++ b/services/sync/tests/unit/test_node_reassignment.js @@ -127,7 +127,7 @@ async function syncAndExpectNodeReassignment(server, firstNotification, between, // Verify that the client requests a node reassignment. // Install a node handler to watch for these requests. - installNodeHandler(server, function() { + installNodeHandler(server, function () { nodeFetched = true; }); @@ -141,7 +141,7 @@ async function syncAndExpectNodeReassignment(server, firstNotification, between, // Make absolutely sure that any event listeners are done with their work // before we proceed. - waitForZeroTimer(function() { + waitForZeroTimer(function () { _("Second sync nextTick."); do_check_true(nodeFetched); Service.startOver(); @@ -155,7 +155,7 @@ async function syncAndExpectNodeReassignment(server, firstNotification, between, // Make sure that it works! let request = new RESTRequest(url); - request.get(function() { + request.get(function () { do_check_eq(request.response.status, 401); Utils.nextTick(onwards); }); @@ -323,7 +323,7 @@ add_task(async function test_loop_avoidance_storage() { // Verify that the client requests a node reassignment. // Install a node handler to watch for these requests. - installNodeHandler(server, function() { + installNodeHandler(server, function () { nodeFetched = true; }); @@ -368,7 +368,7 @@ add_task(async function test_loop_avoidance_storage() { // Make absolutely sure that any event listeners are done with their work // before we proceed. - waitForZeroTimer(function() { + waitForZeroTimer(function () { _("Third sync nextTick."); do_check_false(getReassigned()); do_check_true(nodeFetched); @@ -462,7 +462,7 @@ add_task(async function test_loop_avoidance_engine() { // Verify that the client requests a node reassignment. // Install a node handler to watch for these requests. - installNodeHandler(server, function() { + installNodeHandler(server, function () { nodeFetched = true; }); @@ -508,7 +508,7 @@ add_task(async function test_loop_avoidance_engine() { // Make absolutely sure that any event listeners are done with their work // before we proceed. - waitForZeroTimer(function() { + waitForZeroTimer(function () { _("Third sync nextTick."); do_check_false(getReassigned()); do_check_true(nodeFetched); diff --git a/services/sync/tests/unit/test_password_store.js b/services/sync/tests/unit/test_password_store.js index f21fbb95f3ea..d232d5e63421 100644 --- a/services/sync/tests/unit/test_password_store.js +++ b/services/sync/tests/unit/test_password_store.js @@ -17,7 +17,7 @@ function checkRecord(name, record, expectedCount, timeCreated, record.formSubmitURL, null); _("Record" + name + ":" + JSON.stringify(logins)); - _("Count" + name + ":" + count.value); + _("Count" + name + ":" + count.value); do_check_eq(count.value, expectedCount); @@ -50,10 +50,10 @@ function changePassword(name, hostname, password, expectedCount, timeCreated, const BOGUS_GUID = "zzzzzz" + hostname; let record = {id: BOGUS_GUID, - hostname, + hostname: hostname, formSubmitURL: hostname, username: "john", - password, + password: password, usernameField: "username", passwordField: "password"}; @@ -129,7 +129,7 @@ function test_apply_same_record_with_different_times() { 100, 800, timePasswordChanged, true, true); timePasswordChanged = changePassword("A", "http://a.tn", "password2", 1, 500, - 100, 1536213005222, timePasswordChanged, + 100, 1536213005222, timePasswordChanged, true, true); timePasswordChanged = changePassword("A", "http://a.tn", "password2", 1, 500, 100, 800, timePasswordChanged, true, true); @@ -196,4 +196,4 @@ function run_test() { } finally { store.wipe(); } -} +} \ No newline at end of file diff --git a/services/sync/tests/unit/test_places_guid_downgrade.js b/services/sync/tests/unit/test_places_guid_downgrade.js index 06c8d3299370..2f99c4a93e54 100644 --- a/services/sync/tests/unit/test_places_guid_downgrade.js +++ b/services/sync/tests/unit/test_places_guid_downgrade.js @@ -34,7 +34,7 @@ function removePlacesDatabase() { } } -Svc.Obs.add("places-shutdown", function() { +Svc.Obs.add("places-shutdown", function () { do_timeout(0, removePlacesDatabase); }); diff --git a/services/sync/tests/unit/test_postqueue.js b/services/sync/tests/unit/test_postqueue.js index d4dadbb8e2ab..e60008a96ede 100644 --- a/services/sync/tests/unit/test_postqueue.js +++ b/services/sync/tests/unit/test_postqueue.js @@ -8,7 +8,7 @@ initTestLogging("Trace"); function makeRecord(nbytes) { // make a string 2-bytes less - the added quotes will make it correct. return { - toJSON: () => "x".repeat(nbytes - 2), + toJSON: () => "x".repeat(nbytes-2), } } @@ -85,7 +85,7 @@ add_test(function test_max_post_bytes_no_batch() { commit: false, headers: [["x-if-unmodified-since", time]], batch: "true", - }, { + },{ nbytes: 22, commit: false, // we know we aren't in a batch, so never commit. headers: [["x-if-unmodified-since", time + 100]], @@ -125,7 +125,7 @@ add_test(function test_max_post_records_no_batch() { commit: false, batch: "true", headers: [["x-if-unmodified-since", time]], - }, { + },{ nbytes: 22, commit: false, // we know we aren't in a batch, so never commit. batch: null, @@ -202,7 +202,7 @@ add_test(function test_max_post_bytes_batch() { commit: false, batch: "true", headers: [['x-if-unmodified-since', time]], - }, { + },{ nbytes: 22, commit: true, batch: 1234, @@ -259,7 +259,7 @@ add_test(function test_max_post_bytes_batch() { commit: false, batch: "true", headers: [['x-if-unmodified-since', time0]], - }, { + },{ // second post of 22 bytes in the first batch, committing it. nbytes: 22, commit: true, @@ -271,7 +271,7 @@ add_test(function test_max_post_bytes_batch() { commit: false, batch: "true", headers: [['x-if-unmodified-since', time1]], - }, { + },{ // 4th post of 22 bytes in second batch, committing it. nbytes: 22, commit: true, @@ -317,7 +317,7 @@ add_test(function test_max_post_bytes_batch() { commit: false, batch: "true", headers: [['x-if-unmodified-since', time]], - }, { + },{ nbytes: 22, commit: true, batch: 1234, @@ -369,7 +369,7 @@ add_test(function test_huge_record() { commit: false, batch: "true", headers: [['x-if-unmodified-since', time]], - }, { + },{ nbytes: 22, commit: true, batch: 1234, @@ -431,7 +431,7 @@ add_test(function test_max_records_batch() { commit: false, batch: "true", headers: [['x-if-unmodified-since', time0]], - }, { // 2 records -- end batch1 + },{ // 2 records -- end batch1 nbytes: 43, commit: true, batch: 1234, @@ -441,7 +441,7 @@ add_test(function test_max_records_batch() { commit: false, batch: "true", headers: [['x-if-unmodified-since', time1]], - }, { // 1 record -- end batch2 + },{ // 1 record -- end batch2 nbytes: 22, commit: true, batch: 5678, @@ -452,4 +452,4 @@ add_test(function test_max_records_batch() { equal(pq.lastModified, time1 + 200); run_next_test(); -}); +}); \ No newline at end of file diff --git a/services/sync/tests/unit/test_records_crypto.js b/services/sync/tests/unit/test_records_crypto.js index d4953d2a2cdf..45340e9a31cc 100644 --- a/services/sync/tests/unit/test_records_crypto.js +++ b/services/sync/tests/unit/test_records_crypto.js @@ -66,7 +66,8 @@ add_task(async function test_records_crypto() { let error = ""; try { payload = cryptoWrap.decrypt(keyBundle); - } catch (ex) { + } + catch(ex) { error = ex; } do_check_eq(error, "No ciphertext: nothing to decrypt?"); @@ -88,7 +89,8 @@ add_task(async function test_records_crypto() { error = ""; try { cryptoWrap.decrypt(keyBundle); - } catch (ex) { + } + catch(ex) { error = ex; } do_check_eq(error, "Record id mismatch: resource != other"); @@ -99,7 +101,8 @@ add_task(async function test_records_crypto() { error = ""; try { cryptoWrap.decrypt(keyBundle); - } catch (ex) { + } + catch(ex) { error = ex; } do_check_eq(error.substr(0, 42), "Record SHA256 HMAC mismatch: should be foo"); @@ -169,7 +172,8 @@ add_task(async function test_records_crypto() { emptyKeys.setContents(payload, null); log.info("Done!"); - } finally { + } + finally { await promiseStopServer(server); } }); diff --git a/services/sync/tests/unit/test_records_wbo.js b/services/sync/tests/unit/test_records_wbo.js index 18e90b1cecb4..73f2e4ffbe34 100644 --- a/services/sync/tests/unit/test_records_wbo.js +++ b/services/sync/tests/unit/test_records_wbo.js @@ -24,9 +24,9 @@ function test_toJSON() { do_check_false("ttl" in json); _("Set a TTL, make sure it's present in the JSON representation."); - wbo.ttl = 30 * 60; + wbo.ttl = 30*60; json = JSON.parse(JSON.stringify(wbo)); - do_check_eq(json.ttl, 30 * 60); + do_check_eq(json.ttl, 30*60); } diff --git a/services/sync/tests/unit/test_resource.js b/services/sync/tests/unit/test_resource.js index 6662061c6253..c9e7cabc1684 100644 --- a/services/sync/tests/unit/test_resource.js +++ b/services/sync/tests/unit/test_resource.js @@ -98,7 +98,7 @@ const TIMESTAMP = 1274380461; function server_timestamp(metadata, response) { let body = "Thank you for your request"; - response.setHeader("X-Weave-Timestamp", '' + TIMESTAMP, false); + response.setHeader("X-Weave-Timestamp", ''+TIMESTAMP, false); response.setStatusLine(metadata.httpVersion, 200, "OK"); response.bodyOutputStream.write(body, body.length); } @@ -209,7 +209,7 @@ function run_test() { logger = res._log; let dbg = logger.debug; let debugMessages = []; - logger.debug = function(msg) { + logger.debug = function (msg) { debugMessages.push(msg); dbg.call(this, msg); } @@ -415,7 +415,7 @@ function run_test() { let res11 = new Resource("http://localhost:12345/does/not/exist"); try { content = res11.get(); - } catch (ex) { + } catch(ex) { error = ex; } do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED); diff --git a/services/sync/tests/unit/test_resource_async.js b/services/sync/tests/unit/test_resource_async.js index eb57a14782ee..50899db74b52 100644 --- a/services/sync/tests/unit/test_resource_async.js +++ b/services/sync/tests/unit/test_resource_async.js @@ -98,7 +98,7 @@ const TIMESTAMP = 1274380461; function server_timestamp(metadata, response) { let body = "Thank you for your request"; - response.setHeader("X-Weave-Timestamp", '' + TIMESTAMP, false); + response.setHeader("X-Weave-Timestamp", ''+TIMESTAMP, false); response.setStatusLine(metadata.httpVersion, 200, "OK"); response.bodyOutputStream.write(body, body.length); } @@ -150,7 +150,7 @@ function server_headers(metadata, response) { var quotaValue; Observers.add("weave:service:quota:remaining", - function(subject) { quotaValue = subject; }); + function (subject) { quotaValue = subject; }); function run_test() { logger = Log.repository.getLogger('Test'); @@ -173,7 +173,7 @@ add_test(function test_proxy_auth_redirect() { PACSystemSettings.PACURI = server.baseURI + "/pac2"; installFakePAC(); let res = new AsyncResource(server.baseURI + "/open"); - res.get(function(error, result) { + res.get(function (error, result) { do_check_true(!error); do_check_true(pacFetched); do_check_true(fetched); @@ -261,7 +261,7 @@ add_test(function test_members() { add_test(function test_get() { _("GET a non-password-protected resource"); let res = new AsyncResource(server.baseURI + "/open"); - res.get(function(error, content) { + res.get(function (error, content) { do_check_eq(error, null); do_check_eq(content, "This path exists"); do_check_eq(content.status, 200); @@ -273,7 +273,7 @@ add_test(function test_get() { let logger = res._log; let dbg = logger.debug; let debugMessages = []; - logger.debug = function(msg) { + logger.debug = function (msg) { debugMessages.push(msg); dbg.call(this, msg); } @@ -309,7 +309,7 @@ add_test(function test_basicauth() { add_test(function test_get_protected_fail() { _("GET a password protected resource (test that it'll fail w/o pass, no throw)"); let res2 = new AsyncResource(server.baseURI + "/protected"); - res2.get(function(error, content) { + res2.get(function (error, content) { do_check_eq(error, null); do_check_eq(content, "This path exists and is protected - failed"); do_check_eq(content.status, 401); @@ -325,7 +325,7 @@ add_test(function test_get_protected_success() { let res3 = new AsyncResource(server.baseURI + "/protected"); res3.authenticator = auth; do_check_eq(res3.authenticator, auth); - res3.get(function(error, content) { + res3.get(function (error, content) { do_check_eq(error, null); do_check_eq(content, "This path exists and is protected"); do_check_eq(content.status, 200); @@ -337,7 +337,7 @@ add_test(function test_get_protected_success() { add_test(function test_get_404() { _("GET a non-existent resource (test that it'll fail, but not throw)"); let res4 = new AsyncResource(server.baseURI + "/404"); - res4.get(function(error, content) { + res4.get(function (error, content) { do_check_eq(error, null); do_check_eq(content, "File not found"); do_check_eq(content.status, 404); @@ -367,7 +367,7 @@ add_test(function test_put_string() { add_test(function test_put_object() { _("PUT to a resource (object)"); let res_upload = new AsyncResource(server.baseURI + "/upload"); - res_upload.put(sample_data, function(error, content) { + res_upload.put(sample_data, function (error, content) { do_check_eq(error, null); do_check_eq(content, "Valid data upload via PUT"); do_check_eq(content.status, 200); @@ -380,7 +380,7 @@ add_test(function test_put_data_string() { _("PUT without data arg (uses resource.data) (string)"); let res_upload = new AsyncResource(server.baseURI + "/upload"); res_upload.data = JSON.stringify(sample_data); - res_upload.put(function(error, content) { + res_upload.put(function (error, content) { do_check_eq(error, null); do_check_eq(content, "Valid data upload via PUT"); do_check_eq(content.status, 200); @@ -393,7 +393,7 @@ add_test(function test_put_data_object() { _("PUT without data arg (uses resource.data) (object)"); let res_upload = new AsyncResource(server.baseURI + "/upload"); res_upload.data = sample_data; - res_upload.put(function(error, content) { + res_upload.put(function (error, content) { do_check_eq(error, null); do_check_eq(content, "Valid data upload via PUT"); do_check_eq(content.status, 200); @@ -405,7 +405,7 @@ add_test(function test_put_data_object() { add_test(function test_post_string() { _("POST to a resource (string)"); let res_upload = new AsyncResource(server.baseURI + "/upload"); - res_upload.post(JSON.stringify(sample_data), function(error, content) { + res_upload.post(JSON.stringify(sample_data), function (error, content) { do_check_eq(error, null); do_check_eq(content, "Valid data upload via POST"); do_check_eq(content.status, 200); @@ -417,7 +417,7 @@ add_test(function test_post_string() { add_test(function test_post_object() { _("POST to a resource (object)"); let res_upload = new AsyncResource(server.baseURI + "/upload"); - res_upload.post(sample_data, function(error, content) { + res_upload.post(sample_data, function (error, content) { do_check_eq(error, null); do_check_eq(content, "Valid data upload via POST"); do_check_eq(content.status, 200); @@ -430,7 +430,7 @@ add_test(function test_post_data_string() { _("POST without data arg (uses resource.data) (string)"); let res_upload = new AsyncResource(server.baseURI + "/upload"); res_upload.data = JSON.stringify(sample_data); - res_upload.post(function(error, content) { + res_upload.post(function (error, content) { do_check_eq(error, null); do_check_eq(content, "Valid data upload via POST"); do_check_eq(content.status, 200); @@ -443,7 +443,7 @@ add_test(function test_post_data_object() { _("POST without data arg (uses resource.data) (object)"); let res_upload = new AsyncResource(server.baseURI + "/upload"); res_upload.data = sample_data; - res_upload.post(function(error, content) { + res_upload.post(function (error, content) { do_check_eq(error, null); do_check_eq(content, "Valid data upload via POST"); do_check_eq(content.status, 200); @@ -455,7 +455,7 @@ add_test(function test_post_data_object() { add_test(function test_delete() { _("DELETE a resource"); let res6 = new AsyncResource(server.baseURI + "/delete"); - res6.delete(function(error, content) { + res6.delete(function (error, content) { do_check_eq(error, null); do_check_eq(content, "This resource has been deleted"); do_check_eq(content.status, 200); @@ -466,7 +466,7 @@ add_test(function test_delete() { add_test(function test_json_body() { _("JSON conversion of response body"); let res7 = new AsyncResource(server.baseURI + "/json"); - res7.get(function(error, content) { + res7.get(function (error, content) { do_check_eq(error, null); do_check_eq(content, JSON.stringify(sample_data)); do_check_eq(content.status, 200); @@ -481,7 +481,7 @@ add_test(function test_weave_timestamp() { // X-Weave-Timestamp header, AsyncResource.serverTime is null. do_check_eq(AsyncResource.serverTime, null); let res8 = new AsyncResource(server.baseURI + "/timestamp"); - res8.get(function(error, content) { + res8.get(function (error, content) { do_check_eq(error, null); do_check_eq(AsyncResource.serverTime, TIMESTAMP); run_next_test(); @@ -491,7 +491,7 @@ add_test(function test_weave_timestamp() { add_test(function test_get_no_headers() { _("GET: no special request headers"); let res_headers = new AsyncResource(server.baseURI + "/headers"); - res_headers.get(function(error, content) { + res_headers.get(function (error, content) { do_check_eq(error, null); do_check_eq(content, '{}'); run_next_test(); @@ -501,7 +501,7 @@ add_test(function test_get_no_headers() { add_test(function test_put_default_content_type() { _("PUT: Content-Type defaults to text/plain"); let res_headers = new AsyncResource(server.baseURI + "/headers"); - res_headers.put('data', function(error, content) { + res_headers.put('data', function (error, content) { do_check_eq(error, null); do_check_eq(content, JSON.stringify({"content-type": "text/plain"})); run_next_test(); @@ -511,7 +511,7 @@ add_test(function test_put_default_content_type() { add_test(function test_post_default_content_type() { _("POST: Content-Type defaults to text/plain"); let res_headers = new AsyncResource(server.baseURI + "/headers"); - res_headers.post('data', function(error, content) { + res_headers.post('data', function (error, content) { do_check_eq(error, null); do_check_eq(content, JSON.stringify({"content-type": "text/plain"})); run_next_test(); @@ -523,7 +523,7 @@ add_test(function test_setHeader() { let res_headers = new AsyncResource(server.baseURI + "/headers"); res_headers.setHeader('X-What-Is-Weave', 'awesome'); do_check_eq(res_headers.headers['x-what-is-weave'], 'awesome'); - res_headers.get(function(error, content) { + res_headers.get(function (error, content) { do_check_eq(error, null); do_check_eq(content, JSON.stringify({"x-what-is-weave": "awesome"})); run_next_test(); @@ -537,7 +537,7 @@ add_test(function test_setHeader_overwrite() { res_headers.setHeader('X-Another-Header', 'hello world'); do_check_eq(res_headers.headers['x-what-is-weave'], 'more awesomer'); do_check_eq(res_headers.headers['x-another-header'], 'hello world'); - res_headers.get(function(error, content) { + res_headers.get(function (error, content) { do_check_eq(error, null); do_check_eq(content, JSON.stringify({"x-another-header": "hello world", "x-what-is-weave": "more awesomer"})); @@ -550,7 +550,7 @@ add_test(function test_headers_object() { _("Setting headers object"); let res_headers = new AsyncResource(server.baseURI + "/headers"); res_headers.headers = {}; - res_headers.get(function(error, content) { + res_headers.get(function (error, content) { do_check_eq(error, null); do_check_eq(content, "{}"); run_next_test(); @@ -562,7 +562,7 @@ add_test(function test_put_override_content_type() { let res_headers = new AsyncResource(server.baseURI + "/headers"); res_headers.setHeader('Content-Type', 'application/foobar'); do_check_eq(res_headers.headers['content-type'], 'application/foobar'); - res_headers.put('data', function(error, content) { + res_headers.put('data', function (error, content) { do_check_eq(error, null); do_check_eq(content, JSON.stringify({"content-type": "application/foobar"})); run_next_test(); @@ -573,7 +573,7 @@ add_test(function test_post_override_content_type() { _("POST: override default Content-Type"); let res_headers = new AsyncResource(server.baseURI + "/headers"); res_headers.setHeader('Content-Type', 'application/foobar'); - res_headers.post('data', function(error, content) { + res_headers.post('data', function (error, content) { do_check_eq(error, null); do_check_eq(content, JSON.stringify({"content-type": "application/foobar"})); run_next_test(); @@ -589,7 +589,7 @@ add_test(function test_weave_backoff() { Observers.add("weave:service:backoff:interval", onBackoff); let res10 = new AsyncResource(server.baseURI + "/backoff"); - res10.get(function(error, content) { + res10.get(function (error, content) { do_check_eq(error, null); do_check_eq(backoffInterval, 600); run_next_test(); @@ -599,7 +599,7 @@ add_test(function test_weave_backoff() { add_test(function test_quota_error() { _("X-Weave-Quota-Remaining header notifies observer on successful requests."); let res10 = new AsyncResource(server.baseURI + "/quota-error"); - res10.get(function(error, content) { + res10.get(function (error, content) { do_check_eq(error, null); do_check_eq(content.status, 400); do_check_eq(quotaValue, undefined); // HTTP 400, so no observer notification. @@ -609,7 +609,7 @@ add_test(function test_quota_error() { add_test(function test_quota_notice() { let res10 = new AsyncResource(server.baseURI + "/quota-notice"); - res10.get(function(error, content) { + res10.get(function (error, content) { do_check_eq(error, null); do_check_eq(content.status, 200); do_check_eq(quotaValue, 1048576); @@ -620,7 +620,7 @@ add_test(function test_quota_notice() { add_test(function test_preserve_exceptions() { _("Error handling in ChannelListener etc. preserves exception information"); let res11 = new AsyncResource("http://localhost:12345/does/not/exist"); - res11.get(function(error, content) { + res11.get(function (error, content) { do_check_neq(error, null); do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED); do_check_eq(error.message, "NS_ERROR_CONNECTION_REFUSED"); @@ -638,7 +638,7 @@ add_test(function test_xpc_exception_handling() { let warnings = []; res14._log.warn = function(msg) { warnings.push(msg); }; - res14.get(function(error, content) { + res14.get(function (error, content) { do_check_eq(error.result, Cr.NS_ERROR_MALFORMED_URI); do_check_eq(error.message, "NS_ERROR_MALFORMED_URI"); do_check_eq(content, null); @@ -659,7 +659,7 @@ add_test(function test_js_exception_handling() { let warnings = []; res15._log.warn = function(msg) { warnings.push(msg); }; - res15.get(function(error, content) { + res15.get(function (error, content) { do_check_eq(error.result, Cr.NS_ERROR_XPC_JS_THREW_STRING); do_check_eq(error.message, "NS_ERROR_XPC_JS_THREW_STRING"); do_check_eq(content, null); @@ -675,7 +675,7 @@ add_test(function test_timeout() { _("Ensure channel timeouts are thrown appropriately."); let res19 = new AsyncResource(server.baseURI + "/json"); res19.ABORT_TIMEOUT = 0; - res19.get(function(error, content) { + res19.get(function (error, content) { do_check_eq(error.result, Cr.NS_ERROR_NET_TIMEOUT); run_next_test(); }); @@ -713,7 +713,7 @@ add_test(function test_not_sending_cookie() { cookieSer.setCookieString(uri, null, "test=test; path=/;", null); let res = new AsyncResource(server.baseURI + "/test"); - res.get(function(error) { + res.get(function (error) { do_check_null(error); do_check_true(this.response.success); do_check_eq("COOKIE!", this.response.body); diff --git a/services/sync/tests/unit/test_resource_header.js b/services/sync/tests/unit/test_resource_header.js index 7410f3d81a2d..4f28e01da24d 100644 --- a/services/sync/tests/unit/test_resource_header.js +++ b/services/sync/tests/unit/test_resource_header.js @@ -35,9 +35,9 @@ function contentHandler(metadata, response) { // Set a proxy function to cause an internal redirect. function triggerRedirect() { - const PROXY_FUNCTION = "function FindProxyForURL(url, host) {" + + const PROXY_FUNCTION = "function FindProxyForURL(url, host) {" + " return 'PROXY a_non_existent_domain_x7x6c572v:80; " + - "PROXY localhost:" + HTTP_PORT + "';" + + "PROXY localhost:" + HTTP_PORT + "';" + "}"; let prefsService = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService); diff --git a/services/sync/tests/unit/test_resource_ua.js b/services/sync/tests/unit/test_resource_ua.js index d2f3f1f41d71..f077e062e381 100644 --- a/services/sync/tests/unit/test_resource_ua.js +++ b/services/sync/tests/unit/test_resource_ua.js @@ -60,7 +60,7 @@ add_test(function test_fetchInfo() { add_test(function test_desktop_post() { _("Testing direct Resource POST."); let r = new AsyncResource(server.baseURI + "/1.1/johndoe/storage/meta/global"); - r.post("foo=bar", function(error, content) { + r.post("foo=bar", function (error, content) { _("User-Agent: " + ua); do_check_eq(ua, expectedUA + ".desktop"); ua = ""; @@ -84,7 +84,7 @@ add_test(function test_mobile_get() { _("Testing mobile."); Svc.Prefs.set("client.type", "mobile"); let r = new AsyncResource(server.baseURI + "/1.1/johndoe/storage/meta/global"); - r.get(function(error, content) { + r.get(function (error, content) { _("User-Agent: " + ua); do_check_eq(ua, expectedUA + ".mobile"); ua = ""; diff --git a/services/sync/tests/unit/test_sendcredentials_controller.js b/services/sync/tests/unit/test_sendcredentials_controller.js index 28e38b79e5b6..42e5ec8e80e0 100644 --- a/services/sync/tests/unit/test_sendcredentials_controller.js +++ b/services/sync/tests/unit/test_sendcredentials_controller.js @@ -31,9 +31,9 @@ function make_sendCredentials_test(topic) { sendAndCompleteCalled = true; // Verify it sends the correct data. - do_check_eq(data.account, Service.identity.account); - do_check_eq(data.password, Service.identity.basicPassword); - do_check_eq(data.synckey, Service.identity.syncKey); + do_check_eq(data.account, Service.identity.account); + do_check_eq(data.password, Service.identity.basicPassword); + do_check_eq(data.synckey, Service.identity.syncKey); do_check_eq(data.serverURL, Service.serverURL); this.controller.onComplete(); diff --git a/services/sync/tests/unit/test_service_detect_upgrade.js b/services/sync/tests/unit/test_service_detect_upgrade.js index 14df99d64662..0f46832d9836 100644 --- a/services/sync/tests/unit/test_service_detect_upgrade.js +++ b/services/sync/tests/unit/test_service_detect_upgrade.js @@ -82,7 +82,8 @@ add_test(function v4_upgrade() { Service.recordManager.set(Service.metaURL, meta_global); try { Service.sync(); - } catch (ex) { + } + catch (ex) { } do_check_eq(Service.status.sync, VERSION_OUT_OF_DATE); } @@ -174,7 +175,7 @@ add_test(function v4_upgrade() { _("Tabs: " + oldTabsModified + " < " + collections.tabs); _("Clients: " + oldClientsModified + " < " + collections.clients); do_check_true(collections.clients > oldClientsModified); - do_check_true(collections.tabs > oldTabsModified); + do_check_true(collections.tabs > oldTabsModified); _("... and keys will now match."); retrieve_and_compare_default(true); @@ -271,7 +272,8 @@ add_test(function v5_upgrade() { _("Logging in."); try { Service.login("johndoe", "ilovejane", passphrase); - } catch (e) { + } + catch (e) { _("Exception: " + e); } _("Status: " + Service.status); diff --git a/services/sync/tests/unit/test_service_getStorageInfo.js b/services/sync/tests/unit/test_service_getStorageInfo.js index 56c0f4312201..841dceb78bea 100644 --- a/services/sync/tests/unit/test_service_getStorageInfo.js +++ b/services/sync/tests/unit/test_service_getStorageInfo.js @@ -31,7 +31,7 @@ add_test(function test_success() { Service.serverURL = server.baseURI + "/"; Service.clusterURL = server.baseURI + "/"; - let request = Service.getStorageInfo("collections", function(error, info) { + let request = Service.getStorageInfo("collections", function (error, info) { do_check_eq(error, null); do_check_true(Utils.deepEquals(info, collections)); @@ -51,8 +51,8 @@ add_test(function test_success() { }); add_test(function test_invalid_type() { - do_check_throws(function() { - Service.getStorageInfo("invalid", function(error, info) { + do_check_throws(function () { + Service.getStorageInfo("invalid", function (error, info) { do_throw("Shouldn't get here!"); }); }); @@ -60,7 +60,7 @@ add_test(function test_invalid_type() { }); add_test(function test_network_error() { - Service.getStorageInfo(INFO_COLLECTIONS, function(error, info) { + Service.getStorageInfo(INFO_COLLECTIONS, function (error, info) { do_check_eq(error.result, Cr.NS_ERROR_CONNECTION_REFUSED); do_check_eq(info, null); run_next_test(); @@ -73,7 +73,7 @@ add_test(function test_http_error() { Service.serverURL = server.baseURI + "/"; Service.clusterURL = server.baseURI + "/"; - let request = Service.getStorageInfo(INFO_COLLECTIONS, function(error, info) { + let request = Service.getStorageInfo(INFO_COLLECTIONS, function (error, info) { do_check_eq(error.status, 500); do_check_eq(info, null); server.stop(run_next_test); @@ -86,7 +86,7 @@ add_test(function test_invalid_json() { Service.serverURL = server.baseURI + "/"; Service.clusterURL = server.baseURI + "/"; - let request = Service.getStorageInfo(INFO_COLLECTIONS, function(error, info) { + let request = Service.getStorageInfo(INFO_COLLECTIONS, function (error, info) { do_check_eq(error.name, "SyntaxError"); do_check_eq(info, null); server.stop(run_next_test); diff --git a/services/sync/tests/unit/test_service_login.js b/services/sync/tests/unit/test_service_login.js index d42b45d5598b..42c163915f02 100644 --- a/services/sync/tests/unit/test_service_login.js +++ b/services/sync/tests/unit/test_service_login.js @@ -9,7 +9,7 @@ Cu.import("resource://services-sync/util.js"); Cu.import("resource://testing-common/services/sync/utils.js"); function login_handling(handler) { - return function(request, response) { + return function (request, response) { if (basic_auth_matches(request, "johndoe", "ilovejane") || basic_auth_matches(request, "janedoe", "ilovejohn")) { handler(request, response); @@ -58,9 +58,9 @@ function setup() { // is where keys are generated or fetched. // TODO: have Jane fetch her keys, not generate them... "/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()), - "/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()), + "/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()), "/1.1/janedoe/storage/crypto/keys": janeU("crypto", new ServerWBO("keys").handler()), - "/1.1/janedoe/storage/meta/global": janeU("meta", new ServerWBO("global").handler()) + "/1.1/janedoe/storage/meta/global": janeU("meta", new ServerWBO("global").handler()) }); Service.serverURL = server.baseURI; diff --git a/services/sync/tests/unit/test_service_migratePrefs.js b/services/sync/tests/unit/test_service_migratePrefs.js index ec15350af1d2..89a147c06a43 100644 --- a/services/sync/tests/unit/test_service_migratePrefs.js +++ b/services/sync/tests/unit/test_service_migratePrefs.js @@ -18,7 +18,7 @@ function test_migrate_logging() { do_check_true(Svc.Prefs.get("log.appender.file.logOnSuccess")); do_check_eq(Svc.Prefs.get("log.appender.debugLog"), undefined); do_check_eq(Svc.Prefs.get("log.appender.debugLog.enabled"), undefined); -} +}; function run_test() { _("Set some prefs on the old branch"); diff --git a/services/sync/tests/unit/test_service_passwordUTF8.js b/services/sync/tests/unit/test_service_passwordUTF8.js index fc74b6b53401..e781050b3684 100644 --- a/services/sync/tests/unit/test_service_passwordUTF8.js +++ b/services/sync/tests/unit/test_service_passwordUTF8.js @@ -20,7 +20,7 @@ basicauth[Utils.encodeUTF8(JAPANESE)] = "Basic am9obmRvZTrjk7/jl7/jm7/jn78="; var server_password; function login_handling(handler) { - return function(request, response) { + return function (request, response) { let basic = basicauth[server_password]; if (basic && (request.getHeader("Authorization") == basic)) { @@ -63,7 +63,7 @@ function run_test() { do_test_pending(); let server = httpd_setup({ "/1.1/johndoe/info/collections": login_handling(collectionsHelper.handler), - "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()), + "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()), "/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()), "/user/1.0/johndoe/password": change_password }); diff --git a/services/sync/tests/unit/test_service_startOver.js b/services/sync/tests/unit/test_service_startOver.js index 9b3dbac66fd5..acc7f10d2fd6 100644 --- a/services/sync/tests/unit/test_service_startOver.js +++ b/services/sync/tests/unit/test_service_startOver.js @@ -14,7 +14,7 @@ BlaEngine.prototype = { __proto__: SyncEngine.prototype, removed: false, - removeClientData() { + removeClientData: function() { this.removed = true; } diff --git a/services/sync/tests/unit/test_service_startup.js b/services/sync/tests/unit/test_service_startup.js index 6d48b84a893f..5148f6d133da 100644 --- a/services/sync/tests/unit/test_service_startup.js +++ b/services/sync/tests/unit/test_service_startup.js @@ -38,7 +38,7 @@ function run_test() { do_check_false(Service.status.ready); do_check_false(xps.ready); - Observers.add("weave:service:ready", function(subject, data) { + Observers.add("weave:service:ready", function (subject, data) { do_check_true(Service.status.ready); do_check_true(xps.ready); diff --git a/services/sync/tests/unit/test_service_sync_401.js b/services/sync/tests/unit/test_service_sync_401.js index e83c001ba3e0..b8547129dee8 100644 --- a/services/sync/tests/unit/test_service_sync_401.js +++ b/services/sync/tests/unit/test_service_sync_401.js @@ -8,7 +8,7 @@ Cu.import("resource://services-sync/util.js"); Cu.import("resource://testing-common/services/sync/utils.js"); function login_handling(handler) { - return function(request, response) { + return function (request, response) { if (request.hasHeader("Authorization") && request.getHeader("Authorization").includes('Hawk id="id"')) { handler(request, response); @@ -30,7 +30,7 @@ add_task(async function run_test() { let server = httpd_setup({ "/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()), - "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()), + "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()), "/1.1/johndoe/info/collections": login_handling(collectionsHelper.handler) }); @@ -44,7 +44,7 @@ add_task(async function run_test() { Svc.Prefs.set("lastPing", Math.floor(Date.now() / 1000)); let threw = false; - Svc.Obs.add("weave:service:sync:error", function(subject, data) { + Svc.Obs.add("weave:service:sync:error", function (subject, data) { threw = true; }); diff --git a/services/sync/tests/unit/test_service_sync_locked.js b/services/sync/tests/unit/test_service_sync_locked.js index 91246a119b8f..ee952c7eef15 100644 --- a/services/sync/tests/unit/test_service_sync_locked.js +++ b/services/sync/tests/unit/test_service_sync_locked.js @@ -15,7 +15,7 @@ function run_test() { // For the purposes of this test we don't need to do full formatting // of the 2nd param, as the ones we care about are always strings. old.debug = function(m, p) { debug.push(p ? m + ": " + p : m); d.call(old, m, p); } - old.info = function(m, p) { info.push(p ? m + ": " + p : m); i.call(old, m, p); } + old.info = function(m, p) { info.push(p ? m + ": " + p : m); i.call(old, m, p); } return old; } diff --git a/services/sync/tests/unit/test_service_sync_remoteSetup.js b/services/sync/tests/unit/test_service_sync_remoteSetup.js index b8c10e1a4216..83dbf3cd7b64 100644 --- a/services/sync/tests/unit/test_service_sync_remoteSetup.js +++ b/services/sync/tests/unit/test_service_sync_remoteSetup.js @@ -160,7 +160,7 @@ function run_test() { metaColl.delete({}); _("Do an initial sync."); - let beforeSync = Date.now() / 1000; + let beforeSync = Date.now()/1000; Service.sync(); _("Checking that remoteSetup returns true."); @@ -224,7 +224,7 @@ function run_test() { let keys = Service.collectionKeys.asWBO(); let b = new BulkKeyBundle("hmacerror"); b.generateRandom(); - collections.crypto = keys.modified = 100 + (Date.now() / 1000); // Future modification time. + collections.crypto = keys.modified = 100 + (Date.now()/1000); // Future modification time. keys.encrypt(b); keys.upload(Service.resource(Service.cryptoKeysURL)); diff --git a/services/sync/tests/unit/test_service_verifyLogin.js b/services/sync/tests/unit/test_service_verifyLogin.js index 307cd8442197..2a27fd1b0e82 100644 --- a/services/sync/tests/unit/test_service_verifyLogin.js +++ b/services/sync/tests/unit/test_service_verifyLogin.js @@ -8,7 +8,7 @@ Cu.import("resource://services-sync/util.js"); Cu.import("resource://testing-common/services/sync/utils.js"); function login_handling(handler) { - return function(request, response) { + return function (request, response) { if (basic_auth_matches(request, "johndoe", "ilovejane")) { handler(request, response); } else { @@ -40,7 +40,7 @@ function run_test() { do_test_pending(); let server; - function weaveHandler(request, response) { + function weaveHandler (request, response) { response.setStatusLine(request.httpVersion, 200, "OK"); let body = server.baseURI + "/api/"; response.bodyOutputStream.write(body, body.length); @@ -51,7 +51,7 @@ function run_test() { "/api/1.1/janedoe/info/collections": service_unavailable, "/api/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()), - "/api/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()), + "/api/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()), "/user/1.0/johndoe/node/weave": weaveHandler, }); diff --git a/services/sync/tests/unit/test_service_wipeServer.js b/services/sync/tests/unit/test_service_wipeServer.js index 87f1b429f11a..b616cfcdce65 100644 --- a/services/sync/tests/unit/test_service_wipeServer.js +++ b/services/sync/tests/unit/test_service_wipeServer.js @@ -14,7 +14,7 @@ function FakeCollection() { this.deleted = false; } FakeCollection.prototype = { - handler() { + handler: function() { let self = this; return function(request, response) { let body = ""; @@ -105,7 +105,7 @@ add_identity_test(this, async function test_wipeServer_list_503() { try { Service.wipeServer(["non-existent", "steam", "petrol", "diesel"]); do_throw("Should have thrown!"); - } catch (ex) { + } catch(ex) { error = ex; } _("wipeServer() threw this exception: " + error); diff --git a/services/sync/tests/unit/test_syncedtabs.js b/services/sync/tests/unit/test_syncedtabs.js index a42561bf29da..d499ee659a31 100644 --- a/services/sync/tests/unit/test_syncedtabs.js +++ b/services/sync/tests/unit/test_syncedtabs.js @@ -107,7 +107,7 @@ add_task(async function test_clientWithTabs() { let clients = await SyncedTabs.getTabClients(); equal(clients.length, 2); - clients.sort((a, b) => { return a.name.localeCompare(b.name); }); + clients.sort((a, b) => { return a.name.localeCompare(b.name);}); equal(clients[0].tabs.length, 1); equal(clients[0].tabs[0].url, "http://foo.com/"); equal(clients[0].tabs[0].icon, "http://foo.com/favicon"); @@ -157,7 +157,7 @@ add_task(async function test_staleClientWithTabs() { guid_stale_name_desktop: "My Laptop", }); let clients = await SyncedTabs.getTabClients(); - clients.sort((a, b) => { return a.name.localeCompare(b.name); }); + clients.sort((a, b) => { return a.name.localeCompare(b.name);}); equal(clients.length, 3); equal(clients[0].name, "My Desktop"); equal(clients[0].tabs.length, 1); @@ -184,7 +184,7 @@ add_task(async function test_clientWithTabsIconsDisabled() { let clients = await SyncedTabs.getTabClients(); equal(clients.length, 1); - clients.sort((a, b) => { return a.name.localeCompare(b.name); }); + clients.sort((a, b) => { return a.name.localeCompare(b.name);}); equal(clients[0].tabs.length, 1); equal(clients[0].tabs[0].url, "http://foo.com/"); // expect the default favicon (empty string) due to the pref being false. diff --git a/services/sync/tests/unit/test_syncengine_sync.js b/services/sync/tests/unit/test_syncengine_sync.js index 6b8a4a4a3341..4e2e6e906d22 100644 --- a/services/sync/tests/unit/test_syncengine_sync.js +++ b/services/sync/tests/unit/test_syncengine_sync.js @@ -342,9 +342,9 @@ add_task(async function test_processIncoming_reconcile() { long_original: "Long Original Entry", nukeme: "Nuke me!"}; // Make this record 1 min old, thus older than the one on the server - engine._tracker.addChangedID('newerserver', Date.now() / 1000 - 60); + engine._tracker.addChangedID('newerserver', Date.now()/1000 - 60); // This record has been changed 2 mins later than the one on the server - engine._tracker.addChangedID('olderidentical', Date.now() / 1000); + engine._tracker.addChangedID('olderidentical', Date.now()/1000); let meta_global = Service.recordManager.set(engine.metaURL, new WBORecord(engine.metaURL)); @@ -614,7 +614,7 @@ add_task(async function test_processIncoming_mobile_batchSize() { let collection = new ServerCollection(); collection.get_log = []; collection._get = collection.get; - collection.get = function(options) { + collection.get = function (options) { this.get_log.push(options); return this._get(options); }; @@ -623,9 +623,9 @@ add_task(async function test_processIncoming_mobile_batchSize() { // 10 minutes old. for (let i = 0; i < 234; i++) { let id = 'record-no-' + i; - let payload = encryptPayload({id, denomination: "Record No. " + i}); + let payload = encryptPayload({id: id, denomination: "Record No. " + i}); let wbo = new ServerWBO(id, payload); - wbo.modified = Date.now() / 1000 - 60 * (i + 10); + wbo.modified = Date.now()/1000 - 60*(i+10); collection.insertWBO(wbo); } @@ -661,12 +661,12 @@ add_task(async function test_processIncoming_mobile_batchSize() { do_check_eq(collection.get_log[1].full, undefined); do_check_eq(collection.get_log[1].limit, undefined); for (let i = 1; i <= Math.floor(234 / MOBILE_BATCH_SIZE); i++) { - do_check_eq(collection.get_log[i + 1].full, 1); - do_check_eq(collection.get_log[i + 1].limit, undefined); + do_check_eq(collection.get_log[i+1].full, 1); + do_check_eq(collection.get_log[i+1].limit, undefined); if (i < Math.floor(234 / MOBILE_BATCH_SIZE)) - do_check_eq(collection.get_log[i + 1].ids.length, MOBILE_BATCH_SIZE); + do_check_eq(collection.get_log[i+1].ids.length, MOBILE_BATCH_SIZE); else - do_check_eq(collection.get_log[i + 1].ids.length, 234 % MOBILE_BATCH_SIZE); + do_check_eq(collection.get_log[i+1].ids.length, 234 % MOBILE_BATCH_SIZE); } } finally { @@ -695,9 +695,9 @@ add_task(async function test_processIncoming_store_toFetch() { // Let's create three batches worth of server side records. for (var i = 0; i < MOBILE_BATCH_SIZE * 3; i++) { let id = 'record-no-' + i; - let payload = encryptPayload({id, denomination: "Record No. " + id}); + let payload = encryptPayload({id: id, denomination: "Record No. " + id}); let wbo = new ServerWBO(id, payload); - wbo.modified = Date.now() / 1000 + 60 * (i - MOBILE_BATCH_SIZE * 3); + wbo.modified = Date.now()/1000 + 60 * (i - MOBILE_BATCH_SIZE * 3); collection.insertWBO(wbo); } @@ -761,7 +761,7 @@ add_task(async function test_processIncoming_resume_toFetch() { denomination: "Rekonstruktionslokomotive"})); for (let i = 0; i < 3; i++) { let id = 'failed' + i; - let payload = encryptPayload({id, denomination: "Record No. " + i}); + let payload = encryptPayload({id: id, denomination: "Record No. " + i}); let wbo = new ServerWBO(id, payload); wbo.modified = LASTSYNC - 10; collection.insertWBO(wbo); @@ -820,7 +820,7 @@ add_task(async function test_processIncoming_applyIncomingBatchSize_smaller() { let engine = makeRotaryEngine(); engine.applyIncomingBatchSize = APPLY_BATCH_SIZE; engine._store._applyIncomingBatch = engine._store.applyIncomingBatch; - engine._store.applyIncomingBatch = function(records) { + engine._store.applyIncomingBatch = function (records) { let failed1 = records.shift(); let failed2 = records.pop(); this._applyIncomingBatch(records); @@ -831,7 +831,7 @@ add_task(async function test_processIncoming_applyIncomingBatchSize_smaller() { let collection = new ServerCollection(); for (let i = 0; i < APPLY_BATCH_SIZE - 1; i++) { let id = 'record-no-' + i; - let payload = encryptPayload({id, denomination: "Record No. " + id}); + let payload = encryptPayload({id: id, denomination: "Record No. " + id}); collection.insert(id, payload); } @@ -877,7 +877,7 @@ add_task(async function test_processIncoming_applyIncomingBatchSize_multiple() { engine.applyIncomingBatchSize = APPLY_BATCH_SIZE; let batchCalls = 0; engine._store._applyIncomingBatch = engine._store.applyIncomingBatch; - engine._store.applyIncomingBatch = function(records) { + engine._store.applyIncomingBatch = function (records) { batchCalls += 1; do_check_eq(records.length, APPLY_BATCH_SIZE); this._applyIncomingBatch.apply(this, arguments); @@ -887,7 +887,7 @@ add_task(async function test_processIncoming_applyIncomingBatchSize_multiple() { let collection = new ServerCollection(); for (let i = 0; i < APPLY_BATCH_SIZE * 3; i++) { let id = 'record-no-' + i; - let payload = encryptPayload({id, denomination: "Record No. " + id}); + let payload = encryptPayload({id: id, denomination: "Record No. " + id}); collection.insert(id, payload); } @@ -930,7 +930,7 @@ add_task(async function test_processIncoming_notify_count() { let engine = makeRotaryEngine(); engine.applyIncomingBatchSize = APPLY_BATCH_SIZE; engine._store._applyIncomingBatch = engine._store.applyIncomingBatch; - engine._store.applyIncomingBatch = function(records) { + engine._store.applyIncomingBatch = function (records) { engine._store._applyIncomingBatch(records.slice(1)); return [records[0].id]; }; @@ -939,7 +939,7 @@ add_task(async function test_processIncoming_notify_count() { let collection = new ServerCollection(); for (var i = 0; i < NUMBER_OF_RECORDS; i++) { let id = 'record-no-' + i; - let payload = encryptPayload({id, denomination: "Record No. " + id}); + let payload = encryptPayload({id: id, denomination: "Record No. " + id}); collection.insert(id, payload); } @@ -1020,7 +1020,7 @@ add_task(async function test_processIncoming_previousFailed() { let engine = makeRotaryEngine(); engine.mobileGUIDFetchBatchSize = engine.applyIncomingBatchSize = APPLY_BATCH_SIZE; engine._store._applyIncomingBatch = engine._store.applyIncomingBatch; - engine._store.applyIncomingBatch = function(records) { + engine._store.applyIncomingBatch = function (records) { engine._store._applyIncomingBatch(records.slice(2)); return [records[0].id, records[1].id]; }; @@ -1029,7 +1029,7 @@ add_task(async function test_processIncoming_previousFailed() { let collection = new ServerCollection(); for (var i = 0; i < NUMBER_OF_RECORDS; i++) { let id = 'record-no-' + i; - let payload = encryptPayload({id, denomination: "Record No. " + i}); + let payload = encryptPayload({id: id, denomination: "Record No. " + i}); collection.insert(id, payload); } @@ -1103,9 +1103,9 @@ add_task(async function test_processIncoming_failed_records() { const NUMBER_OF_RECORDS = MOBILE_BATCH_SIZE * 3 + 5; for (let i = 0; i < NUMBER_OF_RECORDS; i++) { let id = 'record-no-' + i; - let payload = encryptPayload({id, denomination: "Record No. " + id}); + let payload = encryptPayload({id: id, denomination: "Record No. " + id}); let wbo = new ServerWBO(id, payload); - wbo.modified = Date.now() / 1000 + 60 * (i - MOBILE_BATCH_SIZE * 3); + wbo.modified = Date.now()/1000 + 60 * (i - MOBILE_BATCH_SIZE * 3); collection.insertWBO(wbo); } @@ -1131,7 +1131,7 @@ add_task(async function test_processIncoming_failed_records() { return this.__reconcile.apply(this, arguments); }; engine._store._applyIncoming = engine._store.applyIncoming; - engine._store.applyIncoming = function(record) { + engine._store.applyIncoming = function (record) { if (BOGUS_RECORDS.indexOf(record.id) % 2 == 1) { throw "I don't like this record! Baaaaaah!"; } @@ -1249,7 +1249,7 @@ add_task(async function test_processIncoming_decrypt_failed() { // Patch the fake crypto service to throw on the record above. Svc.Crypto._decrypt = Svc.Crypto.decrypt; - Svc.Crypto.decrypt = function(ciphertext) { + Svc.Crypto.decrypt = function (ciphertext) { if (ciphertext == "Decrypt this!") { throw "Derp! Cipher finalized failed. Im ur crypto destroyin ur recordz."; } @@ -1539,7 +1539,7 @@ add_task(async function test_uploadOutgoing_MAX_UPLOAD_RECORDS() { } // Ensure that the uploads were performed in batches of MAX_UPLOAD_RECORDS. - do_check_eq(noOfUploads, Math.ceil(234 / MAX_UPLOAD_RECORDS)); + do_check_eq(noOfUploads, Math.ceil(234/MAX_UPLOAD_RECORDS)); } finally { await cleanAndGo(engine, server); @@ -1554,7 +1554,7 @@ add_task(async function test_uploadOutgoing_largeRecords() { let engine = makeRotaryEngine(); engine.allowSkippedRecord = false; - engine._store.items["large-item"] = "Y".repeat(MAX_UPLOAD_BYTES * 2); + engine._store.items["large-item"] = "Y".repeat(MAX_UPLOAD_BYTES*2); engine._tracker.addChangedID("large-item", 0); collection.insert("large-item"); @@ -1661,7 +1661,7 @@ add_task(async function test_syncFinish_deleteLotsInBatches() { let now = Date.now(); for (var i = 0; i < 234; i++) { let id = 'record-no-' + i; - let payload = encryptPayload({id, denomination: "Record No. " + i}); + let payload = encryptPayload({id: id, denomination: "Record No. " + i}); let wbo = new ServerWBO(id, payload); wbo.modified = now / 1000 - 60 * (i + 110); collection.insertWBO(wbo); @@ -1853,7 +1853,7 @@ add_task(async function test_syncapplied_observer() { let collection = new ServerCollection(); for (var i = 0; i < NUMBER_OF_RECORDS; i++) { let id = 'record-no-' + i; - let payload = encryptPayload({id, denomination: "Record No. " + id}); + let payload = encryptPayload({id: id, denomination: "Record No. " + id}); collection.insert(id, payload); } diff --git a/services/sync/tests/unit/test_syncscheduler.js b/services/sync/tests/unit/test_syncscheduler.js index 949e5e10e885..2e81a5f2455d 100644 --- a/services/sync/tests/unit/test_syncscheduler.js +++ b/services/sync/tests/unit/test_syncscheduler.js @@ -208,13 +208,13 @@ add_identity_test(this, async function test_masterpassword_locked_retry_interval let rescheduleInterval = false; let oldScheduleAtInterval = SyncScheduler.prototype.scheduleAtInterval; - SyncScheduler.prototype.scheduleAtInterval = function(interval) { + SyncScheduler.prototype.scheduleAtInterval = function (interval) { rescheduleInterval = true; do_check_eq(interval, MASTER_PASSWORD_LOCKED_RETRY_INTERVAL); }; let oldVerifyLogin = Service.verifyLogin; - Service.verifyLogin = function() { + Service.verifyLogin = function () { Status.login = MASTER_PASSWORD_LOCKED; return false; }; diff --git a/services/sync/tests/unit/test_syncstoragerequest.js b/services/sync/tests/unit/test_syncstoragerequest.js index 02b7af7b20b8..14e5daade702 100644 --- a/services/sync/tests/unit/test_syncstoragerequest.js +++ b/services/sync/tests/unit/test_syncstoragerequest.js @@ -50,7 +50,7 @@ add_test(function test_user_agent_mobile() { Services.appinfo.appBuildID + ".mobile"; let request = new SyncStorageRequest(server.baseURI + "/resource"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 200); do_check_eq(handler.request.getHeader("User-Agent"), expectedUA); @@ -66,7 +66,7 @@ add_test(function test_auth() { setBasicCredentials("johndoe", "ilovejane", "XXXXXXXXX"); let request = Service.getStorageRequest(server.baseURI + "/resource"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 200); do_check_true(basic_auth_matches(handler.request, "johndoe", "ilovejane")); @@ -90,7 +90,7 @@ add_test(function test_weave_timestamp() { do_check_eq(SyncStorageRequest.serverTime, undefined); let request = new SyncStorageRequest(server.baseURI + "/resource"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 200); do_check_eq(SyncStorageRequest.serverTime, TIMESTAMP); @@ -116,7 +116,7 @@ add_test(function test_weave_backoff() { }); let request = new SyncStorageRequest(server.baseURI + "/resource"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 200); do_check_eq(backoffInterval, 600); @@ -141,7 +141,7 @@ add_test(function test_weave_quota_notice() { }); let request = new SyncStorageRequest(server.baseURI + "/resource"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 200); do_check_eq(quotaValue, 1048576); @@ -166,7 +166,7 @@ add_test(function test_weave_quota_error() { Svc.Obs.add("weave:service:quota:remaining", onQuota); let request = new SyncStorageRequest(server.baseURI + "/resource"); - request.get(function(error) { + request.get(function (error) { do_check_eq(error, null); do_check_eq(this.response.status, 400); do_check_eq(quotaValue, undefined); @@ -187,7 +187,7 @@ add_test(function test_abort() { let request = new SyncStorageRequest(server.baseURI + "/resource"); // Aborting a request that hasn't been sent yet is pointless and will throw. - do_check_throws(function() { + do_check_throws(function () { request.abort(); }); @@ -204,11 +204,11 @@ add_test(function test_abort() { do_check_eq(request.status, request.ABORTED); // Aborting an already aborted request is pointless and will throw. - do_check_throws(function() { + do_check_throws(function () { request.abort(); }); - Utils.nextTick(function() { + Utils.nextTick(function () { // Verify that we didn't try to process any of the values. do_check_eq(SyncStorageRequest.serverTime, undefined); diff --git a/services/sync/tests/unit/test_tab_engine.js b/services/sync/tests/unit/test_tab_engine.js index d9badd745a73..03733247a3b6 100644 --- a/services/sync/tests/unit/test_tab_engine.js +++ b/services/sync/tests/unit/test_tab_engine.js @@ -56,7 +56,7 @@ add_task(async function test_tab_engine_skips_incoming_local_record() { let apply = store.applyIncoming; let applied = []; - store.applyIncoming = function(record) { + store.applyIncoming = function (record) { notEqual(record.id, localID, "Only apply tab records from remote clients"); applied.push(record); apply.call(store, record); @@ -90,7 +90,7 @@ add_task(async function test_tab_engine_skips_incoming_local_record() { let promiseFinished = new Promise(resolve => { let syncFinish = engine._syncFinish; - engine._syncFinish = function() { + engine._syncFinish = function () { equal(applied.length, 1, "Remote client record was applied"); equal(applied[0].id, remoteID, "Remote client ID matches"); diff --git a/services/sync/tests/unit/test_tab_store.js b/services/sync/tests/unit/test_tab_store.js index 86844bd7aaa3..93b60f0c7a2b 100644 --- a/services/sync/tests/unit/test_tab_store.js +++ b/services/sync/tests/unit/test_tab_store.js @@ -95,7 +95,7 @@ function test_createRecord() { let tabs = store.getAllTabs(); let tabsize = JSON.stringify(tabs[0]).length; - let numtabs = Math.ceil(20000. / 77.); + let numtabs = Math.ceil(20000./77.); store.getWindowEnumerator = mockGetWindowEnumerator.bind(this, "http://foo.com", 1, 1); record = store.createRecord("fake-guid"); diff --git a/services/sync/tests/unit/test_tab_tracker.js b/services/sync/tests/unit/test_tab_tracker.js index 8147d616a027..f98920a44566 100644 --- a/services/sync/tests/unit/test_tab_tracker.js +++ b/services/sync/tests/unit/test_tab_tracker.js @@ -12,20 +12,20 @@ function fakeSvcWinMediator() { let logs = []; delete Services.wm; Services.wm = { - getEnumerator() { + getEnumerator: function() { return { cnt: 2, - hasMoreElements() { + hasMoreElements: function() { return this.cnt-- > 0; }, - getNext() { + getNext: function() { let elt = {addTopics: [], remTopics: [], numAPL: 0, numRPL: 0}; logs.push(elt); return { - addEventListener(topic) { + addEventListener: function(topic) { elt.addTopics.push(topic); }, - removeEventListener(topic) { + removeEventListener: function(topic) { elt.remTopics.push(topic); }, gBrowser: { @@ -96,7 +96,7 @@ function run_test() { do_check_false(tracker.modified); // Send a fake tab event - tracker.onTab({type: evttype, originalTarget: evttype}); + tracker.onTab({type: evttype , originalTarget: evttype}); do_check_true(tracker.modified); do_check_true(Utils.deepEquals(Object.keys(engine.getChangedIDs()), [clientsEngine.localID])); diff --git a/services/sync/tests/unit/test_telemetry.js b/services/sync/tests/unit/test_telemetry.js index 7c78d28565ff..e1d5c5bb2ad2 100644 --- a/services/sync/tests/unit/test_telemetry.js +++ b/services/sync/tests/unit/test_telemetry.js @@ -77,7 +77,7 @@ add_identity_test(this, async function test_basic() { let handlers = { "/1.1/johndoe/info/collections": helper.handler, "/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()), - "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()) + "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()) }; let collections = ["clients", "bookmarks", "forms", "history", "passwords", "prefs", "tabs"]; @@ -123,7 +123,7 @@ add_task(async function test_processIncoming_error() { pingPayload = errPing; fullPing = fullErrPing; }); - } catch (ex) { + } catch(ex) { error = ex; } ok(!!error); @@ -485,7 +485,7 @@ add_identity_test(this, async function test_discarding() { let handlers = { "/1.1/johndoe/info/collections": helper.handler, "/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()), - "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()) + "/1.1/johndoe/storage/meta/global": upd("meta", new ServerWBO("global").handler()) }; let collections = ["clients", "bookmarks", "forms", "history", "passwords", "prefs", "tabs"]; diff --git a/services/sync/tests/unit/test_utils_catch.js b/services/sync/tests/unit/test_utils_catch.js index 131286407d44..5f50bf7e43c1 100644 --- a/services/sync/tests/unit/test_utils_catch.js +++ b/services/sync/tests/unit/test_utils_catch.js @@ -7,15 +7,15 @@ function run_test() { let obj = { catch: Utils.catch, _log: { - debug(str) { + debug: function(str) { didThrow = str.search(/^Exception/) == 0; }, - info(str) { + info: function(str) { wasLocked = str.indexOf("Cannot start sync: already syncing?") == 0; } }, - func() { + func: function() { return this.catch(function() { rightThis = this == obj; didCall = true; @@ -23,7 +23,7 @@ function run_test() { })(); }, - throwy() { + throwy: function() { return this.catch(function() { rightThis = this == obj; didCall = true; @@ -31,7 +31,7 @@ function run_test() { })(); }, - callbacky() { + callbacky: function() { return this.catch(function() { rightThis = this == obj; didCall = true; @@ -41,11 +41,11 @@ function run_test() { })(); }, - lockedy() { + lockedy: function() { return this.catch(function() { rightThis = this == obj; didCall = true; - throw ("Could not acquire lock."); + throw("Could not acquire lock."); })(); } }; diff --git a/services/sync/tests/unit/test_utils_json.js b/services/sync/tests/unit/test_utils_json.js index d9697fe9fdc5..8219d4b4a045 100644 --- a/services/sync/tests/unit/test_utils_json.js +++ b/services/sync/tests/unit/test_utils_json.js @@ -66,8 +66,8 @@ add_test(function test_nonexistent_file() { add_test(function test_save_logging() { _("Verify that writes are logged."); let trace; - Utils.jsonSave("log", {_log: {trace(msg) { trace = msg; }}}, - "hi", ensureThrows(function() { + Utils.jsonSave("log", {_log: {trace: function(msg) { trace = msg; }}}, + "hi", ensureThrows(function () { do_check_true(!!trace); run_next_test(); })); @@ -93,10 +93,10 @@ add_test(function test_load_logging() { let trace, debug; let obj = { _log: { - trace(msg) { + trace: function(msg) { trace = msg; }, - debug(msg) { + debug: function(msg) { debug = msg; } } diff --git a/services/sync/tests/unit/test_utils_lock.js b/services/sync/tests/unit/test_utils_lock.js index 06b89549edc3..d1830787e63a 100644 --- a/services/sync/tests/unit/test_utils_lock.js +++ b/services/sync/tests/unit/test_utils_lock.js @@ -13,7 +13,7 @@ function run_test() { let state, lockState, lockedState, unlockState; let obj = { _lock: Utils.lock, - lock() { + lock: function() { lockState = ++state; if (this._locked) { lockedState = ++state; @@ -22,12 +22,12 @@ function run_test() { this._locked = true; return true; }, - unlock() { + unlock: function() { unlockState = ++state; this._locked = false; }, - func() { + func: function() { return this._lock("Test utils lock", function() { rightThis = this == obj; @@ -36,7 +36,7 @@ function run_test() { })(); }, - throwy() { + throwy: function() { return this._lock("Test utils lock throwy", function() { rightThis = this == obj; @@ -63,7 +63,8 @@ function run_test() { try { ret = obj.throwy(); do_throw("throwy internal call should have thrown!"); - } catch (ex) { + } + catch(ex) { // Should throw an Error, not a string. do_check_begins(ex, "Could not acquire lock"); } diff --git a/services/sync/tests/unit/test_utils_notify.js b/services/sync/tests/unit/test_utils_notify.js index 74f2ca0467a9..5bd38da5f272 100644 --- a/services/sync/tests/unit/test_utils_notify.js +++ b/services/sync/tests/unit/test_utils_notify.js @@ -6,10 +6,10 @@ function run_test() { let obj = { notify: Utils.notify("foo:"), _log: { - trace() {} + trace: function() {} }, - func() { + func: function() { return this.notify("bar", "baz", function() { rightThis = this == obj; didCall = true; @@ -17,7 +17,7 @@ function run_test() { })(); }, - throwy() { + throwy: function() { return this.notify("bad", "one", function() { rightThis = this == obj; didCall = true; @@ -29,7 +29,7 @@ function run_test() { let state = 0; let makeObs = function(topic) { let obj = { - observe(subject, topic, data) { + observe: function(subject, topic, data) { this.state = ++state; this.subject = subject; this.topic = topic; @@ -75,7 +75,8 @@ function run_test() { try { ret = obj.throwy(); do_throw("throwy should have thrown!"); - } catch (ex) { + } + catch(ex) { do_check_eq(ex, 10); } do_check_eq(ret, null); diff --git a/services/sync/tests/unit/test_warn_on_truncated_response.js b/services/sync/tests/unit/test_warn_on_truncated_response.js index 0bddc644268e..1f0d87ba96f2 100644 --- a/services/sync/tests/unit/test_warn_on_truncated_response.js +++ b/services/sync/tests/unit/test_warn_on_truncated_response.js @@ -28,7 +28,7 @@ function contentHandler(request, response) { function getWarningMessages(log) { let warnMessages = []; let warn = log.warn; - log.warn = function(message) { + log.warn = function (message) { let regEx = /The response body\'s length of: \d+ doesn\'t match the header\'s content-length of: \d+/i if (message.match(regEx)) { warnMessages.push(message); @@ -60,7 +60,7 @@ add_test(function test_async_resource_logs_content_length_mismatch() { let warnMessages = getWarningMessages(asyncResource._log); - asyncResource.get(function(error, content) { + asyncResource.get(function (error, content) { equal(error, null); equal(content, BODY); notEqual(warnMessages.length, 0, "test that warning was logged"); @@ -85,7 +85,7 @@ add_test(function test_sync_storage_request_logs_content_length_mismatch() { // content-length mismatch. request.charset = ""; - request.get(function(error) { + request.get(function (error) { equal(error, null); equal(this.response.body, BODY); notEqual(warnMessages.length, 0, "test that a warning was logged"); diff --git a/services/sync/tps/extensions/tps/components/tps-cmdline.js b/services/sync/tps/extensions/tps/components/tps-cmdline.js index 233df5200889..aaa9870ba8c1 100644 --- a/services/sync/tps/extensions/tps/components/tps-cmdline.js +++ b/services/sync/tps/extensions/tps/components/tps-cmdline.js @@ -69,7 +69,7 @@ TPSCmdLineHandler.prototype = { let uri = cmdLine.resolveURI(uristr).spec; TPS.RunTestPhase(uri, phase, logfile, options); - // cmdLine.preventDefault = true; + //cmdLine.preventDefault = true; }, helpInfo : " --tps Run TPS tests with the given test file.\n" + @@ -80,7 +80,7 @@ TPSCmdLineHandler.prototype = { var TPSCmdLineFactory = { - createInstance(outer, iid) { + createInstance : function(outer, iid) { if (outer != null) { throw new Error(Components.results.NS_ERROR_NO_AGGREGATION); } @@ -91,7 +91,7 @@ var TPSCmdLineFactory = { var TPSCmdLineModule = { - registerSelf(compMgr, fileSpec, location, type) { + registerSelf : function(compMgr, fileSpec, location, type) { compMgr = compMgr.QueryInterface(nsIComponentRegistrar); compMgr.registerFactoryLocation(TPS_CMDLINE_CLSID, @@ -110,7 +110,7 @@ var TPSCmdLineModule = { TPS_CMDLINE_CONTRACTID, true, true); }, - unregisterSelf(compMgr, fileSpec, location) { + unregisterSelf : function(compMgr, fileSpec, location) { compMgr = compMgr.QueryInterface(nsIComponentRegistrar); compMgr.unregisterFactoryLocation(TPS_CMDLINE_CLSID, fileSpec); @@ -121,7 +121,7 @@ var TPSCmdLineModule = { "m-tps", true); }, - getClassObject(compMgr, cid, iid) { + getClassObject : function(compMgr, cid, iid) { if (cid.equals(TPS_CMDLINE_CLSID)) { return TPSCmdLineFactory; } @@ -133,7 +133,7 @@ var TPSCmdLineModule = { throw new Error(Components.results.NS_ERROR_NO_INTERFACE); }, - canUnload(compMgr) { + canUnload : function(compMgr) { return true; } }; diff --git a/services/sync/tps/extensions/tps/resource/logger.jsm b/services/sync/tps/extensions/tps/resource/logger.jsm index 0adb5c66997f..f4dd4bfb03fa 100644 --- a/services/sync/tps/extensions/tps/resource/logger.jsm +++ b/services/sync/tps/extensions/tps/resource/logger.jsm @@ -16,7 +16,7 @@ var Logger = { _converter: null, _potentialError: null, - init(path) { + init: function (path) { if (this._converter != null) { // we're already open! return; @@ -26,7 +26,8 @@ var Logger = { .getService(Ci.nsIPrefBranch); if (path) { prefs.setCharPref("tps.logfile", path); - } else { + } + else { path = prefs.getCharPref("tps.logfile"); } @@ -47,7 +48,7 @@ var Logger = { this._converter.init(this._foStream, "UTF-8", 0, 0); }, - write(data) { + write: function (data) { if (this._converter == null) { Cu.reportError( "TPS Logger.write called with _converter == null!"); @@ -56,7 +57,7 @@ var Logger = { this._converter.writeString(data); }, - close() { + close: function () { if (this._converter != null) { this._converter.close(); this._converter = null; @@ -64,7 +65,7 @@ var Logger = { } }, - AssertTrue(bool, msg, showPotentialError) { + AssertTrue: function(bool, msg, showPotentialError) { if (bool) { return; } @@ -76,33 +77,34 @@ var Logger = { throw new Error("ASSERTION FAILED! " + msg); }, - AssertFalse(bool, msg, showPotentialError) { + AssertFalse: function(bool, msg, showPotentialError) { return this.AssertTrue(!bool, msg, showPotentialError); }, - AssertEqual(val1, val2, msg) { + AssertEqual: function(val1, val2, msg) { if (val1 != val2) throw new Error("ASSERTION FAILED! " + msg + "; expected " + JSON.stringify(val2) + ", got " + JSON.stringify(val1)); }, - log(msg, withoutPrefix) { + log: function (msg, withoutPrefix) { dump(msg + "\n"); if (withoutPrefix) { this.write(msg + "\n"); - } else { + } + else { function pad(n, len) { let s = "0000" + n; return s.slice(-len); } let now = new Date(); - let year = pad(now.getFullYear(), 4); - let month = pad(now.getMonth() + 1, 2); - let day = pad(now.getDate(), 2); - let hour = pad(now.getHours(), 2); - let minutes = pad(now.getMinutes(), 2); - let seconds = pad(now.getSeconds(), 2); + let year = pad(now.getFullYear(), 4); + let month = pad(now.getMonth() + 1, 2); + let day = pad(now.getDate(), 2); + let hour = pad(now.getHours(), 2); + let minutes = pad(now.getMinutes(), 2); + let seconds = pad(now.getSeconds(), 2); let ms = pad(now.getMilliseconds(), 3); this.write(year + "-" + month + "-" + day + " " + @@ -111,15 +113,15 @@ var Logger = { } }, - clearPotentialError() { + clearPotentialError: function() { this._potentialError = null; }, - logPotentialError(msg) { + logPotentialError: function(msg) { this._potentialError = msg; }, - logLastPotentialError(msg) { + logLastPotentialError: function(msg) { var message = msg; if (this._potentialError) { message = this._poentialError; @@ -128,18 +130,18 @@ var Logger = { this.log("CROSSWEAVE ERROR: " + message); }, - logError(msg) { + logError: function (msg) { this.log("CROSSWEAVE ERROR: " + msg); }, - logInfo(msg, withoutPrefix) { + logInfo: function (msg, withoutPrefix) { if (withoutPrefix) this.log(msg, true); else this.log("CROSSWEAVE INFO: " + msg); }, - logPass(msg) { + logPass: function (msg) { this.log("CROSSWEAVE TEST PASS: " + msg); }, }; diff --git a/services/sync/tps/extensions/tps/resource/modules/bookmarks.jsm b/services/sync/tps/extensions/tps/resource/modules/bookmarks.jsm index 1f5e96768bfa..4f32f2319e06 100644 --- a/services/sync/tps/extensions/tps/resource/modules/bookmarks.jsm +++ b/services/sync/tps/extensions/tps/resource/modules/bookmarks.jsm @@ -34,7 +34,8 @@ var DumpBookmarks = function TPS_Bookmarks__DumpBookmarks() { /** * extend, causes a child object to inherit from a parent */ -function extend(child, supertype) { +function extend(child, supertype) +{ child.prototype.__proto__ = supertype.prototype; } @@ -92,7 +93,7 @@ PlacesItem.prototype = { "toolbar": "toolbarFolder", }, - toString() { + toString: function() { var that = this; var props = ['uri', 'title', 'location', 'folder', 'feedUri', 'siteUri', 'livemark']; var string = (this.props.type ? this.props.type + " " : "") + @@ -129,7 +130,7 @@ PlacesItem.prototype = { * * @return the node id if the item was found, otherwise -1 */ - GetPlacesNodeId(folder, type, title, uri) { + GetPlacesNodeId: function (folder, type, title, uri) { let node_id = -1; let options = PlacesUtils.history.getNewQueryOptions(); @@ -139,7 +140,7 @@ PlacesItem.prototype = { let rootNode = result.root; rootNode.containerOpen = true; - for (let j = 0; j < rootNode.childCount; j++) { + for (let j = 0; j < rootNode.childCount; j ++) { let node = rootNode.getChild(j); if (node.title == title) { if (type == null || type == undefined || node.type == type) @@ -165,7 +166,7 @@ PlacesItem.prototype = { * @return true if this object is immediately adjacent to the other object, * otherwise false */ - IsAdjacentTo(itemName, relativePos) { + IsAdjacentTo: function(itemName, relativePos) { Logger.AssertTrue(this.props.folder_id != -1 && this.props.item_id != -1, "Either folder_id or item_id was invalid"); let other_id = this.GetPlacesNodeId(this.props.folder_id, null, itemName); @@ -189,7 +190,7 @@ PlacesItem.prototype = { * * @return the item index, or -1 if there's an error */ - GetItemIndex() { + GetItemIndex: function() { if (this.props.item_id == -1) return -1; return PlacesUtils.bookmarks.getItemIndex(this.props.item_id); @@ -204,7 +205,7 @@ PlacesItem.prototype = { * with one of the bookmark root folders * @return the folder id if the folder is found, otherwise -1 */ - GetFolder(location) { + GetFolder: function(location) { let folder_parts = location.split("/"); if (!(folder_parts[0] in this._bookmarkFolders)) { return -1; @@ -217,7 +218,8 @@ PlacesItem.prototype = { folder_parts[i]); if (subfolder_id == -1) { return -1; - } else { + } + else { folder_id = subfolder_id; } } @@ -233,7 +235,7 @@ PlacesItem.prototype = { * with one of the bookmark root folders * @return the folder id if the folder was created, otherwise -1 */ - CreateFolder(location) { + CreateFolder: function(location) { let folder_parts = location.split("/"); if (!(folder_parts[0] in this._bookmarkFolders)) { return -1; @@ -247,7 +249,8 @@ PlacesItem.prototype = { if (subfolder_id == -1) { folder_id = PlacesUtils.bookmarks.createFolder(folder_id, folder_parts[i], -1); - } else { + } + else { folder_id = subfolder_id; } } @@ -263,7 +266,7 @@ PlacesItem.prototype = { * with one of the bookmark root folders * @return the folder id if the folder was found or created, otherwise -1 */ - GetOrCreateFolder(location) { + GetOrCreateFolder: function(location) { folder_id = this.GetFolder(location); if (folder_id == -1) folder_id = this.CreateFolder(location); @@ -281,7 +284,7 @@ PlacesItem.prototype = { * @return true if the actual and expected descriptions match, or if * there is no expected description; otherwise false */ - CheckDescription(expectedDescription) { + CheckDescription: function(expectedDescription) { if (expectedDescription != null) { let description = ""; if (PlacesUtils.annotations.itemHasAnnotation(this.props.item_id, @@ -312,7 +315,7 @@ PlacesItem.prototype = { * or null if this check should be skipped * @return true if this item is in the correct position, otherwise false */ - CheckPosition(before, after, last_item_pos) { + CheckPosition: function(before, after, last_item_pos) { if (after) if (!this.IsAdjacentTo(after, 1)) return false; if (before) @@ -338,7 +341,7 @@ PlacesItem.prototype = { * folders; if null, no changes are made * @return nothing if successful, otherwise an exception is thrown */ - SetLocation(location) { + SetLocation: function(location) { if (location != null) { let newfolder_id = this.GetOrCreateFolder(location); Logger.AssertTrue(newfolder_id != -1, "Location " + location + @@ -357,7 +360,7 @@ PlacesItem.prototype = { * made * @return nothing */ - SetDescription(description) { + SetDescription: function(description) { if (description != null) { if (description != "") PlacesUtils.annotations.setItemAnnotation(this.props.item_id, @@ -382,7 +385,7 @@ PlacesItem.prototype = { * the current folder * @return nothing if successful, otherwise an exception is thrown */ - SetPosition(position) { + SetPosition: function(position) { if (position != null) { let newposition = -1; if (position != -1) { @@ -404,7 +407,7 @@ PlacesItem.prototype = { * are made * @return nothing */ - SetTitle(title) { + SetTitle: function(title) { if (title != null) { PlacesUtils.bookmarks.setItemTitle(this.props.item_id, title); } @@ -434,7 +437,7 @@ Bookmark.prototype = { * changes are made * @return nothing */ - SetKeyword(keyword) { + SetKeyword: function(keyword) { if (keyword != null) { // Mirror logic from PlacesSyncUtils's updateBookmarkMetadata let entry = Async.promiseSpinningly(PlacesUtils.keywords.fetch({ @@ -444,7 +447,7 @@ Bookmark.prototype = { Async.promiseSpinningly(PlacesUtils.keywords.remove(entry)); } Async.promiseSpinningly(PlacesUtils.keywords.insert({ - keyword, + keyword: keyword, url: this.props.uri })); } @@ -460,7 +463,7 @@ Bookmark.prototype = { * in no change * @return nothing */ - SetLoadInSidebar(loadInSidebar) { + SetLoadInSidebar: function(loadInSidebar) { if (loadInSidebar == true) PlacesUtils.annotations.setItemAnnotation(this.props.item_id, "bookmarkProperties/loadInSidebar", @@ -481,7 +484,7 @@ Bookmark.prototype = { * are made * @return nothing */ - SetTitle(title) { + SetTitle: function(title) { if (title) PlacesUtils.bookmarks.setItemTitle(this.props.item_id, title); }, @@ -495,7 +498,7 @@ Bookmark.prototype = { * are made * @return nothing */ - SetUri(uri) { + SetUri: function(uri) { if (uri) { let newURI = Services.io.newURI(uri); PlacesUtils.bookmarks.changeBookmarkURI(this.props.item_id, newURI); @@ -513,7 +516,7 @@ Bookmark.prototype = { * tags are removed from this bookmark. * @return nothing */ - SetTags(tags) { + SetTags: function(tags) { if (tags != null) { let URI = Services.io.newURI(this.props.uri); PlacesUtils.tagging.untagURI(URI, null); @@ -529,7 +532,7 @@ Bookmark.prototype = { * * @return the id of the created bookmark */ - Create() { + Create: function() { this.props.folder_id = this.GetOrCreateFolder(this.props.location); Logger.AssertTrue(this.props.folder_id != -1, "Unable to create " + "bookmark, error creating folder " + this.props.location); @@ -553,7 +556,7 @@ Bookmark.prototype = { * * @return nothing */ - Update() { + Update: function() { Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null, "Invalid item_id during Remove"); this.SetDescription(this.updateProps.description); @@ -573,7 +576,7 @@ Bookmark.prototype = { * * @return the bookmark id if the bookmark was found, otherwise -1 */ - Find() { + Find: function() { this.props.folder_id = this.GetFolder(this.props.location); if (this.props.folder_id == -1) { Logger.logError("Unable to find folder " + this.props.location); @@ -627,7 +630,8 @@ Bookmark.prototype = { JSON.stringify(tags) + " for " + this.toString()); return -1; } - } catch (e) { + } + catch (e) { Logger.logPotentialError("error processing tags " + e); return -1; } @@ -647,7 +651,7 @@ Bookmark.prototype = { * * @return nothing */ - Remove() { + Remove: function() { Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null, "Invalid item_id during Remove"); PlacesUtils.bookmarks.removeItem(this.props.item_id); @@ -675,7 +679,7 @@ BookmarkFolder.prototype = { * * @return the id of the created bookmark folder */ - Create() { + Create: function() { this.props.folder_id = this.GetOrCreateFolder(this.props.location); Logger.AssertTrue(this.props.folder_id != -1, "Unable to create " + "folder, error creating parent folder " + this.props.location); @@ -694,7 +698,7 @@ BookmarkFolder.prototype = { * * @return the folder id if the folder was found, otherwise -1 */ - Find() { + Find: function() { this.props.folder_id = this.GetFolder(this.props.location); if (this.props.folder_id == -1) { Logger.logError("Unable to find folder " + this.props.location); @@ -721,7 +725,7 @@ BookmarkFolder.prototype = { * * @return nothing */ - Remove() { + Remove: function() { Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null, "Invalid item_id during Remove"); PlacesUtils.bookmarks.removeFolderChildren(this.props.item_id); @@ -736,7 +740,7 @@ BookmarkFolder.prototype = { * * @return nothing */ - Update() { + Update: function() { Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null, "Invalid item_id during Update"); this.SetLocation(this.updateProps.location); @@ -767,7 +771,7 @@ Livemark.prototype = { * * @return the id of the created livemark */ - Create() { + Create: function() { this.props.folder_id = this.GetOrCreateFolder(this.props.location); Logger.AssertTrue(this.props.folder_id != -1, "Unable to create " + "folder, error creating parent folder " + this.props.location); @@ -776,7 +780,7 @@ Livemark.prototype = { siteURI = Services.io.newURI(this.props.siteUri); let livemarkObj = {parentId: this.props.folder_id, title: this.props.livemark, - siteURI, + siteURI: siteURI, feedURI: Services.io.newURI(this.props.feedUri), index: PlacesUtils.bookmarks.DEFAULT_INDEX}; @@ -805,7 +809,7 @@ Livemark.prototype = { * * @return the item id if the livemark was found, otherwise -1 */ - Find() { + Find: function() { this.props.folder_id = this.GetFolder(this.props.location); if (this.props.folder_id == -1) { Logger.logError("Unable to find folder " + this.props.location); @@ -859,7 +863,7 @@ Livemark.prototype = { * * @return nothing */ - Update() { + Update: function() { Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null, "Invalid item_id during Update"); this.SetLocation(this.updateProps.location); @@ -876,7 +880,7 @@ Livemark.prototype = { * * @return nothing */ - Remove() { + Remove: function() { Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null, "Invalid item_id during Remove"); PlacesUtils.bookmarks.removeItem(this.props.item_id); @@ -904,7 +908,7 @@ Separator.prototype = { * * @return the id of the created separator */ - Create() { + Create: function () { this.props.folder_id = this.GetOrCreateFolder(this.props.location); Logger.AssertTrue(this.props.folder_id != -1, "Unable to create " + "folder, error creating parent folder " + this.props.location); @@ -921,7 +925,7 @@ Separator.prototype = { * * @return the item id if the separator was found, otherwise -1 */ - Find() { + Find: function () { this.props.folder_id = this.GetFolder(this.props.location); if (this.props.folder_id == -1) { Logger.logError("Unable to find folder " + this.props.location); @@ -943,19 +947,23 @@ Separator.prototype = { return -1; } expected_pos = PlacesUtils.bookmarks.getItemIndex(other_id) - 1; - } else { + } + else { expected_pos = this.props.last_item_pos + 1; } this.props.item_id = PlacesUtils.bookmarks.getIdForItemAt(this.props.folder_id, expected_pos); if (this.props.item_id == -1) { Logger.logPotentialError("No separator found at position " + expected_pos); - } else if (PlacesUtils.bookmarks.getItemType(this.props.item_id) != + } + else { + if (PlacesUtils.bookmarks.getItemType(this.props.item_id) != PlacesUtils.bookmarks.TYPE_SEPARATOR) { Logger.logPotentialError("Places item at position " + expected_pos + " is not a separator"); return -1; } + } return this.props.item_id; }, @@ -967,7 +975,7 @@ Separator.prototype = { * * @return nothing */ - Update() { + Update: function() { Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null, "Invalid item_id during Update"); this.SetLocation(this.updateProps.location); @@ -983,7 +991,7 @@ Separator.prototype = { * * @return nothing */ - Remove() { + Remove: function() { Logger.AssertTrue(this.props.item_id != -1 && this.props.item_id != null, "Invalid item_id during Update"); PlacesUtils.bookmarks.removeItem(this.props.item_id); diff --git a/services/sync/tps/extensions/tps/resource/modules/forms.jsm b/services/sync/tps/extensions/tps/resource/modules/forms.jsm index a88aaf0e7527..deb1a28a574f 100644 --- a/services/sync/tps/extensions/tps/resource/modules/forms.jsm +++ b/services/sync/tps/extensions/tps/resource/modules/forms.jsm @@ -146,7 +146,7 @@ FormData.prototype = { * 'now', and -1 is 1 hour ago) * @return the corresponding number of microseconds since the epoch */ - hours_to_us(hours) { + hours_to_us: function(hours) { return this.usSinceEpoch + (hours * 60 * 60 * 1000 * 1000); }, @@ -158,7 +158,7 @@ FormData.prototype = { * * @return nothing */ - Create() { + Create: function() { Logger.AssertTrue(this.fieldname != null && this.value != null, "Must specify both fieldname and value"); @@ -184,7 +184,7 @@ FormData.prototype = { * * @return true if this entry exists in the database, otherwise false */ - Find() { + Find: function() { return FormDB.getDataForValue(this.fieldname, this.value).then(formdata => { let status = formdata != null; if (status) { @@ -211,7 +211,7 @@ FormData.prototype = { * * @return nothing */ - Remove() { + Remove: function() { /* Right now Weave doesn't handle this correctly, see bug 568363. */ return FormDB.remove(this.id); diff --git a/services/sync/tps/extensions/tps/resource/modules/history.jsm b/services/sync/tps/extensions/tps/resource/modules/history.jsm index c952aa8ee80c..61e087abdb22 100644 --- a/services/sync/tps/extensions/tps/resource/modules/history.jsm +++ b/services/sync/tps/extensions/tps/resource/modules/history.jsm @@ -101,13 +101,13 @@ var HistoryEntry = { * the time the current Crossweave run was started * @return nothing */ - Add(item, usSinceEpoch) { + Add: function(item, usSinceEpoch) { Logger.AssertTrue("visits" in item && "uri" in item, "History entry in test file must have both 'visits' " + "and 'uri' properties"); let uri = Services.io.newURI(item.uri); let place = { - uri, + uri: uri, visits: [] }; for (let visit of item.visits) { @@ -145,7 +145,7 @@ var HistoryEntry = { * the time the current Crossweave run was started * @return true if all the visits for the uri are found, otherwise false */ - Find(item, usSinceEpoch) { + Find: function(item, usSinceEpoch) { Logger.AssertTrue("visits" in item && "uri" in item, "History entry in test file must have both 'visits' " + "and 'uri' properties"); @@ -180,13 +180,15 @@ var HistoryEntry = { * the time the current Crossweave run was started * @return nothing */ - Delete(item, usSinceEpoch) { + Delete: function(item, usSinceEpoch) { if ("uri" in item) { let uri = Services.io.newURI(item.uri); PlacesUtils.history.removePage(uri); - } else if ("host" in item) { + } + else if ("host" in item) { PlacesUtils.history.removePagesFromHost(item.host, false); - } else if ("begin" in item && "end" in item) { + } + else if ("begin" in item && "end" in item) { let cb = Async.makeSpinningCallback(); let msSinceEpoch = parseInt(usSinceEpoch / 1000); let filter = { @@ -195,9 +197,10 @@ var HistoryEntry = { }; PlacesUtils.history.removeVisitsByFilter(filter) .catch(ex => Logger.AssertTrue(false, "An error occurred while deleting history: " + ex)) - .then(result => { cb(null, result) }, err => { cb(err) }); + .then(result => {cb(null, result)}, err => {cb(err)}); Async.waitForSyncCallback(cb); - } else { + } + else { Logger.AssertTrue(false, "invalid entry in delete history"); } }, diff --git a/services/sync/tps/extensions/tps/resource/modules/passwords.jsm b/services/sync/tps/extensions/tps/resource/modules/passwords.jsm index ae55c2ce5b16..a84800babb14 100644 --- a/services/sync/tps/extensions/tps/resource/modules/passwords.jsm +++ b/services/sync/tps/extensions/tps/resource/modules/passwords.jsm @@ -60,7 +60,8 @@ function Password(props) { for (var prop in props.changes) if (prop in this.updateProps) this.updateProps[prop] = props.changes[prop]; - } else { + } + else { this.updateProps = null; } } @@ -77,7 +78,7 @@ Password.prototype = { * * @return the new login guid */ - Create() { + Create: function() { let login = new nsLoginInfo(this.props.hostname, this.props.submitURL, this.props.realm, this.props.username, this.props.password, @@ -96,7 +97,7 @@ Password.prototype = { * * @return the guid of the password if found, otherwise -1 */ - Find() { + Find: function() { let logins = Services.logins.findLogins({}, this.props.hostname, this.props.submitURL, @@ -123,7 +124,7 @@ Password.prototype = { * * @return nothing */ - Update() { + Update: function() { let oldlogin = new nsLoginInfo(this.props.hostname, this.props.submitURL, this.props.realm, @@ -149,7 +150,7 @@ Password.prototype = { * * @return nothing */ - Remove() { + Remove: function() { let login = new nsLoginInfo(this.props.hostname, this.props.submitURL, this.props.realm, diff --git a/services/sync/tps/extensions/tps/resource/modules/prefs.jsm b/services/sync/tps/extensions/tps/resource/modules/prefs.jsm index a357d3a9d4cf..286c5a6b561e 100644 --- a/services/sync/tps/extensions/tps/resource/modules/prefs.jsm +++ b/services/sync/tps/extensions/tps/resource/modules/prefs.jsm @@ -23,7 +23,7 @@ Cu.import("resource://tps/logger.jsm"); * * Initializes instance properties. */ -function Preference(props) { +function Preference (props) { Logger.AssertTrue("name" in props && "value" in props, "Preference must have both name and value"); @@ -43,14 +43,15 @@ Preference.prototype = { * * @return nothing */ - Modify() { + Modify: function() { // Determine if this pref is actually something Weave even looks at. let weavepref = WEAVE_PREF_PREFIX + this.name; try { let syncPref = prefs.getBoolPref(weavepref); if (!syncPref) prefs.setBoolPref(weavepref, true); - } catch (e) { + } + catch(e) { Logger.AssertTrue(false, "Weave doesn't sync pref " + this.name); } @@ -85,12 +86,12 @@ Preference.prototype = { * * @return nothing */ - Find() { + Find: function() { // Read the pref value. let value; try { let prefType = prefs.getPrefType(this.name); - switch (prefType) { + switch(prefType) { case Ci.nsIPrefBranch.PREF_INT: value = prefs.getIntPref(this.name); break; @@ -101,7 +102,8 @@ Preference.prototype = { value = prefs.getBoolPref(this.name); break; } - } catch (e) { + } + catch (e) { Logger.AssertTrue(false, "Error accessing pref " + this.name); } diff --git a/services/sync/tps/extensions/tps/resource/modules/tabs.jsm b/services/sync/tps/extensions/tps/resource/modules/tabs.jsm index 670c0af1e7a1..af983573f270 100644 --- a/services/sync/tps/extensions/tps/resource/modules/tabs.jsm +++ b/services/sync/tps/extensions/tps/resource/modules/tabs.jsm @@ -23,7 +23,7 @@ var BrowserTabs = { * @param uri The uri to load in the new tab * @return nothing */ - Add(uri, fn) { + Add: function(uri, fn) { // Open the uri in a new tab in the current browser window, and calls // the callback fn from the tab's onload handler. let wm = Cc["@mozilla.org/appshell/window-mediator;1"] @@ -46,7 +46,7 @@ var BrowserTabs = { * @param profile The profile to search for tabs * @return true if the specified tab could be found, otherwise false */ - Find(uri, title, profile) { + Find: function(uri, title, profile) { // Find the uri in Weave's list of tabs for the given profile. let engine = Weave.Service.engineManager.get("tabs"); for (let [guid, client] of Object.entries(engine.getAllClients())) { diff --git a/services/sync/tps/extensions/tps/resource/modules/windows.jsm b/services/sync/tps/extensions/tps/resource/modules/windows.jsm index 42ee234abd6b..d892aea566c7 100644 --- a/services/sync/tps/extensions/tps/resource/modules/windows.jsm +++ b/services/sync/tps/extensions/tps/resource/modules/windows.jsm @@ -23,7 +23,7 @@ var BrowserWindows = { * @param aPrivate The private option. * @return nothing */ - Add(aPrivate, fn) { + Add: function(aPrivate, fn) { let wm = Cc["@mozilla.org/appshell/window-mediator;1"] .getService(Ci.nsIWindowMediator); let mainWindow = wm.getMostRecentWindow("navigator:browser"); diff --git a/services/sync/tps/extensions/tps/resource/quit.js b/services/sync/tps/extensions/tps/resource/quit.js index da200a35b110..0ec5498b0bae 100644 --- a/services/sync/tps/extensions/tps/resource/quit.js +++ b/services/sync/tps/extensions/tps/resource/quit.js @@ -21,7 +21,8 @@ function canQuitApplication() { if (cancelQuit.data) { return false; } - } catch (ex) {} + } + catch (ex) {} return true; } @@ -33,24 +34,27 @@ function goQuitApplication() { const kAppStartup = '@mozilla.org/toolkit/app-startup;1'; const kAppShell = '@mozilla.org/appshell/appShellService;1'; - var appService; - var forceQuit; + var appService; + var forceQuit; if (kAppStartup in Components.classes) { appService = Components.classes[kAppStartup] .getService(Components.interfaces.nsIAppStartup); forceQuit = Components.interfaces.nsIAppStartup.eForceQuit; - } else if (kAppShell in Components.classes) { + } + else if (kAppShell in Components.classes) { appService = Components.classes[kAppShell]. getService(Components.interfaces.nsIAppShellService); forceQuit = Components.interfaces.nsIAppShellService.eForceQuit; - } else { + } + else { throw new Error('goQuitApplication: no AppStartup/appShell'); } try { appService.quit(forceQuit); - } catch (ex) { + } + catch(ex) { throw new Error('goQuitApplication: ' + ex); } diff --git a/services/sync/tps/extensions/tps/resource/tps.jsm b/services/sync/tps/extensions/tps/resource/tps.jsm index 3b62b878752f..f4cc0214aa21 100644 --- a/services/sync/tps/extensions/tps/resource/tps.jsm +++ b/services/sync/tps/extensions/tps/resource/tps.jsm @@ -137,7 +137,7 @@ var TPS = { this.delayAutoSync(); - OBSERVER_TOPICS.forEach(function(aTopic) { + OBSERVER_TOPICS.forEach(function (aTopic) { Services.obs.addObserver(this, aTopic, true); }, this); @@ -146,7 +146,8 @@ var TPS = { // Import the appropriate authentication module if (this.fxaccounts_enabled) { Cu.import("resource://tps/auth/fxaccounts.jsm", module); - } else { + } + else { Cu.import("resource://tps/auth/sync.jsm", module); } }, @@ -171,7 +172,7 @@ var TPS = { try { Logger.logInfo("----------event observed: " + topic); - switch (topic) { + switch(topic) { case "private-browsing": Logger.logInfo("private browsing " + data); break; @@ -209,7 +210,8 @@ var TPS = { Logger.logInfo("Sync error; retrying..."); this._syncErrors++; Utils.nextTick(this.RunNextTestAction, this); - } else { + } + else { this._triggeredSync = false; this.DumpError("Sync error; aborting test"); return; @@ -226,7 +228,7 @@ var TPS = { // Wait a second before continuing, otherwise we can get // 'sync not complete' errors. - Utils.namedTimer(function() { + Utils.namedTimer(function () { this.FinishAsyncOperation(); }, 1000, this, "postsync"); @@ -249,9 +251,10 @@ var TPS = { this._isTracking = false; break; } - } catch (e) { + } + catch (e) { this.DumpError("Observer failed", e); - + return; } }, @@ -287,10 +290,10 @@ var TPS = { this.goQuitApplication(); }, - HandleWindows(aWindow, action) { + HandleWindows: function (aWindow, action) { Logger.logInfo("executing action " + action.toUpperCase() + " on window " + JSON.stringify(aWindow)); - switch (action) { + switch(action) { case ACTION_ADD: BrowserWindows.Add(aWindow.private, function(win) { Logger.logInfo("window finished loading"); @@ -301,13 +304,13 @@ var TPS = { Logger.logPass("executing action " + action.toUpperCase() + " on windows"); }, - HandleTabs(tabs, action) { + HandleTabs: function (tabs, action) { this._tabsAdded = tabs.length; this._tabsFinished = 0; for (let tab of tabs) { Logger.logInfo("executing action " + action.toUpperCase() + " on tab " + JSON.stringify(tab)); - switch (action) { + switch(action) { case ACTION_ADD: // When adding tabs, we keep track of how many tabs we're adding, // and wait until we've received that many onload events from our @@ -322,7 +325,7 @@ var TPS = { // Wait a second before continuing to be sure tabs can be synced, // otherwise we can get 'error locating tab' - Utils.namedTimer(function() { + Utils.namedTimer(function () { that.FinishAsyncOperation(); }, 1000, this, "postTabsOpening"); } @@ -348,12 +351,12 @@ var TPS = { Logger.logPass("executing action " + action.toUpperCase() + " on tabs"); }, - HandlePrefs(prefs, action) { + HandlePrefs: function (prefs, action) { for (let pref of prefs) { Logger.logInfo("executing action " + action.toUpperCase() + " on pref " + JSON.stringify(pref)); let preference = new Preference(pref); - switch (action) { + switch(action) { case ACTION_MODIFY: preference.Modify(); break; @@ -367,13 +370,13 @@ var TPS = { Logger.logPass("executing action " + action.toUpperCase() + " on pref"); }, - HandleForms(data, action) { + HandleForms: function (data, action) { this.shouldValidateForms = true; for (let datum of data) { Logger.logInfo("executing action " + action.toUpperCase() + " on form entry " + JSON.stringify(datum)); let formdata = new FormData(datum, this._usSinceEpoch); - switch (action) { + switch(action) { case ACTION_ADD: Async.promiseSpinningly(formdata.Create()); break; @@ -396,12 +399,12 @@ var TPS = { " on formdata"); }, - HandleHistory(entries, action) { + HandleHistory: function (entries, action) { try { for (let entry of entries) { Logger.logInfo("executing action " + action.toUpperCase() + " on history entry " + JSON.stringify(entry)); - switch (action) { + switch(action) { case ACTION_ADD: HistoryEntry.Add(entry, this._usSinceEpoch); break; @@ -422,13 +425,14 @@ var TPS = { } Logger.logPass("executing action " + action.toUpperCase() + " on history"); - } catch (e) { + } + catch(e) { DumpHistory(); - throw (e); + throw(e); } }, - HandlePasswords(passwords, action) { + HandlePasswords: function (passwords, action) { this.shouldValidatePasswords = true; try { for (let password of passwords) { @@ -463,19 +467,20 @@ var TPS = { } Logger.logPass("executing action " + action.toUpperCase() + " on passwords"); - } catch (e) { + } + catch(e) { DumpPasswords(); - throw (e); + throw(e); } }, - HandleAddons(addons, action, state) { + HandleAddons: function (addons, action, state) { this.shouldValidateAddons = true; for (let entry of addons) { Logger.logInfo("executing action " + action.toUpperCase() + " on addon " + JSON.stringify(entry)); let addon = new Addon(this, entry); - switch (action) { + switch(action) { case ACTION_ADD: addon.install(); break; @@ -499,7 +504,7 @@ var TPS = { " on addons"); }, - HandleBookmarks(bookmarks, action) { + HandleBookmarks: function (bookmarks, action) { this.shouldValidateBookmarks = true; try { let items = []; @@ -529,13 +534,15 @@ var TPS = { if (action == ACTION_ADD) { item_id = placesItem.Create(); - } else { + } + else { item_id = placesItem.Find(); if (action == ACTION_VERIFY_NOT) { Logger.AssertTrue(item_id == -1, "places item exists but it shouldn't: " + JSON.stringify(bookmark)); - } else + } + else Logger.AssertTrue(item_id != -1, "places item not found", true); } @@ -548,7 +555,7 @@ var TPS = { for (let item of items) { Logger.logInfo("executing action " + action.toUpperCase() + " on bookmark " + JSON.stringify(item)); - switch (action) { + switch(action) { case ACTION_DELETE: item.Remove(); break; @@ -562,9 +569,10 @@ var TPS = { Logger.logPass("executing action " + action.toUpperCase() + " on bookmarks"); - } catch (e) { + } + catch (e) { DumpBookmarks(); - throw (e); + throw(e); } }, @@ -572,11 +580,13 @@ var TPS = { Logger.logInfo("mozmill endTest: " + JSON.stringify(obj)); if (obj.failed > 0) { this.DumpError('mozmill test failed, name: ' + obj.name + ', reason: ' + JSON.stringify(obj.fails)); - - } else if ('skipped' in obj && obj.skipped) { + return; + } + else if ('skipped' in obj && obj.skipped) { this.DumpError('mozmill test failed, name: ' + obj.name + ', reason: ' + obj.skipped_reason); - - } else { + return; + } + else { Utils.namedTimer(function() { this.FinishAsyncOperation(); }, 2000, this, "postmozmilltest"); @@ -723,7 +733,7 @@ var TPS = { return this.ValidateCollection("addons", AddonValidator); }, - RunNextTestAction() { + RunNextTestAction: function() { try { if (this._currentAction >= this._phaselist[this._currentPhase].length) { @@ -769,7 +779,8 @@ var TPS = { return; this._currentAction++; - } catch (e) { + } + catch(e) { if (Async.isShutdownException(e)) { if (this._requestedQuit) { Logger.logInfo("Sync aborted due to requested shutdown"); @@ -853,7 +864,7 @@ var TPS = { * @param options * Object defining addition run-time options. */ - RunTestPhase(file, phase, logpath, options) { + RunTestPhase: function (file, phase, logpath, options) { try { let settings = options || {}; @@ -883,9 +894,9 @@ var TPS = { // service:ready event, this is required to ensure all handlers have // executed. Utils.nextTick(this._executeTestPhase.bind(this, file, phase, settings)); - } catch (e) { + } catch(e) { this.DumpError("RunTestPhase failed", e); - + return; } }, @@ -946,9 +957,10 @@ var TPS = { // start processing the test actions this._currentAction = 0; - } catch (e) { + } + catch(e) { this.DumpError("_executeTestPhase failed", e); - + return; } }, @@ -1171,7 +1183,8 @@ var TPS = { if (wipeAction) { this._syncWipeAction = wipeAction; Weave.Svc.Prefs.set("firstSync", wipeAction); - } else { + } + else { Weave.Svc.Prefs.reset("firstSync"); }