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

Export TypeScript Types, Minor Code Housekeeping #13

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ build
dist
.DS_Store
coverage
.idea/
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
"version": "1.1.2",
"module": "dist/index.esm.js",
"license": "MIT",
"types": "./dist/types/index.d.ts",
"types": "./dist/types/types.d.ts",
"scripts": {
"clean": "rm -rf dist",
"build": "npm run clean && rollup -c rollup.config.ts",
"start": "rollup -c rollup.config.ts -w",
"lint": "prettier --write --config .prettierrc.json ./src/*.ts",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "npm run test -- --coverage",
Expand Down
10 changes: 3 additions & 7 deletions rollup.config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from 'rollup-plugin-typescript2';
import json from '@rollup/plugin-json';
import { terser } from 'rollup-plugin-terser';
import resolve from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import copy from 'rollup-plugin-copy';
import { terser } from 'rollup-plugin-terser';
import typescript from 'rollup-plugin-typescript2';

const OUTPUT_DATA = [
{
Expand Down Expand Up @@ -48,9 +47,6 @@ const config = OUTPUT_DATA.map(({ file, format, input }) => ({
comments: false,
},
}),
copy({
targets: [{ src: 'src/logdna.d.ts', dest: 'dist/types' }],
}),
],
}));

Expand Down
28 changes: 9 additions & 19 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,15 @@
const DEFAULT_INGESTION_URL = 'https://logs.logdna.com/logs/ingest';
const LOG_LINE_FLUSH_TIMEOUT = 250; // ms
const FLUSH_BYTE_LIMIT = 60 * 1024; // Max chrome allows with fetch and keep alive is 64kb, we are making it smaller to account for headers and unknowns
const SAMPLE_RATE = 100;
export const DEFAULT_INGESTION_URL: string =
'https://logs.logdna.com/logs/ingest';
export const LOG_LINE_FLUSH_TIMEOUT: number = 250; // ms
export const FLUSH_BYTE_LIMIT: number = 60 * 1024; // Max chrome allows with fetch and keep alive is 64kb, we are making it smaller to account for headers and unknowns
export const SAMPLE_RATE: number = 100;

const STARTING_BACK_OFF = 1000; // 1 sec
const MAX_BACK_OFF = 60000; // 60 sec
export const STARTING_BACK_OFF: number = 1000; // 1 sec
export const MAX_BACK_OFF: number = 60000; // 60 sec

const MAX_FETCH_ERROR_RETRY = 30;
export const MAX_FETCH_ERROR_RETRY: number = 30;

