Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 src/evaluator/combiners/and.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import { ILogger } from '../../logger/types';
import thenable from '../../utils/promise/thenable';
import { MaybeThenable } from '../../dtos/types';
import { IMatcher } from '../types';
import { DEBUG_0 } from '../../logger/constants';
import { DEBUG_ENGINE_COMBINER_AND } from '../../logger/constants';

export default function andCombinerContext(log: ILogger, matchers: IMatcher[]) {

function andResults(results: boolean[]): boolean {
// Array.prototype.every is supported by target environments
const hasMatchedAll = results.every(value => value);

log.debug(DEBUG_0, [hasMatchedAll]);
log.debug(DEBUG_ENGINE_COMBINER_AND, [hasMatchedAll]);
return hasMatchedAll;
}

Expand Down
10 changes: 5 additions & 5 deletions src/evaluator/matchers/__tests__/ew.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ test('MATCHER ENDS_WITH / should return true ONLY when the value ends with ["a",
value: ['a', 'b', 'c']
} as IMatcherDto) as IMatcher;

expect(matcher('america')).toBe(true); // america end with ["a", "b", "c"]
expect(matcher('blob')).toBe(true); // blob end with ["a", "b", "c"]
expect(matcher('zodiac')).toBe(true); // zodiac end with ["a", "b", "c"]
expect(matcher('violin')).toBe(false); // t end with ["a", "b", "c"]
expect(matcher('manager')).toBe(false); // t end with ["a", "b", "c"]
expect(matcher('america')).toBe(true); // america ends with ["a", "b", "c"]
expect(matcher('blob')).toBe(true); // blob ends with ["a", "b", "c"]
expect(matcher('zodiac')).toBe(true); // zodiac ends with ["a", "b", "c"]
expect(matcher('violin')).toBe(false); // violin doesn't end with ["a", "b", "c"]
expect(matcher('manager')).toBe(false); // manager doesn't end with ["a", "b", "c"]
});

test('MATCHER ENDS_WITH / should return true ONLY when the value ends with ["demo.test.org"]', function () {
Expand Down
10 changes: 5 additions & 5 deletions src/evaluator/matchers/__tests__/sw.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ test('MATCHER STARTS_WITH / should return true ONLY when the value starts with [
value: ['a', 'b', 'c']
} as IMatcherDto) as IMatcher;

expect(matcher('awesome')).toBe(true); // awesome start with ["a", "b", "c"]
expect(matcher('black')).toBe(true); // black start with ["a", "b", "c"]
expect(matcher('chello')).toBe(true); // chello start with ["a", "b", "c"]
expect(matcher('violin')).toBe(false); // t start with ["a", "b", "c"]
expect(matcher('manager')).toBe(false); // t start with ["a", "b", "c"]
expect(matcher('awesome')).toBe(true); // awesome starts with ["a", "b", "c"]
expect(matcher('black')).toBe(true); // black starts with ["a", "b", "c"]
expect(matcher('chello')).toBe(true); // chello starts with ["a", "b", "c"]
expect(matcher('violin')).toBe(false); // violin doesn't start with ["a", "b", "c"]
expect(matcher('manager')).toBe(false); // manager doesn't start with ["a", "b", "c"]
});
6 changes: 3 additions & 3 deletions src/evaluator/value/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { SplitIO } from '../../types';
import { IMatcherDto } from '../types';
import { ILogger } from '../../logger/types';
import sanitizeValue from './sanitize';
import { DEBUG_24, WARN_1, WARN_0 } from '../../logger/constants';
import { DEBUG_24, WARN_ENGINE_NO_ATTRIBUTES, WARN_ENGINE_INVALID_VALUE } from '../../logger/constants';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

FTR: Let's use this format instead of a numeric one. It's clearer!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done in next commit


