Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Convert entry points to es module and create minified bundles #445

Merged
merged 16 commits into from
Apr 9, 2020
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ jobs:
before_script:
- mkdir $HOME/travisci-tools && pushd $HOME/travisci-tools && git init && git pull https://[email protected]/optimizely/travisci-tools.git && popd
script:
- CLIENT=node $HOME/travisci-tools/trigger-script-with-status-update.sh
- CLIENT=browser $HOME/travisci-tools/trigger-script-with-status-update.sh
- CLIENT=node TESTAPP_BRANCH=fayyaz/added-support-for-es6 $HOME/travisci-tools/trigger-script-with-status-update.sh
- CLIENT=browser TESTAPP_BRANCH=fayyaz/added-support-for-es6 $HOME/travisci-tools/trigger-script-with-status-update.sh
after_success: travis_terminate 0
- <<: *integrationtest
stage: 'Benchmarking tests'
Expand Down
3 changes: 2 additions & 1 deletion packages/optimizely-sdk/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ module.exports = {
Promise: 'readonly',
},
parserOptions: {
ecmaVersion: 5,
ecmaVersion: 6,
sourceType: 'module',
},
rules: {
'no-prototype-builtins': 'off',
Expand Down
2 changes: 1 addition & 1 deletion packages/optimizely-sdk/karma.base.conf.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2018, Optimizely
* Copyright 2018, 2020 Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down
264 changes: 142 additions & 122 deletions packages/optimizely-sdk/lib/index.browser.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2016-2017, 2019, Optimizely
* Copyright 2016-2017, 2019-2020 Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -13,146 +13,166 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var logging = require('@optimizely/js-sdk-logging');
var fns = require('./utils/fns');
var configValidator = require('./utils/config_validator');
var defaultErrorHandler = require('./plugins/error_handler');
var defaultEventDispatcher = require('./plugins/event_dispatcher/index.browser');
var enums = require('./utils/enums');
var eventProcessor = require('@optimizely/js-sdk-event-processor');
var loggerPlugin = require('./plugins/logger');
var Optimizely = require('./optimizely');
var eventProcessorConfigValidator = require('./utils/event_processor_config_validator');

var logger = logging.getLogger();
logging.setLogHandler(loggerPlugin.createLogger());
logging.setLogLevel(logging.LogLevel.INFO);
import {
getLogger,
setLogHandler,
setLogLevel,
setErrorHandler,
getErrorHandler,
LogLevel,
} from '@optimizely/js-sdk-logging';
import { LocalStoragePendingEventsDispatcher } from '@optimizely/js-sdk-event-processor';

import fns from './utils/fns';
import configValidator from './utils/config_validator';
import defaultErrorHandler from './plugins/error_handler';
import defaultEventDispatcher from './plugins/event_dispatcher/index.browser';
import enums from './utils/enums';
import loggerPlugin from './plugins/logger';
import Optimizely from './optimizely';
import eventProcessorConfigValidator from './utils/event_processor_config_validator';

var logger = getLogger();
setLogHandler(loggerPlugin.createLogger());
setLogLevel(LogLevel.INFO);

var MODULE_NAME = 'INDEX_BROWSER';

var DEFAULT_EVENT_BATCH_SIZE = 10;
var DEFAULT_EVENT_FLUSH_INTERVAL = 1000; // Unit is ms, default is 1s

var hasRetriedEvents = false;

/**
* Entry point into the Optimizely Browser SDK
* Creates an instance of the Optimizely class
* @param {Object} config
* @param {Object} config.datafile
* @param {Object} config.errorHandler
* @param {Object} config.eventDispatcher
* @param {Object} config.logger
* @param {Object} config.logLevel
* @param {Object} config.userProfileService
* @param {Object} config.eventBatchSize
* @param {Object} config.eventFlushInterval
* @return {Object} the Optimizely object
*/
module.exports = {
logging: loggerPlugin,
errorHandler: defaultErrorHandler,
eventDispatcher: defaultEventDispatcher,
enums: enums,

setLogger: logging.setLogHandler,
setLogLevel: logging.setLogLevel,

/**
* Creates an instance of the Optimizely class
* @param {Object} config
* @param {Object} config.datafile
* @param {Object} config.errorHandler
* @param {Object} config.eventDispatcher
* @param {Object} config.logger
* @param {Object} config.logLevel
* @param {Object} config.userProfileService
* @param {Object} config.eventBatchSize
* @param {Object} config.eventFlushInterval
* @return {Object} the Optimizely object
*/
createInstance: function(config) {
try {
config = config || {};
var createInstance = function(config) {
try {
config = config || {};

// TODO warn about setting per instance errorHandler / logger / logLevel
if (config.errorHandler) {
logging.setErrorHandler(config.errorHandler);
}
if (config.logger) {
logging.setLogHandler(config.logger);
// respect the logger's shouldLog functionality
logging.setLogLevel(logging.LogLevel.NOTSET);
}
if (config.logLevel !== undefined) {
logging.setLogLevel(config.logLevel);
}
// TODO warn about setting per instance errorHandler / logger / logLevel
if (config.errorHandler) {
setErrorHandler(config.errorHandler);
}
if (config.logger) {
setLogHandler(config.logger);
// respect the logger's shouldLog functionality
setLogLevel(LogLevel.NOTSET);
}
if (config.logLevel !== undefined) {
setLogLevel(config.logLevel);
}

try {
configValidator.validate(config);
config.isValidInstance = true;
} catch (ex) {
logger.error(ex);
config.isValidInstance = false;
try {
configValidator.validate(config);
config.isValidInstance = true;
} catch (ex) {
logger.error(ex);
config.isValidInstance = false;
}

var eventDispatcher;
// prettier-ignore
if (config.eventDispatcher == null) { // eslint-disable-line eqeqeq
// only wrap the event dispatcher with pending events retry if the user didnt override
eventDispatcher = new LocalStoragePendingEventsDispatcher({
eventDispatcher: defaultEventDispatcher,
});

if (!hasRetriedEvents) {
eventDispatcher.sendPendingEvents();
hasRetriedEvents = true;
}
} else {
eventDispatcher = config.eventDispatcher;
}

var eventDispatcher;
// prettier-ignore
if (config.eventDispatcher == null) { // eslint-disable-line eqeqeq
// only wrap the event dispatcher with pending events retry if the user didnt override
eventDispatcher = new eventProcessor.LocalStoragePendingEventsDispatcher({
eventDispatcher: defaultEventDispatcher,
});

if (!hasRetriedEvents) {
eventDispatcher.sendPendingEvents();
hasRetriedEvents = true;
}
} else {
eventDispatcher = config.eventDispatcher;
config = fns.assign(
{
clientEngine: enums.JAVASCRIPT_CLIENT_ENGINE,
eventBatchSize: DEFAULT_EVENT_BATCH_SIZE,
eventFlushInterval: DEFAULT_EVENT_FLUSH_INTERVAL,
},
config,
{
eventDispatcher: eventDispatcher,
// always get the OptimizelyLogger facade from logging
logger: logger,
errorHandler: getErrorHandler(),
}
);

config = fns.assign(
{
clientEngine: enums.JAVASCRIPT_CLIENT_ENGINE,
eventBatchSize: DEFAULT_EVENT_BATCH_SIZE,
eventFlushInterval: DEFAULT_EVENT_FLUSH_INTERVAL,
},
config,
{
eventDispatcher: eventDispatcher,
// always get the OptimizelyLogger facade from logging
logger: logger,
errorHandler: logging.getErrorHandler(),
}
if (!eventProcessorConfigValidator.validateEventBatchSize(config.eventBatchSize)) {
logger.warn('Invalid eventBatchSize %s, defaulting to %s', config.eventBatchSize, DEFAULT_EVENT_BATCH_SIZE);
config.eventBatchSize = DEFAULT_EVENT_BATCH_SIZE;
}
if (!eventProcessorConfigValidator.validateEventFlushInterval(config.eventFlushInterval)) {
logger.warn(
'Invalid eventFlushInterval %s, defaulting to %s',
config.eventFlushInterval,
DEFAULT_EVENT_FLUSH_INTERVAL
);
config.eventFlushInterval = DEFAULT_EVENT_FLUSH_INTERVAL;
}

if (!eventProcessorConfigValidator.validateEventBatchSize(config.eventBatchSize)) {
logger.warn('Invalid eventBatchSize %s, defaulting to %s', config.eventBatchSize, DEFAULT_EVENT_BATCH_SIZE);
config.eventBatchSize = DEFAULT_EVENT_BATCH_SIZE;
}
if (!eventProcessorConfigValidator.validateEventFlushInterval(config.eventFlushInterval)) {
logger.warn(
'Invalid eventFlushInterval %s, defaulting to %s',
config.eventFlushInterval,
DEFAULT_EVENT_FLUSH_INTERVAL
);
config.eventFlushInterval = DEFAULT_EVENT_FLUSH_INTERVAL;
}
var optimizely = new Optimizely(config);

var optimizely = new Optimizely(config);

try {
if (typeof window.addEventListener === 'function') {
var unloadEvent = 'onpagehide' in window ? 'pagehide' : 'unload';
window.addEventListener(
unloadEvent,
function() {
optimizely.close();
},
false
);
}
} catch (e) {
logger.error(enums.LOG_MESSAGES.UNABLE_TO_ATTACH_UNLOAD, MODULE_NAME, e.message);
try {
if (typeof window.addEventListener === 'function') {
var unloadEvent = 'onpagehide' in window ? 'pagehide' : 'unload';
window.addEventListener(
unloadEvent,
function() {
optimizely.close();
},
false
);
}

return optimizely;
} catch (e) {
logger.error(e);
return null;
logger.error(enums.LOG_MESSAGES.UNABLE_TO_ATTACH_UNLOAD, MODULE_NAME, e.message);
}
},

__internalResetRetryState: function() {
hasRetriedEvents = false;
},
return optimizely;
} catch (e) {
logger.error(e);
return null;
}
};

var __internalResetRetryState = function() {
hasRetriedEvents = false;
};

/**
* Entry point into the Optimizely Browser SDK
*/
export {
loggerPlugin as logging,
defaultErrorHandler as errorHandler,
defaultEventDispatcher as eventDispatcher,
enums,
setLogHandler as setLogger,
setLogLevel,
createInstance,
__internalResetRetryState,
}

export default {
logging: loggerPlugin,
errorHandler: defaultErrorHandler,
eventDispatcher: defaultEventDispatcher,
enums,
Copy link
Contributor

@mjc1283 mjc1283 Apr 9, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, I missed this. @zashraf1985 don't use the property shorthand here. This is not ES5-compatible. Needs to be enums: enums.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is Done

setLogger: setLogHandler,
setLogLevel,
createInstance,
__internalResetRetryState,
};
27 changes: 12 additions & 15 deletions packages/optimizely-sdk/lib/index.browser.tests.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2016-2019, Optimizely
* Copyright 2016-2020 Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -13,19 +13,17 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var logging = require('@optimizely/js-sdk-logging');
var configValidator = require('./utils/config_validator');
var eventProcessor = require('@optimizely/js-sdk-event-processor');
var Optimizely = require('./optimizely');
var optimizelyFactory = require('./index.browser');
var packageJSON = require('../package.json');
var testData = require('./tests/test_data');
var eventProcessor = require('@optimizely/js-sdk-event-processor');
var eventProcessorConfigValidator = require('./utils/event_processor_config_validator');

var chai = require('chai');
var assert = chai.assert;
var sinon = require('sinon');
import { assert } from 'chai';
import sinon from 'sinon';
import * as logging from '@optimizely/js-sdk-logging';
import * as eventProcessor from '@optimizely/js-sdk-event-processor';

import Optimizely from './optimizely';
import testData from './tests/test_data';
import packageJSON from '../package.json';
import optimizelyFactory from './index.browser';
import configValidator from './utils/config_validator';
import eventProcessorConfigValidator from './utils/event_processor_config_validator';

var LocalStoragePendingEventsDispatcher = eventProcessor.LocalStoragePendingEventsDispatcher;

Expand Down Expand Up @@ -57,7 +55,6 @@ describe('javascript-sdk', function() {
sinon.stub(configValidator, 'validate');

xhr = sinon.useFakeXMLHttpRequest();
global.XMLHttpRequest = xhr;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this line not necessary?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looked redundant and removing it did not affect any tests.

requests = [];
xhr.onCreate = function(req) {
requests.push(req);
Expand Down
Loading