From a97f338cc2026fca821d19308d3c044fb020a933 Mon Sep 17 00:00:00 2001 From: Ethan Neff Date: Fri, 16 Dec 2016 11:20:31 -0800 Subject: [PATCH] fix: remove es6 --- DEVELOPING.md | 4 - gulpfile.js | 41 +- hooks.es6/afterPrepareHook.js | 79 ---- hooks.es6/beforePluginInstallHook.js | 97 ----- hooks.es6/iosBeforePrepareHook.js | 78 ---- hooks.es6/lib/android/manifestWriter.js | 298 -------------- hooks.es6/lib/configXmlHelper.js | 118 ------ hooks.es6/lib/configXmlParser.js | 132 ------- hooks.es6/lib/ios/projectEntitlements.js | 176 --------- hooks.es6/lib/ios/xcodePreferences.js | 220 ----------- hooks.es6/lib/xmlHelper.js | 60 --- package.json | 2 - testbed/www/js.es6/index.js | 312 --------------- tests.es6/plugin.xml | 36 -- tests.es6/tests.js | 206 ---------- www.es6/branch.js | 480 ----------------------- 16 files changed, 2 insertions(+), 2337 deletions(-) delete mode 100755 hooks.es6/afterPrepareHook.js delete mode 100755 hooks.es6/beforePluginInstallHook.js delete mode 100755 hooks.es6/iosBeforePrepareHook.js delete mode 100755 hooks.es6/lib/android/manifestWriter.js delete mode 100755 hooks.es6/lib/configXmlHelper.js delete mode 100755 hooks.es6/lib/configXmlParser.js delete mode 100755 hooks.es6/lib/ios/projectEntitlements.js delete mode 100755 hooks.es6/lib/ios/xcodePreferences.js delete mode 100755 hooks.es6/lib/xmlHelper.js delete mode 100644 testbed/www/js.es6/index.js delete mode 100644 tests.es6/plugin.xml delete mode 100644 tests.es6/tests.js delete mode 100644 www.es6/branch.js diff --git a/DEVELOPING.md b/DEVELOPING.md index 3ad02145..87e8e89f 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -46,10 +46,6 @@ npm install; ### Develop -> Code in .es6 files - -### Validate - > Build ```sh diff --git a/gulpfile.js b/gulpfile.js index bd012c5f..35ab26a3 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -2,12 +2,11 @@ var gulp = require('gulp') var fs = require('fs') var sourcemaps = require('gulp-sourcemaps') -var babel = require('gulp-babel') var standard = require('gulp-standard') // primary tasks -gulp.task('predev', ['setupDev', 'babel', 'lint']) -gulp.task('prerelease', ['setupNpm', 'babel', 'lint']) +gulp.task('predev', ['setupDev', 'lint']) +gulp.task('prerelease', ['setupNpm', 'lint']) gulp.task('lint', ['standard']) // secondary tasks @@ -117,39 +116,3 @@ function emitFiles (path) { ret.push('') return ret } - -// -------------------------------------------------- -// Babel -// -------------------------------------------------- -gulp.task('babel', babelTasks) - -var babelTasks = [] -function babelize (taskName, dir) { - // copy resources and compile es6 from corresponding directories - // list of all babel tasks so we can build all of them - - babelTasks.push(taskName + '-babel') - if (!dir) { - dir = taskName - } - var srcDir = dir + '.es6/' - var srcPattern = dir + '.es6/**/*.js' - var destDir = dir + '/' - gulp.task(taskName + '-copy', function () { - return gulp.src(srcDir + '**/*.*').pipe(gulp.dest(destDir)) - }) - gulp.task(taskName + '-babel', [ taskName + '-copy' ], function () { - return gulp.src(srcPattern) - .pipe(sourcemaps.init()) - .pipe(babel({ - presets: [ 'es2015', 'stage-2' ] - })) - .pipe(gulp.dest(destDir)) - }) -} - -babelize('hooks') -babelize('www') -babelize('tests') -babelize('testbed', 'testbed/www/js') - diff --git a/hooks.es6/afterPrepareHook.js b/hooks.es6/afterPrepareHook.js deleted file mode 100755 index 34e0d815..00000000 --- a/hooks.es6/afterPrepareHook.js +++ /dev/null @@ -1,79 +0,0 @@ -/** -Hook is executed at the end of the 'prepare' stage. Usually, when you call 'cordova build'. - -It will inject required preferences in the platform-specific projects, based on -data you have specified in the projects config.xml file. -*/ - -var configParser = require('./lib/configXmlParser.js'), - androidManifestWriter = require('./lib/android/manifestWriter.js'), - // androidWebHook = require('./lib/android/webSiteHook.js'), - iosProjectEntitlements = require('./lib/ios/projectEntitlements.js'), - iosProjectPreferences = require('./lib/ios/xcodePreferences.js'), - ANDROID = 'android', - IOS = 'ios'; - -module.exports = function(ctx) { - run(ctx); -}; - -/** - * Execute hook. - * - * @param {Object} cordovaContext - cordova context object - */ -function run(cordovaContext) { - var pluginPreferences = configParser.readPreferences(cordovaContext), - platformsList = cordovaContext.opts.platforms; - - // if no preferences are found - exit - if (pluginPreferences == null) { - return; - } - - // if no host is defined - exit - if (pluginPreferences.hosts == null || pluginPreferences.hosts.length == 0) { - console.warn('No host is specified in the config.xml. Universal Links plugin is not going to work.'); - return; - } - - platformsList.forEach(function(platform) { - switch (platform) { - case ANDROID: { - activateUniversalLinksInAndroid(cordovaContext, pluginPreferences); - break; - } - case IOS: { - activateUniversalLinksInIos(cordovaContext, pluginPreferences); - break; - } - } - }); -} - -/** - * Activate Deep Links for Android application. - * - * @param {Object} cordovaContext - cordova context object - * @param {Object} pluginPreferences - plugin preferences from the config.xml file. Basically, content from tag. - */ -function activateUniversalLinksInAndroid(cordovaContext, pluginPreferences) { - // inject preferenes into AndroidManifest.xml - androidManifestWriter.writePreferences(cordovaContext, pluginPreferences); - -} - -/** - * Activate Universal Links for iOS application. - * - * @param {Object} cordovaContext - cordova context object - * @param {Object} pluginPreferences - plugin preferences from the config.xml file. Basically, content from tag. - */ -function activateUniversalLinksInIos(cordovaContext, pluginPreferences) { - // modify xcode project preferences - iosProjectPreferences.enableAssociativeDomainsCapability(cordovaContext); - - // generate entitlements file - iosProjectEntitlements.generateAssociatedDomainsEntitlements(cordovaContext, pluginPreferences); - -} diff --git a/hooks.es6/beforePluginInstallHook.js b/hooks.es6/beforePluginInstallHook.js deleted file mode 100755 index 4abccdac..00000000 --- a/hooks.es6/beforePluginInstallHook.js +++ /dev/null @@ -1,97 +0,0 @@ -'use strict'; - -// installs the node modules via npm install one at a time -// @return {callback(error)} -function installNodeModules(exec, modules, callback) { - // base case - if (modules.length <= 0) { - return callback(false); - } - - // install one at a time - var module = modules.pop(); - console.log('Installing "' + module + '"'); - - var install = 'npm install --prefix ./plugins/io.branch.sdk -D ' + module; - exec(install, function(err, stdout, stderr) { - // handle error - if (err) { - console.error('Failed to install Branch Dependency: "' + module + '"'); - return callback(true); - } - // next module - else { - installNodeModules(exec, modules, callback); - } - }); -} - -// checks to see which node modules need to be installed -// @return {[string]} of node modules from package.json.dependencies -function getNodeModulesToInstall(dependencies) { - var modules = []; - for (var module in dependencies) { - if (dependencies.hasOwnProperty(module)) { - try { - var exists = require(module); - } catch (err) { - modules.push(module); - } - } - } - return modules; -} - -// if the Branch SDK package has already been installed -// @return {boolean} based on .installed file is found -function getPackageInstalled(filesave, installFlagLocation) { - try { - var exists = filesave.readFileSync(installFlagLocation); - return true; - } catch (err) { - return false; - } -} - -// set that the Branch SDK package has been installed -// @return {void} based on .installed file is created -function setPackageInstalled(filesave, installFlagLocation) { - filesave.closeSync(filesave.openSync(installFlagLocation, 'w')); -} - -// hooks entry point -// @return {void} based on async npm install completion -module.exports = function(context) { - // properties - var q = context.requireCordovaModule('q'); - var async = new q.defer(); - var filesave = require('fs'); - var path = require('path'); - var exec = require('child_process').exec; - var installFlagName = '.installed'; - var installFlagLocation = path.join(context.opts.projectRoot, 'plugins', context.opts.plugin.id, installFlagName); - var dependencies = require(path.join(context.opts.projectRoot, 'plugins', context.opts.plugin.id, 'package.json')).dependencies; - - // only run once - if (getPackageInstalled(filesave, installFlagLocation)) { - return; - } - - // install node modules - var modules = getNodeModulesToInstall(dependencies); - installNodeModules(exec, modules, function(err) { - // handle error - if (err) { - console.error('Failed to install the Branch SDK'); - } - // only run once - else { - setPackageInstalled(filesave, installFlagLocation); - } - // async complete - async.resolve(); - }); - - // wait until callbacks from the all the npm install complete - return async.promise; -}; diff --git a/hooks.es6/iosBeforePrepareHook.js b/hooks.es6/iosBeforePrepareHook.js deleted file mode 100755 index 14d8fed5..00000000 --- a/hooks.es6/iosBeforePrepareHook.js +++ /dev/null @@ -1,78 +0,0 @@ -/* -Hook executed before the 'prepare' stage. Only for iOS project. -It will check if project name has changed. If so - it will change the name of the .entitlements file to remove that file duplicates. -If file name has no changed - hook would not do anything. -*/ - -var path = require('path'), - fs = require('fs'), - ConfigXmlHelper = require('./lib/configXmlHelper.js'); - -module.exports = function(ctx) { - run(ctx); -}; - -/** - * Run the hook logic. - * - * @param {Object} ctx - cordova context object - */ -function run(ctx) { - var projectRoot = ctx.opts.projectRoot, - iosProjectFilePath = path.join(projectRoot, 'platforms', 'ios'), - configXmlHelper = new ConfigXmlHelper(ctx), - oldProjectName = getOldProjectName(iosProjectFilePath), - newProjectName = configXmlHelper.getProjectName(); - - // if name has not changed - do nothing - if (oldProjectName.length > 0 && oldProjectName === newProjectName) { - return; - } - - console.log('Project name has changed. Renaming .entitlements file.'); - - // if it does - rename it - var oldEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', oldProjectName + '.entitlements'), - newEntitlementsFilePath = path.join(iosProjectFilePath, oldProjectName, 'Resources', newProjectName + '.entitlements'); - - try { - fs.renameSync(oldEntitlementsFilePath, newEntitlementsFilePath); - } catch (err) { - console.warn('Failed to rename .entitlements file.'); - console.warn(err); - } -} - -// region Private API - -/** - * Get old name of the project. - * Name is detected by the name of the .xcodeproj file. - * - * @param {String} projectDir absolute path to ios project directory - * @return {String} old project name - */ -function getOldProjectName(projectDir) { - var files = [], - projectName = ''; - - try { - files = fs.readdirSync(projectDir); - } catch (err) { - return ''; - } - - // find file with .xcodeproj extension, use it as an old project name - files.some(function(fileName) { - if (path.extname(fileName) === '.xcodeproj') { - projectName = path.basename(fileName, '.xcodeproj'); - return true; - } - - return false; - }); - - return projectName; -} - -// endregion diff --git a/hooks.es6/lib/android/manifestWriter.js b/hooks.es6/lib/android/manifestWriter.js deleted file mode 100755 index eef485ba..00000000 --- a/hooks.es6/lib/android/manifestWriter.js +++ /dev/null @@ -1,298 +0,0 @@ -/** -Class injects plugin preferences into AndroidManifest.xml file. -*/ -(function() { - - var path = require('path'), - xmlHelper = require('../xmlHelper.js'); - - module.exports = { - writePreferences: writePreferences - }; - - // region Public API - - /** - * Inject preferences into AndroidManifest.xml file. - * - * @param {Object} cordovaContext - cordova context object - * @param {Object} pluginPreferences - plugin preferences as JSON object; already parsed - */ - function writePreferences(cordovaContext, pluginPreferences) { - var pathToManifest = path.join(cordovaContext.opts.projectRoot, 'platforms', 'android', 'AndroidManifest.xml'), - manifestSource = xmlHelper.readXmlAsJson(pathToManifest), - cleanManifest, - updatedManifest; - - // remove old intent-filters - cleanManifest = removeOldOptions(manifestSource); - - // inject intent-filters based on plugin preferences - updatedManifest = injectOptions(cleanManifest, pluginPreferences); - - // save new version of the AndroidManifest - xmlHelper.writeJsonAsXml(updatedManifest, pathToManifest); - } - - // endregion - - // region Manifest cleanup methods - - /** - * Remove old intent-filters from the manifest file. - * - * @param {Object} manifestData - manifest content as JSON object - * @return {Object} manifest data without old intent-filters - */ - function removeOldOptions(manifestData) { - var cleanManifest = manifestData, - activities = manifestData['manifest']['application'][0]['activity']; - - activities.forEach(removeIntentFiltersFromActivity); - cleanManifest['manifest']['application'][0]['activity'] = activities; - - return cleanManifest; - } - - /** - * Remove old intent filters from the given activity. - * - * @param {Object} activity - activity, from which we need to remove intent-filters. - * Changes applied to the passed object. - */ - function removeIntentFiltersFromActivity(activity) { - var oldIntentFilters = activity['intent-filter'], - newIntentFilters = []; - if (oldIntentFilters == null || oldIntentFilters.length == 0) { - return; - } - - oldIntentFilters.forEach(function(intentFilter) { - if (!isIntentFilterForUniversalLinks(intentFilter)) { - newIntentFilters.push(intentFilter); - } - }); - - activity['intent-filter'] = newIntentFilters; - } - - /** - * Check if given intent-filter is for Universal Links. - * - * @param {Object} intentFilter - intent-filter to check - * @return {Boolean} true - if intent-filter for Universal Links; otherwise - false; - */ - function isIntentFilterForUniversalLinks(intentFilter) { - var actions = intentFilter['action'], - categories = intentFilter['category'], - data = intentFilter['data']; - - return isActionForUniversalLinks(actions) && isCategoriesForUniversalLinks(categories) && isDataTagForUniversalLinks(data); - } - - /** - * Check if actions from the intent-filter corresponds to actions for Universal Links. - * - * @param {Array} actions - list of actions in the intent-filter - * @return {Boolean} true - if action for Universal Links; otherwise - false - */ - function isActionForUniversalLinks(actions) { - // there can be only 1 action - if (actions == null || actions.length != 1) { - return false; - } - - var action = actions[0]['$']['android:name']; - - return action === 'android.intent.action.VIEW'; - } - - /** - * Check if categories in the intent-filter corresponds to categories for Universal Links. - * - * @param {Array} categories - list of categories in the intent-filter - * @return {Boolean} true - if action for Universal Links; otherwise - false - */ - function isCategoriesForUniversalLinks(categories) { - // there can be only 2 categories - if (categories == null || categories.length != 2) { - return false; - } - - var isBrowsable = false, - isDefault = false; - - // check intent categories - categories.forEach(function(category) { - var categoryName = category['$']['android:name']; - if (!isBrowsable) { - isBrowsable = categoryName === 'android.intent.category.BROWSABLE'; - } - - if (!isDefault) { - isDefault = categoryName === 'android.intent.category.DEFAULT'; - } - }); - - return isDefault && isBrowsable; - } - - /** - * Check if data tag from intent-filter corresponds to data for Universal Links. - * - * @param {Array} data - list of data tags in the intent-filter - * @return {Boolean} true - if data tag for Universal Links; otherwise - false - */ - function isDataTagForUniversalLinks(data) { - // can have only 1 data tag in the intent-filter - if (data == null || data.length != 1) { - return false; - } - - var dataHost = data[0]['$']['android:host'], - dataScheme = data[0]['$']['android:scheme'], - hostIsSet = dataHost != null && dataHost.length > 0, - schemeIsSet = dataScheme != null && dataScheme.length > 0; - - return hostIsSet && schemeIsSet; - } - - // endregion - - // region Methods to inject preferences into AndroidManifest.xml file - - /** - * Inject options into manifest file. - * - * @param {Object} manifestData - manifest content where preferences should be injected - * @param {Object} pluginPreferences - plugin preferences from config.xml; already parsed - * @return {Object} updated manifest data with corresponding intent-filters - */ - function injectOptions(manifestData, pluginPreferences) { - var changedManifest = manifestData, - targetSdk = changedManifest['manifest']['uses-sdk'][0]['$']['android:targetSdkVersion'], - activitiesList = changedManifest['manifest']['application'][0]['activity'], - launchActivityIndex = getMainLaunchActivityIndex(activitiesList), - ulIntentFilters = [], - launchActivity; - - if (launchActivityIndex < 0) { - console.warn('Could not find launch activity in the AndroidManifest file. Can\'t inject Universal Links preferences.'); - return; - } - - // get launch activity - launchActivity = activitiesList[launchActivityIndex]; - - // generate intent-filters - pluginPreferences.hosts.forEach(function(host) { - ulIntentFilters.push(createIntentFilter(host.name, host.scheme, pluginPreferences.androidPrefix, parseInt(targetSdk) >= 23)); - }); - - // add Universal Links intent-filters to the launch activity - launchActivity['intent-filter'] = launchActivity['intent-filter'].concat(ulIntentFilters); - - return changedManifest; - } - - /** - * Find index of the applications launcher activity. - * - * @param {Array} activities - list of all activities in the app - * @return {Integer} index of the launch activity; -1 - if none was found - */ - function getMainLaunchActivityIndex(activities) { - var launchActivityIndex = -1; - activities.some(function(activity, index) { - if (isLaunchActivity(activity)) { - launchActivityIndex = index; - return true; - } - - return false; - }); - - return launchActivityIndex; - } - - /** - * Check if the given actvity is a launch activity. - * - * @param {Object} activity - activity to check - * @return {Boolean} true - if this is a launch activity; otherwise - false - */ - function isLaunchActivity(activity) { - var intentFilters = activity['intent-filter'], - isLauncher = false; - - if (intentFilters == null || intentFilters.length == 0) { - return false; - } - - isLauncher = intentFilters.some(function(intentFilter) { - var action = intentFilter['action'], - category = intentFilter['category']; - - if (action == null || action.length != 1 || category == null || category.length != 1) { - return false; - } - - var isMainAction = (action[0]['$']['android:name'] === 'android.intent.action.MAIN'), - isLauncherCategory = (category[0]['$']['android:name'] === 'android.intent.category.LAUNCHER'); - - return isMainAction && isLauncherCategory; - }); - - return isLauncher; - } - - /** - * Create JSON object that represent intent-filter for universal link. - * - * @param {String} host - host name - * @param {String} scheme - host scheme - * @param {String} pathName - host path - * @return {Object} intent-filter as a JSON object - */ - function createIntentFilter(host, scheme, pathPrefix, androidM) { - var intentFilter = { - '$': { - 'android:autoVerify': 'true' - }, - 'action': [ { - '$': { - 'android:name': 'android.intent.action.VIEW' - } - } ], - 'category': [ { - '$': { - 'android:name': 'android.intent.category.DEFAULT' - } - }, { - '$': { - 'android:name': 'android.intent.category.BROWSABLE' - } - } ], - 'data': [ { - '$': { - 'android:host': host, - 'android:scheme': scheme, - 'android:pathPrefix': pathPrefix - } - } ] - }; - - if (!pathPrefix) { - delete intentFilter['data'][0]['$']['android:pathPrefix']; - } - - if (!androidM) { - delete intentFilter['$']['android:autoVerify']; - } - - return intentFilter; - } - - // endregion - -})(); diff --git a/hooks.es6/lib/configXmlHelper.js b/hooks.es6/lib/configXmlHelper.js deleted file mode 100755 index 6d94f0b1..00000000 --- a/hooks.es6/lib/configXmlHelper.js +++ /dev/null @@ -1,118 +0,0 @@ -/* -Helper class to read data from config.xml file. -*/ -(function() { - var path = require('path'), - xmlHelper = require('./xmlHelper.js'), - ANDROID = 'android', - IOS = 'ios', - CONFIG_FILE_NAME = 'config.xml', - context, - projectRoot; - - module.exports = ConfigXmlHelper; - - // region public API - - /** - * Constructor. - * - * @param {Object} cordovaContext - cordova context object - */ - function ConfigXmlHelper(cordovaContext) { - context = cordovaContext; - projectRoot = context.opts.projectRoot; - } - - /** - * Read config.xml data as JSON object. - * - * @return {Object} JSON object with data from config.xml - */ - ConfigXmlHelper.prototype.read = function() { - var filePath = getConfigXmlFilePath(); - - return xmlHelper.readXmlAsJson(filePath); - } - - /** - * Get package name for the application. Depends on the platform. - * - * @param {String} platform - 'ios' or 'android'; for what platform we need a package name - * @return {String} package/bundle name - */ - ConfigXmlHelper.prototype.getPackageName = function(platform) { - var configFilePath = getConfigXmlFilePath(), - config = getCordovaConfigParser(configFilePath), - packageName; - - switch (platform) { - case ANDROID: { - packageName = config.android_packageName(); - break; - } - case IOS: { - packageName = config.ios_CFBundleIdentifier(); - break; - } - } - if (packageName === undefined || packageName.length == 0) { - packageName = config.packageName(); - } - - return packageName; - } - - /** - * Get name of the current project. - * - * @return {String} name of the project - */ - ConfigXmlHelper.prototype.getProjectName = function() { - return getProjectName(); - } - - // endregion - - // region Private API - - /** - * Get config parser from cordova library. - * - * @param {String} configFilePath absolute path to the config.xml file - * @return {Object} - */ - function getCordovaConfigParser(configFilePath) { - var ConfigParser; - - // If we are running Cordova 5.4 or abova - use parser from cordova-common. - // Otherwise - from cordova-lib. - try { - ConfigParser = context.requireCordovaModule('cordova-common/src/ConfigParser/ConfigParser'); - } catch (e) { - ConfigParser = context.requireCordovaModule('cordova-lib/src/configparser/ConfigParser') - } - - return new ConfigParser(configFilePath); - } - - /** - * Get absolute path to the config.xml. - */ - function getConfigXmlFilePath() { - return path.join(projectRoot, CONFIG_FILE_NAME); - } - - /** - * Get project name from config.xml - */ - function getProjectName() { - var configFilePath = getConfigXmlFilePath(), - config = getCordovaConfigParser(configFilePath); - - return config.name(); - } - - // endregion - -})(); diff --git a/hooks.es6/lib/configXmlParser.js b/hooks.es6/lib/configXmlParser.js deleted file mode 100755 index 35da7a04..00000000 --- a/hooks.es6/lib/configXmlParser.js +++ /dev/null @@ -1,132 +0,0 @@ -/* -Parser for config.xml file. Read plugin-specific preferences (from tag) as JSON object. -*/ -(function() { - - var path = require('path'), - fs = require('fs'), - xml2js = require('xml2js'), - ConfigXmlHelper = require('./configXmlHelper.js'), - DEFAULT_SCHEME = 'http'; - - module.exports = { - readPreferences: readPreferences - }; - - // region Public API - - /** - * Read plugin preferences from the config.xml file. - * - * @param {Object} cordovaContext - cordova context object - * @return {Array} list of host objects - */ - function readPreferences(cordovaContext) { - // read data from projects root config.xml file - var configXml = new ConfigXmlHelper(cordovaContext).read(); - if (configXml == null) { - console.warn('config.xml not found! Please, check that it exist\'s in your project\'s root directory.'); - return null; - } - - // look for data from the tag - var ulXmlPreferences = configXml.widget['branch-config']; - if (ulXmlPreferences == null || ulXmlPreferences.length == 0) { - console.warn(' tag is not set in the config.xml. Universal Links plugin is not going to work.'); - return null; - } - - var xmlPreferences = ulXmlPreferences[0]; - - // read hosts - var hosts = constructHostsList(xmlPreferences); - - // read ios team ID - var iosTeamId = getTeamIdPreference(xmlPreferences); - - // read Android prefix - var androidPrefix = getAndroidPrefixPreference(xmlPreferences); - - return { - 'hosts': hosts, - 'iosTeamId': iosTeamId, - 'androidPrefix': androidPrefix - }; - } - - // endregion - - // region Private API - - function getTeamIdPreference(xmlPreferences) { - if (xmlPreferences.hasOwnProperty('ios-team-id')) { - return xmlPreferences['ios-team-id'][0]['$']['value']; - } - - return null; - } - - function getAndroidPrefixPreference(xmlPreferences) { - if (xmlPreferences.hasOwnProperty('android-prefix')) { - return xmlPreferences['android-prefix'][0]['$']['value']; - } - - return null; - } - - /** - * Construct list of host objects, defined in xml file. - * - * @param {Object} xmlPreferences - plugin preferences from config.xml as JSON object - * @return {Array} array of JSON objects, where each entry defines host data from config.xml. - */ - function constructHostsList(xmlPreferences) { - var hostsList = []; - - // look for defined hosts - var xmlHostList = xmlPreferences['host']; - if (xmlHostList == null || xmlHostList.length == 0) { - return []; - } - - xmlHostList.forEach(function(xmlElement) { - var host = constructHostEntry(xmlElement); - if (host) { - hostsList.push(host); - } - }); - - return hostsList; - } - - /** - * Construct host object from xml data. - * - * @param {Object} xmlElement - xml data to process. - * @return {Object} host entry as JSON object - */ - function constructHostEntry(xmlElement) { - var host = { - scheme: DEFAULT_SCHEME, - name: '' - }, - hostProperties = xmlElement['$']; - - if (hostProperties == null || hostProperties.length == 0) { - return null; - } - - // read host name - host.name = hostProperties.name; - - // read scheme if defined - if (hostProperties['scheme'] != null) { - host.scheme = hostProperties.scheme; - } - - return host; - } - - // endregion - -})(); diff --git a/hooks.es6/lib/ios/projectEntitlements.js b/hooks.es6/lib/ios/projectEntitlements.js deleted file mode 100755 index df5e065b..00000000 --- a/hooks.es6/lib/ios/projectEntitlements.js +++ /dev/null @@ -1,176 +0,0 @@ -/* -Script creates entitlements file with the list of hosts, specified in config.xml. -File name is: ProjectName.entitlements -Location: ProjectName/ - -Script only generates content. File it self is included in the xcode project in another hook: xcodePreferences.js. -*/ -(function() { - - var path = require('path'), - fs = require('fs'), - plist = require('plist'), - mkpath = require('mkpath'), - ConfigXmlHelper = require('../configXmlHelper.js'), - ASSOCIATED_DOMAINS = 'com.apple.developer.associated-domains', - context, - projectRoot, - projectName, - entitlementsFilePath; - - module.exports = { - generateAssociatedDomainsEntitlements: generateEntitlements - }; - - // region Public API - - /** - * Generate entitlements file content. - * - * @param {Object} cordovaContext - cordova context object - * @param {Object} pluginPreferences - plugin preferences from config.xml; already parsed - */ - function generateEntitlements(cordovaContext, pluginPreferences) { - context = cordovaContext; - - var currentEntitlements = getEntitlementsFileContent(), - newEntitlements = injectPreferences(currentEntitlements, pluginPreferences); - - saveContentToEntitlementsFile(newEntitlements); - } - - // endregion - - // region Work with entitlements file - - /** - * Save data to entitlements file. - * - * @param {Object} content - data to save; JSON object that will be transformed into xml - */ - function saveContentToEntitlementsFile(content) { - var plistContent = plist.build(content), - filePath = pathToEntitlementsFile(); - - // ensure that file exists - mkpath.sync(path.dirname(filePath)); - - // save it's content - fs.writeFileSync(filePath, plistContent, 'utf8'); - } - - /** - * Read data from existing entitlements file. If none exist - default value is returned - * - * @return {String} entitlements file content - */ - function getEntitlementsFileContent() { - var pathToFile = pathToEntitlementsFile(), - content; - - try { - content = fs.readFileSync(pathToFile, 'utf8'); - } catch (err) { - return defaultEntitlementsFile(); - } - - return plist.parse(content); - } - - /** - * Get content for an empty entitlements file. - * - * @return {String} default entitlements file content - */ - function defaultEntitlementsFile() { - return {}; - } - - /** - * Inject list of hosts into entitlements file. - * - * @param {Object} currentEntitlements - entitlements where to inject preferences - * @param {Object} pluginPreferences - list of hosts from config.xml - * @return {Object} new entitlements content - */ - function injectPreferences(currentEntitlements, pluginPreferences) { - var newEntitlements = currentEntitlements, - content = generateAssociatedDomainsContent(pluginPreferences); - - newEntitlements[ASSOCIATED_DOMAINS] = content; - - return newEntitlements; - } - - /** - * Generate content for associated-domains dictionary in the entitlements file. - * - * @param {Object} pluginPreferences - list of hosts from conig.xml - * @return {Object} associated-domains dictionary content - */ - function generateAssociatedDomainsContent(pluginPreferences) { - var domainsList = [], - link; - - // generate list of host links - pluginPreferences.hosts.forEach(function(host) { - link = domainsListEntryForHost(host); - domainsList.push(link); - }); - - return domainsList; - } - - /** - * Generate domain record for the given host. - * - * @param {Object} host - host entry - * @return {String} record - */ - function domainsListEntryForHost(host) { - return 'applinks:' + host.name; - } - - // endregion - - // region Path helper methods - - /** - * Path to entitlements file. - * - * @return {String} absolute path to entitlements file - */ - function pathToEntitlementsFile() { - if (entitlementsFilePath === undefined) { - entitlementsFilePath = path.join(getProjectRoot(), 'platforms', 'ios', getProjectName(), 'Resources', getProjectName() + '.entitlements'); - } - - return entitlementsFilePath; - } - - /** - * Projects root folder path. - * - * @return {String} absolute path to the projects root - */ - function getProjectRoot() { - return context.opts.projectRoot; - } - - /** - * Name of the project from config.xml - * - * @return {String} project name - */ - function getProjectName() { - if (projectName === undefined) { - var configXmlHelper = new ConfigXmlHelper(context); - projectName = configXmlHelper.getProjectName(); - } - - return projectName; - } - - // endregion - -})(); diff --git a/hooks.es6/lib/ios/xcodePreferences.js b/hooks.es6/lib/ios/xcodePreferences.js deleted file mode 100755 index dc602935..00000000 --- a/hooks.es6/lib/ios/xcodePreferences.js +++ /dev/null @@ -1,220 +0,0 @@ -/* -Script activates support for Universal Links in the application by setting proper preferences in the xcode project file. -Which is: -- deployment target set to iOS 9.0 -- .entitlements file added to project PBXGroup and PBXFileReferences section -- path to .entitlements file added to Code Sign Entitlements preference -*/ - -(function() { - - var path = require('path'), - compare = require('node-version-compare'), - ConfigXmlHelper = require('../configXmlHelper.js'), - // pbxFile = require('xcode/lib/pbxFile'), - IOS_DEPLOYMENT_TARGET = '8.0', - COMMENT_KEY = /_comment$/, - context; - - module.exports = { - enableAssociativeDomainsCapability: enableAssociativeDomainsCapability - } - - // region Public API - - /** - * Activate associated domains capability for the application. - * - * @param {Object} cordovaContext - cordova context object - */ - function enableAssociativeDomainsCapability(cordovaContext) { - context = cordovaContext; - - var projectFile = loadProjectFile(); - - // adjust preferences - activateAssociativeDomains(projectFile.xcode); - - // add entitlements file to pbxfilereference - addPbxReference(projectFile.xcode); - - // save changes - projectFile.write(); - } - - // endregion - - // region Alter project file preferences - - /** - * Activate associated domains support in the xcode project file: - * - set deployment target to ios 9; - * - add .entitlements file to Code Sign Entitlements preference. - * - * @param {Object} xcodeProject - xcode project preferences; all changes are made in that instance - */ - function activateAssociativeDomains(xcodeProject) { - var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection()), - entitlementsFilePath = pathToEntitlementsFile(), - config, - buildSettings, - deploymentTargetIsUpdated; - - for (config in configurations) { - buildSettings = configurations[config].buildSettings; - buildSettings['CODE_SIGN_ENTITLEMENTS'] = '"' + entitlementsFilePath + '"'; - // if deployment target is less then the required one - increase it - if (buildSettings['IPHONEOS_DEPLOYMENT_TARGET']) { - var buildDeploymentTarget = buildSettings['IPHONEOS_DEPLOYMENT_TARGET'].toString(); - if (compare(buildDeploymentTarget, IOS_DEPLOYMENT_TARGET) == -1) { - buildSettings['IPHONEOS_DEPLOYMENT_TARGET'] = IOS_DEPLOYMENT_TARGET; - deploymentTargetIsUpdated = true; - } - } - else { - buildSettings['IPHONEOS_DEPLOYMENT_TARGET'] = IOS_DEPLOYMENT_TARGET; - deploymentTargetIsUpdated = true; - } - } - - if (deploymentTargetIsUpdated) { - console.log('IOS project now has deployment target set as: ' + IOS_DEPLOYMENT_TARGET); - } - - console.log('IOS project Code Sign Entitlements now set to: ' + entitlementsFilePath); - } - - // endregion - - // region PBXReference methods - - /** - * Add .entitlemets file into the project. - * - * @param {Object} xcodeProject - xcode project preferences; all changes are made in that instance - */ - function addPbxReference(xcodeProject) { - var fileReferenceSection = nonComments(xcodeProject.pbxFileReferenceSection()), - entitlementsRelativeFilePath = pathToEntitlementsFile(); - - if (isPbxReferenceAlreadySet(fileReferenceSection, entitlementsRelativeFilePath)) { - console.log('Entitlements file is in reference section.'); - return; - } - - console.log('Entitlements file is not in references section, adding it'); - createPbxFileReference(xcodeProject, entitlementsRelativeFilePath); - } - - /** - * Check if .entitlemets file reference already set. - * - * @param {Object} fileReferenceSection - PBXFileReference section - * @param {String} entitlementsRelativeFilePath - relative path to entitlements file - * @return true - if reference is set; otherwise - false - */ - function isPbxReferenceAlreadySet(fileReferenceSection, entitlementsRelativeFilePath) { - var isAlreadyInReferencesSection = false, - uuid, - fileRefEntry; - - for (uuid in fileReferenceSection) { - fileRefEntry = fileReferenceSection[uuid]; - if (fileRefEntry.path && fileRefEntry.path.indexOf(entitlementsRelativeFilePath) > -1) { - isAlreadyInReferencesSection = true; - break; - } - } - - return isAlreadyInReferencesSection; - } - - /** - * Create reference to the entitlements file in the xcode project. - * - * @param {Object} xcodeProject - xcode project preferences; all changes are made in that instance - * @param {String} entitlementsRelativeFilePath - relative path to entitlemets file - */ - function createPbxFileReference(xcodeProject, entitlementsRelativeFilePath) { - // commented for now - // var rootGroup = nonComments(xcodeProject.pbxGroupByName('CustomTemplate')), - // entitlementsPbxFile = new pbxFile(entitlementsRelativeFilePath); - // - // entitlementsPbxFile.fileRef = xcodeProject.generateUuid(), - // entitlementsPbxFile.uuid = xcodeProject.generateUuid(); - // - // xcodeProject.addToPbxFileReferenceSection(entitlementsPbxFile); - // - // rootGroup.children.push({ - // 'value': entitlementsPbxFile.fileRef, - // 'comment': path.basename(entitlementsRelativeFilePath) - // }); - xcodeProject.addResourceFile(path.basename(entitlementsRelativeFilePath)); - } - - // region Xcode project file helpers - - /** - * Load iOS project file from platform specific folder. - * - * @return {Object} projectFile - project file information - */ - function loadProjectFile() { - var platform_ios, - projectFile; - - try { - // try pre-5.0 cordova structure - platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms')['ios']; - projectFile = platform_ios.parseProjectFile(iosPlatformPath()); - } catch (e) { - // let's try cordova 5.0 structure - platform_ios = context.requireCordovaModule('cordova-lib/src/plugman/platforms/ios'); - projectFile = platform_ios.parseProjectFile(iosPlatformPath()); - } - - return projectFile; - } - - /** - * Remove comments from the file. - * - * @param {Object} obj - file object - * @return {Object} file object without comments - */ - function nonComments(obj) { - var keys = Object.keys(obj), - newObj = {}; - - for (var i = 0, len = keys.length; i < len; i++) { - if (!COMMENT_KEY.test(keys[i])) { - newObj[keys[i]] = obj[keys[i]]; - } - } - - return newObj; - } - - // endregion - - // region Path helpers - - function iosPlatformPath() { - return path.join(projectRoot(), 'platforms', 'ios'); - } - - function projectRoot() { - return context.opts.projectRoot; - } - - function pathToEntitlementsFile() { - var configXmlHelper = new ConfigXmlHelper(context), - projectName = configXmlHelper.getProjectName(), - fileName = projectName + '.entitlements'; - - return path.join(projectName, 'Resources', fileName); - } - - // endregion - -})(); diff --git a/hooks.es6/lib/xmlHelper.js b/hooks.es6/lib/xmlHelper.js deleted file mode 100755 index d425d73c..00000000 --- a/hooks.es6/lib/xmlHelper.js +++ /dev/null @@ -1,60 +0,0 @@ -/* -Small helper class to read/write from/to xml file. -*/ -(function() { - - var fs = require('fs'), - xml2js = require('xml2js'); - - module.exports = { - readXmlAsJson: readXmlAsJson, - writeJsonAsXml: writeJsonAsXml - }; - - /** - * Read data from the xml file as JSON object. - * - * @param {String} filePath - absolute path to xml file - * @return {Object} JSON object with the contents of the xml file - */ - function readXmlAsJson(filePath) { - var xmlData, - xmlParser, - parsedData; - - try { - xmlData = fs.readFileSync(filePath); - xmlParser = new xml2js.Parser(); - xmlParser.parseString(xmlData, function(err, data) { - if (data) { - parsedData = data; - } - }); - } catch (err) {} - - return parsedData; - } - - /** - * Write JSON object as xml into the specified file. - * - * @param {Object} jsData - JSON object to write - * @param {String} filePath - path to the xml file where data should be saved - * @return {boolean} true - if data saved to file; false - otherwise - */ - function writeJsonAsXml(jsData, filePath, options) { - var xmlBuilder = new xml2js.Builder(options), - changedXmlData = xmlBuilder.buildObject(jsData), - isSaved = true; - - try { - fs.writeFileSync(filePath, changedXmlData); - } catch (err) { - console.log(err); - isSaved = false; - } - - return isSaved; - } - -})(); diff --git a/package.json b/package.json index 0e202475..19c82bdc 100644 --- a/package.json +++ b/package.json @@ -47,9 +47,7 @@ "xml2js": "^0.4.16" }, "devDependencies": { - "babel-eslint": "^6.1.2", "gulp": "^3.9.1", - "gulp-babel": "^6.1.2", "gulp-sourcemaps": "^1.6.0", "gulp-standard": "^8.0.3", "husky": "^0.12.0", diff --git a/testbed/www/js.es6/index.js b/testbed/www/js.es6/index.js deleted file mode 100644 index ea801228..00000000 --- a/testbed/www/js.es6/index.js +++ /dev/null @@ -1,312 +0,0 @@ -// app -var app = { - initialize: function() { - this.bindEvents(); - }, - bindEvents: function() { - document.addEventListener('deviceready', this.onDeviceReady, false); - document.addEventListener('resume', this.onDeviceReady, false); - }, - onDeviceReady: function() { - BranchInit(true); - }, - onDeviceResume: function() { - BranchInit(true); - } -}; -app.initialize(); - -// branch -function BranchInit(isDebug) { - console.log('Trigger BranchInit()'); - - // for development and debugging only - Branch.setDebug(isDebug); - - // sync with Mixpanel if installed - Branch.setMixpanelToken('your_mixpanel_token'); - - // Branch initialization - Branch.initSession(function(data) { - // read deep link data on click - console.log('Trigger DeepLinkHandler()'); - alert('Deep Link Data: ' + JSON.stringify(data)); - }).then(function(res) { - console.log(res); - }).catch(function(err) { - console.error(err); - }); - - // optional - Branch.onNonBranchLink(function NonBranchLinkHandler(data) { - console.log('Trigger NonBranchLinkData()'); - - if (data) { - alert(JSON.stringify(data)); - } - }); -} - -function BranchEvent() { - console.log('Trigger BranchEvent()'); - - // event name - var event = document.getElementById('custom-action').value; - - // optional - var metadata = { "custom_dictionary": 123 }; - Branch.userCompletedAction(event, metadata).then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} - -function BranchFirstData() { - console.log('Trigger BranchFirstData()'); - - Branch.getFirstReferringParams().then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} - -function BranchLatestData() { - console.log('Trigger BranchLatestData()'); - - Branch.getLatestReferringParams().then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} - -function BranchUser() { - console.log('Trigger BranchUser()'); - - var userId = document.getElementById('identity').value; - Branch.setIdentity(userId).then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} - -function BranchLogout() { - console.log('Trigger BranchLogout()'); - - Branch.logout().then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} - -var branchUniversalObj = null; -function BranchUniversalObject() { - console.log('Trigger BranchUniversalObject()'); - - // only canonicalIdentifier is required - var properties = { - canonicalIdentifier: "123", - canonicalUrl: "http://example.com/123", - title: "Content 123", - contentDescription: "Content 123 " + Date.now(), - contentImageUrl: "http://lorempixel.com/400/400/", - price: 12.12, - currency: "GBD", - contentIndexingMode: "private", - contentMetadata: { - "custom": "data", - "testing": 123, - "this_is": true - } - }; - - // create a branchUniversalObj variable to reference with other Branch methods - Branch.createBranchUniversalObject(properties).then(function(res) { - console.log(res); - branchUniversalObj = res; - alert("Response: " + JSON.stringify(res)); - }).catch(function(err) { - console.log(err); - alert("Error: " + JSON.stringify(err)); - }); -} - -function BranchView() { - console.log('Trigger BranchView()'); - - if (branchUniversalObj === null) { - return alert('need to Generate Branch Universal Object'); - } - branchUniversalObj.registerView().then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} - -function BranchDeepLink() { - console.log('Trigger BranchDeepLink()'); - - // optional fields - var analytics = { - channel: "channel", - feature: "feature", - campaign: "campaign", - stage: "stage", - tags: [ "one", "two", "three" ], - alias: document.getElementById('alias').value - }; - - // optional fields - var properties = { - $fallback_url: "http://www.example.com/example", - $desktop_url: "http://www.example.com/desktop", - $android_url: "http://www.example.com/android", - $ios_url: "http://www.example.com/ios", - $ipad_url: "http://www.example.com/ipad", - $deeplink_path: "content/123", - $match_duration: 2000, - more_custom: "data", - even_more_custom: true, - this_is_custom: 41231, - this_is_date: Date.now() - }; - - // needs a universal object - if (branchUniversalObj === null) { - return alert('need to Generate Branch Universal Object'); - } - - branchUniversalObj.generateShortUrl(analytics, properties).then(function(res) { - console.log(res); - document.getElementById('generated-url').placeholder = ''; - document.getElementById('generated-url').value = res.url; - alert(JSON.stringify(res.url)); - }).catch(function(err) { - console.error(err); - alert(JSON.stringify(err)); - }); -} - -function BranchShareSheet() { - console.log('Trigger BranchShareSheet()'); - - // optional fields - var analytics = { - channel: "channel", - feature: "feature", - campaign: "campaign", - stage: "stage", - tags: [ "one", "two", "three" ] - }; - - // optional fields - var properties = { - $fallback_url: "http://www.example.com/example", - $desktop_url: "http://www.example.com/desktop", - $android_url: "http://www.example.com/android", - $ios_url: "http://www.example.com/ios", - $ipad_url: "http://www.example.com/ipad", - more_custom: "data", - even_more_custom: true, - this_is_custom: 41231 - }; - - var message = "Check out this link"; - - // needs a universal object - if (branchUniversalObj === null) { - return alert('need to Generate Branch Universal Object'); - } - - // optional listeners (must be called before showShareSheet) - branchUniversalObj.onShareSheetLaunched(function(res) { - // android only - console.log(res); - alert(JSON.stringify(res)); - }); - branchUniversalObj.onShareSheetDismissed(function(res) { - console.log(res); - alert(JSON.stringify(res)); - }); - branchUniversalObj.onLinkShareResponse(function(res) { - console.log(res); - alert(JSON.stringify(res)); - }); - branchUniversalObj.onChannelSelected(function(res) { - // android only - console.log(res); - alert(JSON.stringify(res)); - }); - - // share sheet - branchUniversalObj.showShareSheet(analytics, properties, message); -} - -function BranchSpotlight() { - console.log('Trigger ListOnSpotlight()'); - - if (branchUniversalObj === null) { - return alert('need to Generate Branch Universal Object'); - } - branchUniversalObj.listOnSpotlight().then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} - -function BranchReferralsLoad() { - console.log('Trigger BranchReferralsLoad()'); - - Branch.loadRewards().then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} - -function BranchReferralsRedeem() { - console.log('Trigger BranchReferralsRedeem()'); - - var reward = 1000; - Branch.redeemRewards(reward).then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} - -function BranchReferralsHistory() { - console.log('Trigger BranchReferralsHistory()'); - - Branch.creditHistory().then(function(res) { - console.log(res); - alert('Response: ' + JSON.stringify(res)); - }).catch(function(err) { - console.error(err); - alert('Error: ' + JSON.stringify(err)); - }); -} diff --git a/tests.es6/plugin.xml b/tests.es6/plugin.xml deleted file mode 100644 index 9d61826c..00000000 --- a/tests.es6/plugin.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - branch-cordova-sdk-tests - Apache 2.0 - - - - diff --git a/tests.es6/tests.js b/tests.es6/tests.js deleted file mode 100644 index fa8a2084..00000000 --- a/tests.es6/tests.js +++ /dev/null @@ -1,206 +0,0 @@ -/** - * Branch.IO Cordova Plugin Unit-Test - * ---------------------------------- - */ -/* jshint jasmine: true */ - -exports.defineAutoTests = function() { - - describe('Branch.IO SDK (Branch)', function() { - it('should exist', function() { - expect(window.Branch).toBeDefined(); - }); - it('should contain a method called getLatestReferringParams()', function() { - expect(window.Branch.getLatestReferringParams).toBeDefined(); - expect(typeof(window.Branch.getLatestReferringParams)).toBe('function'); - }); - it('should contain a method called getFirstReferringParams()', function() { - expect(window.Branch.getFirstReferringParams).toBeDefined(); - expect(typeof(window.Branch.getFirstReferringParams)).toBe('function'); - }); - it('should contain a method called setIdentity()', function() { - expect(window.Branch.setIdentity).toBeDefined(); - expect(typeof(window.Branch.setIdentity)).toBe('function'); - }); - it('should contain a method called logout()', function() { - expect(window.Branch.logout).toBeDefined(); - expect(typeof(window.Branch.logout)).toBe('function'); - }); - it('should contain a method called createBranchUniversalObject()', function() { - expect(window.Branch.createBranchUniversalObject).toBeDefined(); - expect(typeof(window.Branch.createBranchUniversalObject)).toBe('function'); - }); - it('should contain a method called userCompletedAction()', function() { - expect(window.Branch.userCompletedAction).toBeDefined(); - expect(typeof(window.Branch.userCompletedAction)).toBe('function'); - }); - it('should contain a method called loadRewards()', function() { - expect(window.Branch.loadRewards).toBeDefined(); - expect(typeof(window.Branch.loadRewards)).toBe('function'); - }); - it('should contain a method called redeemRewards()', function() { - expect(window.Branch.redeemRewards).toBeDefined(); - expect(typeof(window.Branch.redeemRewards)).toBe('function'); - }); - it('should contain a method called creditHistory()', function() { - expect(window.Branch.creditHistory).toBeDefined(); - expect(typeof(window.Branch.creditHistory)).toBe('function'); - }); - }); - - describe('Branch.getLatestReferringParams()', function() { - beforeEach(function(done) { - window.Branch.initSession().then(function() { - done(); - }); - }, 3000); - it('should return an object response', function(done) { - window.Branch.getLatestReferringParams().then(function(res) { - expect(typeof(res)).toBe('object'); - done(); - }); - }, 10000); - }); - - describe('Branch.getFirstReferringParams()', function() { - beforeEach(function(done) { - window.Branch.initSession().then(function() { - done(); - }); - }, 3000); - it('should return an object response', function(done) { - window.Branch.getFirstReferringParams().then(function(res) { - // We expect false since we won't open this from a branch link - expect(res).toBe(false); - done(); - }); - }, 10000); - }); - - - describe('Branch.setIdentity()', function() { - beforeEach(function(done) { - window.Branch.initSession().then(function() { - done(); - }); - }, 3000); - it('should return "Success" response', function(done) { - window.Branch.setIdentity('new_identity').then(function(res) { - expect(typeof(res)).toBe('object'); - done(); - }); - }, 10000); - }); - - describe('Branch.createBranchUniversalObject()', function() { - var branchUniversalObj; - - beforeEach(function(done) { - window.Branch.initSession().then(function() { - var properties = { - canonicalIdentifier: 'testbed', - title: 'testbed', - contentDescription: 'Testbed Application', - contentImageUrl: 'https://imgflip.com/s/meme/Derp.jpg', - contentIndexingMode: 'public', - contentMetadata: {} - }; - window.Branch.createBranchUniversalObject(properties).then(function(res) { - branchUniversalObj = res; - done(); - }); - }); - }, 3000); - it('should execute register view', function(done) { - branchUniversalObj.registerView().then(function(res) { - expect(typeof(res)).toBe('object'); - done(); - }); - }, 5000); - it('should execute generate short url', function(done) { - var properties = { - feature: 'test', - alias: 'testbed', - channel: 'test', - stage: 'test', - duration: 10000 - }; - var controlParams = { - $fallback_url: 'www.another.com', - $desktop_url: 'www.desktop.com', - $android_url: 'test', - $ios_url: 'ios', - $ipad_url: 'ipad', - $fire_url: 'fire', - $blackberry_url: 'blackberry', - $windows_phone_url: 'win-phone' - }; - branchUniversalObj.generateShortUrl(properties, controlParams).then(function(res) { - expect(typeof(res)).toBe('object'); - done(); - }); - }, 5000); - }); - - describe('Branch.userCompletedAction()', function() { - beforeEach(function(done) { - window.Branch.initSession().then(function() { - done(); - }); - }, 3000); - it('should successfully execute the method', function(done) { - window.Branch.userCompletedAction('login'); - expect('Success').toBe('Success'); - done(); - }, 10000); - }); - - describe('Branch.loadRewards()', function() { - beforeEach(function(done) { - window.Branch.initSession().then(function() { - done(); - }); - }, 3000); - it('should return an object response', function(done) { - window.Branch.loadRewards().then(function(res) { - expect(typeof(res)).toBe('number'); - done(); - }, function(err) { - expect(typeof(err)).toBe('string'); - done(); - }); - }, 10000); - }); - - describe('Branch.redeemRewards()', function() { - beforeEach(function(done) { - window.Branch.initSession().then(function() { - done(); - }); - }, 3000); - it('should return an object/string error response', function(done) { - window.Branch.redeemRewards(100).then(function(res) { - expect(typeof(res)).toBe('object'); - done(); - }, function(err) { - expect(typeof(err)).toBe('string'); - done(); - }); - }, 10000); - }); - - describe('Branch.creditHistory()', function() { - beforeEach(function(done) { - window.Branch.initSession().then(function() { - done(); - }); - }, 3000); - it('should return the credit balance', function(done) { - window.Branch.creditHistory().then(function(res) { - expect(typeof(res)).toBe('object'); - done(); - }); - }, 10000); - }); - -}; diff --git a/www.es6/branch.js b/www.es6/branch.js deleted file mode 100644 index 1b550654..00000000 --- a/www.es6/branch.js +++ /dev/null @@ -1,480 +0,0 @@ -/** - * Branch.IO SDK - * ------------- - * Method usage: - * All methods are promisified, therefore you can call .then(successCallback, errorCallback) for any of the method - * called for executing success or error callbacks. - */ - -var exec = require('cordova/exec'); -var deviceVendor = window.clientInformation.vendor; -var _API_CLASS = 'BranchSDK'; // SDK Class - -/** - * Execute SDK method using cordova.exec() - * - * @param (String) method - The class method to execute. - * @param (Array) params - Method parameter(s) to pass. - * - * @return (Promise) - */ -function execute(method, params) { - - params = (!params) ? [] : params; - - return new Promise(function(resolve, reject) { - exec(function(res) { - resolve(res); - }, function(err) { - reject(err); - }, _API_CLASS, method, params); - }); - -} - -/** - * Set listener callback for SDK method. - * - * @param (String) method - The class method to execute. - * @param (Function) callback - The method listener callback. - * @param (Array) params - The method listener parameters. - * - * @return (Promise) - */ -function executeCallback(method, callback, params) { - - params = (!params) ? [] : params; - - exec(callback, function(err) { - console.error(err); - }, _API_CLASS, method, params); - -} - -/** - * @class Branch - */ -var Branch = function() { - - this.debugMode = false; - -}; - -var disableGlobalListenersWarnings = false; - -/** - * Don't emit warnings regarding use of global listeners. - */ -Branch.prototype.disableGlobalListenersWarnings = function() { - disableGlobalListenersWarnings = true; -}; - -var branchLinkListener = null; -function onBranchLinkStub(data) { - branchLinkListener(data); -} - -/** - * Initialize the Branch instance. - * @param (Function) onBranchLinkHook. listener to trigger on deep links. - * @return (Promise) - */ -Branch.prototype.initSession = function(onBranchLinkHook) { - if (!onBranchLinkHook && !disableGlobalListenersWarnings) { - console.log('WARNING: branch link hook is not being passed to initSession. ' + - 'Falling back to global DeepLinkHandler method. See https://goo.gl/GijGKP for details.'); - } - else { - var currentHook = window.DeepLinkHandler; - if (currentHook !== undefined && currentHook !== onBranchLinkStub) { - if (!disableGlobalListenersWarnings) { - console.log('WARNING: you are calling initSession with a branch link hook when an ' + - 'existing global DeepLinkHandler is defined. The global ' + - 'DeepLinkHandler will be overwritten. See https://goo.gl/GijGKP ' + - 'for details.'); - } - } - if (onBranchLinkHook) { - branchLinkListener = onBranchLinkHook; - window.DeepLinkHandler = onBranchLinkStub; - } - } - - return execute('initSession'); -}; - - -var nonBranchLinkListener = null; -function onNonBranchLinkStub(data) { - nonBranchLinkListener(data); -} - -/** - * Register listener for non branch links. - */ -Branch.prototype.onNonBranchLink = function(newHook) { - if (!newHook) { - throw new Error('non branch link hook is falsy, expected a function, not: "' + newHook + '"'); - } - - var currentHook = window.NonBranchLinkHandler; - if (currentHook !== undefined && currentHook !== onNonBranchLinkStub && currentHook !== defaultNonBranchLinkHandler) { - if (!disableGlobalListenersWarnings) { - console.log('WARNING: you are calling onNonBranchLink when an ' + - 'existing global NonBranchLinkHandler is defined. The global ' + - 'NonBranchLinkHandler will be overwritten. See https://goo.gl/GijGKP ' + - 'for details.'); - } - } - nonBranchLinkListener = newHook; - window.NonBranchLinkHandler = onNonBranchLinkStub; -} - -/** - * Get Mixpanel tolen/assisstance. - * NOTE: This must be called before initSession - * - * @param (String) token. Default = false - * - * @return (Promise) - */ -Branch.prototype.setMixpanelToken = function(token) { - - return execute('setMixpanelToken', [ token ]); - -}; - -/** - * Set debug mode to simulate fresh installs. - * NOTE: This must be called before initSession - * - * @param (Boolean) isEnabled. Default = false - * - * @return (Promise) - */ -Branch.prototype.setDebug = function(isEnabled) { - - isEnabled = typeof isEnabled !== 'boolean' ? false : isEnabled; - - this.debugMode = isEnabled; - - return execute('setDebug', [ isEnabled ]); -}; - -/** - * Retrieves the install session parameters. - * - * @return (Promise) - */ -Branch.prototype.getFirstReferringParams = function() { - - return execute('getFirstReferringParams'); - -}; - -/** - * Retrieves the latest referring parameters. - * - * @return (Promise) - */ -Branch.prototype.getLatestReferringParams = function() { - - return execute('getLatestReferringParams'); - -}; - -/** - * Sets the identity of a user and returns the data. - * - * @param (String) identity - A unique identifier for the user [REQUIRED] - * - * @return (Promise) - * - */ -Branch.prototype.setIdentity = function(identity) { - - if (identity) { - return execute('setIdentity', [ identity ]); - } - else { - return new Promise(function(resolve, reject) { - reject('Please set an identity'); - }); - } - -}; - -/** - * Logout from the current session. Replace session and identity IDs. - * - * @return (Promise) - */ -Branch.prototype.logout = function() { - - return execute('logout'); - -}; - -/** - * Register custom events. - * - * @param (String) action - Name of the custom action - * @param (Object) metaData - Data to pass with the action [OPTIONAL] - * - * @return (Promise) - */ -Branch.prototype.userCompletedAction = function(action, metaData) { - - var args = [ action ]; - - if (metaData) { - args.push(metaData); - } - - return execute('userCompletedAction', args); - -}; - -/** - * Create an universal Branch object - * - * @params (Object) options - * - * @return (Promise) - * - * options: - * -------------------------------------------------------------- - * | KEY | TYPE | DESCRIPTION | - * -------------------------------------------------------------- - * | canonicalIdentifier | String | The object identifier | - * | title | String | The object title | - * | contentDescription | String | Object description | - * | contentImageUrl | String | The image URL | - * | contentIndexingMode | String | Indexing Mode | - * | | |('private' or 'public')| - * | contentMetadata | Object | Custom key/value | - * -------------------------------------------------------------- - */ -Branch.prototype.createBranchUniversalObject = function(options) { - - return new Promise(function(resolve, reject) { - execute('createBranchUniversalObject', [ options ]).then(function(res) { - - var obj = { - message: res.message, - instanceId: res.branchUniversalObjectId - }; - - // Attach object functions - /** - * Register view count. - * - * @return (Promise) - */ - obj.registerView = function() { - - return execute('registerView', [ obj.instanceId ]); - - }; - - /** - * Generates a short url. - * - * @param (Object) options - * @param (Object) controlParameters - * - * @return (Promise) - * - * options: - * -------------------------------------------------- - * | KEY | TYPE | DESCRIPTION | - * -------------------------------------------------- - * | feature | String | The link feature | - * | alias | String | The link alias | - * | channel | String | The link channel | - * | campaign | String | The link campaign | - * | stage | String | The link stage | - * | duration | Int | The link duration | - * -------------------------------------------------- - * - * controlParameters: - * ------------------------------------------------------- - * | KEY | TYPE | DESCRIPTION | - * ------------------------------------------------------- - * | $fallback_url | String | Fallback URL | - * | $desktop_url | String | Desktop URL | - * | $android_url | String | Android URL | - * | $ios_url | String | iOS URL | - * | $ipad_url | String | iPad URL | - * | $fire_url | String | Kindle Fire URL | - * | $blackberry_url | String | Blackberry URL | - * | $windows_phone_url | String | Kindle Fire URL | - * ------------------------------------------------------- - */ - obj.generateShortUrl = function(options, controlParameters) { - - return execute('generateShortUrl', [ obj.instanceId, options, controlParameters ]); - - }; - - /** - * Show the share dialog. - * - * @param (Object) options - * @param (Object) controlParameters - * @param (String) shareText [OPTIONAL] - * - * @return (Promise) - * - * options: - * -------------------------------------------------- - * | KEY | TYPE | DESCRIPTION | - * -------------------------------------------------- - * | feature | String | The link feature | - * | alias | String | The link alias | - * | channel | String | The link channel | - * | campaign | String | The link campaign | - * | stage | String | The link stage | - * | duration | Int | The link duration | - * -------------------------------------------------- - * - * controlParameters: - * ------------------------------------------------------- - * | KEY | TYPE | DESCRIPTION | - * ------------------------------------------------------- - * | $fallback_url | String | Fallback URL | - * | $desktop_url | String | Desktop URL | - * | $android_url | String | Android URL | - * | $ios_url | String | iOS URL | - * | $ipad_url | String | iPad URL | - * | $fire_url | String | Kindle Fire URL | - * | $blackberry_url | String | Blackberry URL | - * | $windows_phone_url | String | Kindle Fire URL | - * ------------------------------------------------------- - */ - obj.showShareSheet = function(options, controlParameters, shareText) { - - if (!shareText) { - shareText = 'This stuff is awesome: '; - } - - return execute('showShareSheet', [ obj.instanceId, options, controlParameters, shareText ]); - - }; - - /** - * Set on share sheet launched listener callback. - * - * @param (Function) callback - */ - obj.onShareSheetLaunched = function(callback) { - - if (deviceVendor.indexOf('Apple') < 0) { - executeCallback('onShareLinkDialogLaunched', callback, [ obj.instanceId ]); - } - - }; - - obj.onShareSheetDismissed = function(callback) { - - executeCallback('onShareLinkDialogDismissed', callback, [ obj.instanceId ]); - - } - - /** - * Set on link share listener callback. - * - * @param (Function) callback - */ - obj.onLinkShareResponse = function(callback) { - - executeCallback('onLinkShareResponse', callback, [ obj.instanceId ]); - - }; - - /** - * Set on channel select listener callback. - * - * @param (Function) callback - */ - obj.onChannelSelected = function(callback) { - - if (deviceVendor.indexOf('Apple') < 0) { - executeCallback('onChannelSelected', callback, [ obj.instanceId ]); - } - - }; - - /** - * List item on Spotlight (iOS Only). - */ - obj.listOnSpotlight = function() { - - return execute('listOnSpotlight', [ obj.instanceId ]); - - }; - - resolve(obj); - - }, function(err) { - reject(err); - }); - }); - -}; - -/** - * Retrieve the current reward balance. - * - * @return (Promise) - */ -Branch.prototype.loadRewards = function(bucket) { - - if (!bucket) { - bucket = ''; - } - - return execute('loadRewards', [ bucket ]); - -}; - -/** - * Redeem rewards to your account. - * - * @param (Int) value - The amount to redeem. - * @param (String) bucket - The value containing the name of the referral bucket to attempt to redeem credits from. [OPTIONAL] - * - * @return (Promise) - */ -Branch.prototype.redeemRewards = function(value, bucket) { - - var params = [ value ]; - - if (bucket) { - params.push(bucket); - } - - return execute('redeemRewards', params); - -}; - -/** - * Retrieve the entire history of credits and redemptions from the individual user. - * - * @return (Promise) - */ -Branch.prototype.creditHistory = function() { - - return execute('getCreditHistory'); - -}; - -/** - * NonBranchLinkHandler callback placeholder. - * - * @param {String} response - */ -var defaultNonBranchLinkHandler = function(response) {}; -window.NonBranchLinkHandler = (typeof NonBranchLinkHandler === 'undefined') ? defaultNonBranchLinkHandler : NonBranchLinkHandler; - -module.exports = new Branch();