const HOSTNAME_CHECK = new RegExp(
export const HOSTNAME_CHECK: RegExp = new RegExp(
'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\\.)*' +
'([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$',
);

export {
DEFAULT_INGESTION_URL,
LOG_LINE_FLUSH_TIMEOUT,
FLUSH_BYTE_LIMIT,
HOSTNAME_CHECK,
SAMPLE_RATE,
MAX_FETCH_ERROR_RETRY,
STARTING_BACK_OFF,
MAX_BACK_OFF,
};
69 changes: 69 additions & 0 deletions src/exceptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
export class InvalidConsoleIntegrationError extends Error {
constructor() {
super(`LogDNA Browser Logger console integration types must be an array`);
}
}

export class InvalidConsoleMethodError extends Error {
constructor() {
super(
`LogDNA Browser Logger console plugin was passed an invalid console methods`,
);
}
}

export class UndefinedIngestionKeyError extends Error {
constructor() {
super(`Ingestion key can not be undefined when calling init`);
}
}

export class InvalidHostnameError extends Error {
constructor(public readonly hostname: string) {
super(
`LogDNA Browser Logger: \`${hostname}\` is not a valid hostname, see documentation for the \`hostname\` configuration option for details.`,
);
}
}

export class InvalidSampleRateError extends Error {
constructor() {
super(
`LogDNA Browser Logger: \`sampleRate\` option must be a number between 0 and 100`,
);
}
}

export class DuplicatePluginMethodError extends Error {
constructor() {
super(
'A LogDNA Browser Logger plugin is attempting to register a method that already exists.',
);
}
}

export class MissingPluginNameError extends Error {
constructor() {
super(`A LogDNA Browser Logger plugin must contain a name property`);
}
}

export class MissingPluginInitError extends Error {
constructor() {
super(`A LogDNA Browser Logger plugin must contain an init function`);
}
}

export class DuplicatePluginRegistrationError extends Error {
constructor(public readonly pluginName: string) {
super(`The plugin ${pluginName} is already registered with LogDNA Browser`);
}
}

export class PrematureLogLineError extends Error {
constructor() {
super(
`LogDNA Browser Logger: Attempting send to log lines before calling "init()"`,
);
}
}
60 changes: 28 additions & 32 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,33 @@
import { detect } from 'detect-browser';
import {
ContextT,
LogDNABrowserOptionsT,
StaticContext,
ILogDNABrowserLogger,
Plugin,
} from './logdna.d';
import utils from './utils';
import {
DEFAULT_INGESTION_URL,
LOG_LINE_FLUSH_TIMEOUT,
SAMPLE_RATE,
} from './constants';
import {
DuplicatePluginMethodError,
DuplicatePluginRegistrationError,
InvalidHostnameError,
InvalidSampleRateError,
MissingPluginInitError,
MissingPluginNameError,
PrematureLogLineError,
UndefinedIngestionKeyError,
} from './exceptions';

import Logger from './logger';
import SessionManager from './session-manager';
import allPlugins from './plugins';
import ConsolePlugin from './plugins/console';
import GlobalErrorHandlerPlugin from './plugins/global-handlers';
import allPlugins from './plugins';
import SessionManager from './session-manager';
import {
ContextT,
ILogDNABrowserLogger,
LogDNABrowserOptionsT,
Plugin,
StaticContext,
} from './types';
import utils from './utils';

class LogDNABrowserLogger implements ILogDNABrowserLogger {
Plugins = allPlugins;
Expand Down Expand Up @@ -53,16 +63,14 @@ class LogDNABrowserLogger implements ILogDNABrowserLogger {
this.options = { ...this.options, ...options };

if (ingestionKey == null) {
throw new Error('Ingestion key can not be undefined when calling init');
throw new UndefinedIngestionKeyError();
}

if (
this.options.hostname &&
!utils.validateHostname(this.options.hostname)
) {
throw new Error(
`LogDNA Browser Logger: \`${this.options.hostname}\` is not a valid hostname, see documentation for the \`hostname\` configuration option for details.`,
);
throw new InvalidHostnameError(this.options.hostname);
}

if (
Expand All @@ -71,9 +79,7 @@ class LogDNABrowserLogger implements ILogDNABrowserLogger {
this.options.sampleRate > 100 ||
isNaN(this.options.sampleRate)
) {
throw new Error(
`LogDNA Browser Logger: \`sampleRate\` option must be a number between 0 and 100`,
);
throw new InvalidSampleRateError();
}

this.staticContext = this.getStaticContext();
Expand Down Expand Up @@ -184,9 +190,7 @@ class LogDNABrowserLogger implements ILogDNABrowserLogger {
registerMethod(name: string, fn: Function) {
// @ts-ignore
if (this[name]) {
throw Error(
'A LogDNA Browser Logger plugin is attempting to register a method that already exists.',
);
throw new DuplicatePluginMethodError();
}
// @ts-ignore
this[name] = fn;
Expand Down Expand Up @@ -228,21 +232,15 @@ class LogDNABrowserLogger implements ILogDNABrowserLogger {

private registerPlugin(plugin: Plugin) {
if (!plugin.name) {
throw new Error(
'A LogDNA Browser Logger plugin must contain a name property',
);
throw new MissingPluginNameError();
}

if (typeof plugin.init !== 'function') {
throw new Error(
'A LogDNA Browser Logger plugin must contain an init function',
);
throw new MissingPluginInitError();
}

if (this.plugins.includes(plugin.name)) {
throw Error(
`The plugin ${plugin.name} is already registered with LogDNA Browser`,
);
throw new DuplicatePluginRegistrationError(plugin.name);
}

this.plugins.push(plugin.name);
Expand All @@ -257,9 +255,7 @@ class LogDNABrowserLogger implements ILogDNABrowserLogger {

private logLines(level: string, message: any, lineContext?: any) {
if (this.logger == null) {
throw new Error(
'LogDNA Browser Logger: Attempting send to log lines before calling `.init()`',
);
throw new PrematureLogLineError();
}

if (
Expand Down
2 changes: 1 addition & 1 deletion src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { LoggerOptionsT, LogDNALogLine } from './logdna.d';
import { LoggerOptionsT, LogDNALogLine } from './types';
import {
LOG_LINE_FLUSH_TIMEOUT,
FLUSH_BYTE_LIMIT,
Expand Down
37 changes: 19 additions & 18 deletions src/plugins/console.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { Plugin, ILogDNABrowserLogger } from '../logdna.d';
import {
InvalidConsoleIntegrationError,
InvalidConsoleMethodError,
} from '../exceptions';
import {
ConsoleOptions,
ILogDNABrowserLogger,
ConsoleLogType,
Plugin,
} from '../types';

type LogType = 'log' | 'debug' | 'error' | 'warn' | 'info' | 'assert';

export type Options = {
integrations?: LogType[];
enable?: boolean;
};

export const DEFAULT_CONSOLE_METHODS: LogType[] = [
export const DEFAULT_CONSOLE_METHODS: ConsoleLogType[] = [
'log',
'debug',
'error',
Expand All @@ -21,7 +23,7 @@ class ConsolePlugin implements Plugin {
options;

constructor(
options: Options = {
options: ConsoleOptions = {
integrations: DEFAULT_CONSOLE_METHODS,
},
) {
Expand All @@ -32,9 +34,7 @@ class ConsolePlugin implements Plugin {
const { integrations = DEFAULT_CONSOLE_METHODS } = this.options;

if (!Array.isArray(integrations)) {
throw new Error(
'LogDNA Browser Logger console integration types must be an array',
);
throw new InvalidConsoleIntegrationError();
}

const { log, debug, error, warn, info, assert } = window.console;
Expand All @@ -44,12 +44,13 @@ class ConsolePlugin implements Plugin {
window.__LogDNA__.console = _windowConsole;

(integrations || [])
.map((method: LogType): LogType => method.toLowerCase() as LogType)
.forEach((method: LogType) => {
.map(
(method: ConsoleLogType): ConsoleLogType =>
method.toLowerCase() as ConsoleLogType,
)
.forEach((method: ConsoleLogType) => {
if (!DEFAULT_CONSOLE_METHODS.includes(method)) {
throw Error(
'LogDNA Browser Logger console plugin was passed an invalid console methods',
);
throw new InvalidConsoleMethodError();
}

window.console[method] = (...args: any[]) => {
Expand Down
13 changes: 6 additions & 7 deletions src/plugins/global-handlers.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { Plugin, ILogDNABrowserLogger } from '../logdna.d';

export type Options = {
enableErrorHandler?: boolean;
enableUnhandledPromiseRejection?: boolean;
};
import {
GlobalErrorHandlerOptions,
ILogDNABrowserLogger,
Plugin,
} from '../types';

class GlobalErrorHandlerPlugin implements Plugin {
name = 'GlobalErrorHandlerPlugin';
logdna: any;
options;

constructor(
options: Options = {
options: GlobalErrorHandlerOptions = {
enableErrorHandler: true,
enableUnhandledPromiseRejection: true,
},
Expand Down
18 changes: 9 additions & 9 deletions src/plugins/performance-measure.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { Plugin, ILogDNABrowserLogger, LogType } from '../logdna.d';
export type Options = {
prefix?: String;
logLevel?: LogType;
};
import {
Plugin,
ILogDNABrowserLogger,
PerformanceMeasureOptions,
} from '../types';

const NAMESPACE = 'logdna:';
const NAMESPACE: string = 'logdna:';

/* istanbul ignore next */
class PerformanceMeasurePlugin implements Plugin {
name = 'PerformanceMeasurePlugin';
logdna: any;
options: Options;
options: PerformanceMeasureOptions;

constructor(options: Options = {}) {
const defaultOptions: Options = {
constructor(options: PerformanceMeasureOptions = {}) {
const defaultOptions: PerformanceMeasureOptions = {
prefix: 'Performance Measurement',
logLevel: 'debug',
};
Expand Down
Loading