function parseValue(log: ILogger, key: string, attributeName: string | null, attributes: SplitIO.Attributes) {
let value = undefined;
Expand All @@ -11,7 +11,7 @@ function parseValue(log: ILogger, key: string, attributeName: string | null, att
value = attributes[attributeName];
log.debug(DEBUG_24, [attributeName, value]);
} else {
log.warn(WARN_1, [attributeName]);
log.warn(WARN_ENGINE_NO_ATTRIBUTES, [attributeName]);
}
} else {
value = key;
Expand All @@ -31,7 +31,7 @@ export default function value(log: ILogger, key: string, matcherDto: IMatcherDto
if (sanitizedValue !== undefined) {
return sanitizedValue;
} else {
log.warn(WARN_0, [valueToMatch, attributeName ? ' for attribute ' + attributeName : '']);
log.warn(WARN_ENGINE_INVALID_VALUE, [valueToMatch + (attributeName ? ' for attribute ' + attributeName : '')]);
return;
}
}
20 changes: 10 additions & 10 deletions src/integrations/ga/GaToSplit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import { SplitIO } from '../../types';
import { Identity, GoogleAnalyticsToSplitOptions } from './types';
import { ILogger } from '../../logger/types';
import { IIntegrationFactoryParams } from '../types';
// import { logFactory } from '../../logger/sdkLogger';
// const log = logFactory('splitio-ga-to-split');
const logNameMapper = 'splitio-ga-to-split:mapper';

const logPrefix = 'ga-to-split: ';
const logNameMapper = 'ga-to-split:mapper';

/**
* Provides a plugin to use with analytics.js, accounting for the possibility
Expand Down Expand Up @@ -169,7 +169,7 @@ export function fixEventTypeId(log: ILogger, eventTypeId: any) {
.replace(INVALID_PREFIX_REGEX, '')
.replace(INVALID_SUBSTRING_REGEX, '_');
const truncated = fixed.slice(0, 80);
if (truncated.length < fixed.length) log.warn('EventTypeId was truncated because it cannot be more than 80 characters long.');
if (truncated.length < fixed.length) log.warn(logPrefix + 'EventTypeId was truncated because it cannot be more than 80 characters long.');
return truncated;
}

Expand Down Expand Up @@ -210,19 +210,19 @@ export default function GaToSplit(sdkOptions: GoogleAnalyticsToSplitOptions, par
const validIdentities = validateIdentities(opts.identities);

if (validIdentities.length === 0) {
log.warn('No valid identities were provided. Please check that you are passing a valid list of identities or providing a traffic type at the SDK configuration.');
log.warn(logPrefix + 'No valid identities were provided. Please check that you are passing a valid list of identities or providing a traffic type at the SDK configuration.');
return;
}

const invalids = validIdentities.length - opts.identities.length;
if (invalids) {
log.warn(`${invalids} identities were discarded because they are invalid or duplicated. Identities must be an array of objects with key and trafficType.`);
log.warn(logPrefix + `${invalids} identities were discarded because they are invalid or duplicated. Identities must be an array of objects with key and trafficType.`);
}
opts.identities = validIdentities;

// Validate prefix
if (!isString(opts.prefix)) {
log.warn('The provided `prefix` was ignored since it is invalid. Please check that you are passing a string object as `prefix`.');
log.warn(logPrefix + 'The provided `prefix` was ignored since it is invalid. Please check that you are passing a string object as `prefix`.');
opts.prefix = undefined;
}

Expand All @@ -239,7 +239,7 @@ export default function GaToSplit(sdkOptions: GoogleAnalyticsToSplitOptions, par
try {
if (opts.filter && !opts.filter(model)) return;
} catch (err) {
log.warn(`GaToSplit custom filter threw: ${err}`);
log.warn(logPrefix + `custom filter threw: ${err}`);
return;
}

Expand All @@ -249,7 +249,7 @@ export default function GaToSplit(sdkOptions: GoogleAnalyticsToSplitOptions, par
try {
eventData = opts.mapper(model, eventData as SplitIO.EventData);
} catch (err) {
log.warn(`GaToSplit custom mapper threw: ${err}`);
log.warn(logPrefix + `custom mapper threw: ${err}`);
return;
}
if (!eventData)
Expand Down Expand Up @@ -278,7 +278,7 @@ export default function GaToSplit(sdkOptions: GoogleAnalyticsToSplitOptions, par
}
});

log.info('Started GA-to-Split integration');
log.info(logPrefix + 'integration started');
}

}
Expand Down
13 changes: 6 additions & 7 deletions src/integrations/ga/SplitToGa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import { SplitIO } from '../../types';
import { IIntegration } from '../types';
import { SplitToGoogleAnalyticsOptions } from './types';
import { ILogger } from '../../logger/types';
// import { logFactory } from '../../logger/sdkLogger';
// const log = logFactory('splitio-split-to-ga');

const logPrefix = 'split-to-ga: ';
const noGaWarning = '`ga` command queue not found.';
const noHit = 'No hit was sent.';

Expand Down Expand Up @@ -64,7 +63,7 @@ export default class SplitToGa implements IIntegration {
static validateFieldsObject(log: ILogger, fieldsObject: any): fieldsObject is UniversalAnalytics.FieldsObject {
if (fieldsObject && fieldsObject.hitType) return true;

log.warn('your custom mapper returned an invalid FieldsObject instance. It must be an object with at least a `hitType` field.');
log.warn(logPrefix + 'your custom mapper returned an invalid FieldsObject instance. It must be an object with at least a `hitType` field.');
return false;
}

Expand All @@ -90,8 +89,8 @@ export default class SplitToGa implements IIntegration {
this.events = options.events;
}

log.info('Started Split-to-GA integration');
if (typeof SplitToGa.getGa() !== 'function') log.warn(`${noGaWarning} No hits will be sent until it is available.`);
log.info(logPrefix + 'integration started');
if (typeof SplitToGa.getGa() !== 'function') log.warn(logPrefix + `${noGaWarning} No hits will be sent until it is available.`);
}

queue(data: SplitIO.IntegrationData) {
Expand All @@ -116,7 +115,7 @@ export default class SplitToGa implements IIntegration {
if (!fieldsObject || !SplitToGa.validateFieldsObject(this.log, fieldsObject)) return;
}
} catch (err) {
this.log.warn(`SplitToGa queue method threw: ${err}. ${noHit}`);
this.log.warn(logPrefix + `queue method threw: ${err}. ${noHit}`);
return;
}

Expand All @@ -129,7 +128,7 @@ export default class SplitToGa implements IIntegration {
ga(sendCommand, fieldsObject);
});
} else {
this.log.warn(`${noGaWarning} ${noHit}`);
this.log.warn(logPrefix + `${noGaWarning} ${noHit}`);
}
}

Expand Down
12 changes: 6 additions & 6 deletions src/integrations/ga/__tests__/SplitToGa.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ describe('SplitToGa', () => {
// @ts-expect-error
integration.queue('fake-data');
expect(loggerMock.warn.mock.calls).toEqual([ // Warn when creating and queueing while ga command queue does not exist
['`ga` command queue not found. No hits will be sent until it is available.'],
['`ga` command queue not found. No hit was sent.']
['split-to-ga: `ga` command queue not found. No hits will be sent until it is available.'],
['split-to-ga: `ga` command queue not found. No hit was sent.']
]);
});

Expand Down Expand Up @@ -138,7 +138,7 @@ describe('SplitToGa', () => {
}) as SplitToGa;
ga.mockClear();
instance2.queue(fakeImpression);
expect(ga.mock.calls.length === 0).toBe(true); // t queue `ga send` if a Split data (impression or event) is filtered
expect(ga).not.toBeCalled(); // shouldn't queue `ga send` if a Split data (impression or event) is filtered

instance2.queue(fakeEvent);
expect(ga.mock.calls).toEqual([
Expand Down Expand Up @@ -171,23 +171,23 @@ describe('SplitToGa', () => {
}) as SplitToGa;
ga.mockClear();
instance4.queue(fakeImpression);
expect(ga.mock.calls.length === 0).toBe(true); // t queue `ga send` if a custom mapper throw an exception
expect(ga).not.toBeCalled(); // shouldn't queue `ga send` if a custom mapper throw an exception

// `impressions` flags
const instance5 = new SplitToGa(loggerMock, {
impressions: false,
}) as SplitToGa;
ga.mockClear();
instance5.queue(fakeImpression);
expect(ga.mock.calls.length === 0).toBe(true); // t queue `ga send` for an impression if `impressions` flag is false
expect(ga).not.toBeCalled(); // shouldn't queue `ga send` for an impression if `impressions` flag is false

// `impressions` flags
const instance6 = new SplitToGa(loggerMock, {
events: false,
}) as SplitToGa;
ga.mockClear();
instance6.queue(fakeEvent);
expect(ga.mock.calls.length === 0).toBe(true); // t queue `ga send` for a event if `events` flag is false
expect(ga).not.toBeCalled(); // shouldn't queue `ga send` for a event if `events` flag is false

// test teardown
gaRemove();
Expand Down
4 changes: 2 additions & 2 deletions src/listeners/__tests__/browser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ test('Browser JS listener / Impressions debug mode', (done) => {
expect((fakeSplitApi.postTestImpressionsCount as jest.Mock).mock.calls.length).toBe(0);

// pre-check and call stop
expect((global.window.removeEventListener as jest.Mock).mock.calls.length === 0).toBe(true);
expect(global.window.removeEventListener).not.toBeCalled();
listener.stop();

// removed correct listener from correct signal on stop.
Expand Down Expand Up @@ -191,7 +191,7 @@ test('Browser JS listener / Impressions debug mode without sendBeacon API', (don
expect((fakeSplitApi.postTestImpressionsCount as jest.Mock).mock.calls.length).toBe(0);

// pre-check and call stop
expect((global.window.removeEventListener as jest.Mock).mock.calls.length === 0).toBe(true);
expect(global.window.removeEventListener).not.toBeCalled();
listener.stop();

// removed correct listener from correct signal on stop.
Expand Down
2 changes: 1 addition & 1 deletion src/listeners/__tests__/node.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ test('Node JS listener / Signal Listener class methods and start/stop functional
expect(processOnSpy.mock.calls).toEqual([['SIGTERM', listener._sigtermHandler]]);

// pre-check and call stop
expect(processRemoveListenerSpy.mock.calls.length === 0).toBe(true);
expect(processRemoveListenerSpy).not.toBeCalled();
listener.stop();

// removed correct listener from correct signal on stop.
Expand Down
5 changes: 3 additions & 2 deletions src/listeners/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { DEBUG_26, DEBUG_27 } from '../logger/constants';

// 'unload' event is used instead of 'beforeunload', since 'unload' is not a cancelable event, so no other listeners can stop the event from occurring.
const UNLOAD_DOM_EVENT = 'unload';
const EVENT_NAME = 'for unload page event.';

/**
* We'll listen for 'unload' event over the window object, since it's the standard way to listen page reload and close.
Expand All @@ -39,7 +40,7 @@ export default class BrowserSignalListener implements ISignalListener {
*/
start() {
if (typeof window !== 'undefined' && window.addEventListener) {
this.settings.log.debug(DEBUG_26);
this.settings.log.debug(DEBUG_26, [EVENT_NAME]);
window.addEventListener(UNLOAD_DOM_EVENT, this.flushData);
}
}
Expand All @@ -51,7 +52,7 @@ export default class BrowserSignalListener implements ISignalListener {
*/
stop() {
if (typeof window !== 'undefined' && window.removeEventListener) {
this.settings.log.debug(DEBUG_27);
this.settings.log.debug(DEBUG_27, [EVENT_NAME]);
window.removeEventListener(UNLOAD_DOM_EVENT, this.flushData);
}
}
Expand Down
19 changes: 11 additions & 8 deletions src/listeners/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { ISignalListener } from './types';
import thenable from '../utils/promise/thenable';
import { MaybeThenable } from '../dtos/types';
import { ISettings } from '../types';
import { DEBUG_28, DEBUG_29, DEBUG_30, ERROR_1 } from '../logger/constants';
import { CLEANUP_LB, DEBUG_26, DEBUG_27 } from '../logger/constants';

const SIGTERM = 'SIGTERM';
const EVENT_NAME = 'for SIGTERM signal.';

/**
* We'll listen for SIGTERM since it's the standard signal for server shutdown.
Expand All @@ -22,15 +25,15 @@ export default class NodeSignalListener implements ISignalListener {
}

start() {
this.settings.log.debug(DEBUG_28);
this.settings.log.debug(DEBUG_26, [EVENT_NAME]);
// eslint-disable-next-line no-undef
process.on('SIGTERM', this._sigtermHandler);
process.on(SIGTERM, this._sigtermHandler);
}

stop() {
this.settings.log.debug(DEBUG_29);
this.settings.log.debug(DEBUG_27, [EVENT_NAME]);
// eslint-disable-next-line no-undef
process.removeListener('SIGTERM', this._sigtermHandler);
process.removeListener(SIGTERM, this._sigtermHandler);
}

/**
Expand All @@ -43,17 +46,17 @@ export default class NodeSignalListener implements ISignalListener {

// This handler prevented the default behaviour, start again.
// eslint-disable-next-line no-undef
process.kill(process.pid, 'SIGTERM');
process.kill(process.pid, SIGTERM);
};

this.settings.log.debug(DEBUG_30);
this.settings.log.debug(CLEANUP_LB + 'Split SDK graceful shutdown after SIGTERM.');

let handlerResult = null;

try {
handlerResult = this.handler();
} catch (err) {
this.settings.log.error(ERROR_1, [err]);
this.settings.log.error(CLEANUP_LB + `Error with Split SDK graceful shutdown: ${err}`);
}

if (thenable(handlerResult)) {
Expand Down
11 changes: 11 additions & 0 deletions src/logger/browser/debugLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Logger } from '../index';
import { codesError } from '../messages/error';
import { codesWarn } from '../messages/warn';
import { codesInfo } from '../messages/info';
import { codesDebug } from '../messages/debug';
import { _Map } from '../../utils/lang/maps';

export const debugLogger = new Logger(
'splitio', { logLevel: 'DEBUG' },
new _Map(codesError.concat(codesWarn, codesInfo, codesDebug))
);
8 changes: 8 additions & 0 deletions src/logger/browser/errorLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Logger } from '../index';
import { codesError } from '../messages/error';
import { _Map } from '../../utils/lang/maps';

export const errorLogger = new Logger(
'splitio', { logLevel: 'ERROR' },
new _Map(codesError)
);
10 changes: 10 additions & 0 deletions src/logger/browser/infoLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Logger } from '../index';
import { codesError } from '../messages/error';
import { codesWarn } from '../messages/warn';
import { codesInfo } from '../messages/info';
import { _Map } from '../../utils/lang/maps';

export const infoLogger = new Logger(
'splitio', { logLevel: 'INFO' },
new _Map(codesError.concat(codesWarn, codesInfo))
);
9 changes: 9 additions & 0 deletions src/logger/browser/warnLogger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Logger } from '../index';
import { codesError } from '../messages/error';
import { codesWarn } from '../messages/warn';
import { _Map } from '../../utils/lang/maps';

export const warnLogger = new Logger(
'splitio', { logLevel: 'WARN' },
new _Map(codesError.concat(codesWarn))
);
Loading