Skip to content

Commit

Permalink
rename util to Utils
Browse files Browse the repository at this point in the history
  • Loading branch information
afrokick committed Feb 19, 2022
1 parent 6bfb586 commit a930635
Show file tree
Hide file tree
Showing 18 changed files with 337 additions and 390 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ Parcel 1 was a good choice years ago, but now esbuild seems like simple and good

- update `devDependencies`
- apply `Prettier` for the code style
- rename `util` to `Utils`
- remove `peerjs` export.

<a name="1.3.2"></a>

Expand Down
35 changes: 16 additions & 19 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,40 +45,37 @@ declare class Peer {
* @param event Event name
* @param cb id is the brokering ID of the peer
*/
on(event: "open", cb: (id: string) => void): void;
on(event: 'open', cb: (id: string) => void): void;
/**
* Emitted when a new data connection is established from a remote peer.
* @param event Event name
* @param cb Callback Function
*/
on(
event: "connection",
cb: (dataConnection: Peer.DataConnection) => void
): void;
on(event: 'connection', cb: (dataConnection: Peer.DataConnection) => void): void;
/**
* Emitted when a remote peer attempts to call you.
* @param event Event name
* @param cb Callback Function
*/
on(event: "call", cb: (mediaConnection: Peer.MediaConnection) => void): void;
on(event: 'call', cb: (mediaConnection: Peer.MediaConnection) => void): void;
/**
* Emitted when the peer is destroyed and can no longer accept or create any new connections.
* @param event Event name
* @param cb Callback Function
*/
on(event: "close", cb: () => void): void;
on(event: 'close', cb: () => void): void;
/**
* Emitted when the peer is disconnected from the signalling server
* @param event Event name
* @param cb Callback Function
*/
on(event: "disconnected", cb: () => void): void;
on(event: 'disconnected', cb: () => void): void;
/**
* Errors on the peer are almost always fatal and will destroy the peer.
* @param event Event name
* @param cb Callback Function
*/
on(event: "error", cb: (err: any) => void): void;
on(event: 'error', cb: (err: any) => void): void;
/**
* Remove event listeners.(EventEmitter3)
* @param {String} event The event we want to remove.
Expand Down Expand Up @@ -161,10 +158,10 @@ declare namespace Peer {
send(data: any): void;
close(): void;
on(event: string, cb: () => void): void;
on(event: "data", cb: (data: any) => void): void;
on(event: "open", cb: () => void): void;
on(event: "close", cb: () => void): void;
on(event: "error", cb: (err: any) => void): void;
on(event: 'data', cb: (data: any) => void): void;
on(event: 'open', cb: () => void): void;
on(event: 'close', cb: () => void): void;
on(event: 'error', cb: (err: any) => void): void;
off(event: string, fn: Function, once?: boolean): void;
dataChannel: RTCDataChannel;
label: string;
Expand All @@ -184,9 +181,9 @@ declare namespace Peer {
answer(stream?: MediaStream, options?: AnswerOption): void;
close(): void;
on(event: string, cb: () => void): void;
on(event: "stream", cb: (stream: MediaStream) => void): void;
on(event: "close", cb: () => void): void;
on(event: "error", cb: (err: any) => void): void;
on(event: 'stream', cb: (stream: MediaStream) => void): void;
on(event: 'close', cb: () => void): void;
on(event: 'error', cb: (err: any) => void): void;
off(event: string, fn: Function, once?: boolean): void;
open: boolean;
metadata: any;
Expand All @@ -195,15 +192,15 @@ declare namespace Peer {
type: string;
}

interface UtilSupportsObj {
interface Features {
webRTC: boolean;
audioVideo: boolean;
data: boolean;
binaryBlob: boolean;
reliable: boolean;
}

interface util {
supports: UtilSupportsObj;
interface Utils {
readonly features: Features;
}
}
6 changes: 3 additions & 3 deletions lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { util } from './util';
import { Utils } from './utils';
import logger from './logger';

export class API {
Expand Down Expand Up @@ -31,7 +31,7 @@ export class API {

let pathError = '';

if (this._options.path === '/' && this._options.host !== util.CLOUD_HOST) {
if (this._options.path === '/' && this._options.host !== Utils.CLOUD_HOST) {
pathError =
' If you passed in a `path` to your self-hosted PeerServer, ' +
"you'll also need to pass in that same path when creating a new " +
Expand All @@ -53,7 +53,7 @@ export class API {
if (response.status === 401) {
let helpfulError = '';

if (this._options.host === util.CLOUD_HOST) {
if (this._options.host === Utils.CLOUD_HOST) {
helpfulError =
"It looks like you're using the cloud server. You can email " +
'[email protected] to enable peer listing for your API key.';
Expand Down
24 changes: 12 additions & 12 deletions lib/dataconnection.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { util } from './util';
import { Utils } from './utils';
import logger from './logger';
import { Negotiator } from './negotiator';
import { ConnectionType, ConnectionEventType, SerializationType, ServerMessageType } from './enums';
Expand Down Expand Up @@ -51,7 +51,7 @@ export class DataConnection extends BaseConnection implements IDataConnection {
constructor(peerId: string, provider: Peer, options: any) {
super(peerId, provider, options);

this.connectionId = this.options.connectionId || DataConnection.ID_PREFIX + util.randomToken();
this.connectionId = this.options.connectionId || DataConnection.ID_PREFIX + Utils.randomToken();

this.label = this.options.label || this.connectionId;
this.serialization = this.options.serialization || SerializationType.Binary;
Expand Down Expand Up @@ -82,7 +82,7 @@ export class DataConnection extends BaseConnection implements IDataConnection {
}

private _configureDataChannel(): void {
if (!util.supports.binaryBlob || util.supports.reliable) {
if (!Utils.supports.binaryBlob || Utils.supports.reliable) {
this.dataChannel.binaryType = 'arraybuffer';
}

Expand Down Expand Up @@ -115,17 +115,17 @@ export class DataConnection extends BaseConnection implements IDataConnection {
if (isBinarySerialization) {
if (datatype === Blob) {
// Datatype should never be blob
util.blobToArrayBuffer(data as Blob, ab => {
const unpackedData = util.unpack(ab);
Utils.blobToArrayBuffer(data as Blob, ab => {
const unpackedData = Utils.unpack(ab);
this.emit(ConnectionEventType.Data, unpackedData);
});
return;
} else if (datatype === ArrayBuffer) {
deserializedData = util.unpack(data as ArrayBuffer);
deserializedData = Utils.unpack(data as ArrayBuffer);
} else if (datatype === String) {
// String fallback for binary data for browsers that don't support binary yet
const ab = util.binaryStringToArrayBuffer(data as string);
deserializedData = util.unpack(ab);
const ab = Utils.binaryStringToArrayBuffer(data as string);
deserializedData = Utils.unpack(ab);
}
} else if (this.serialization === SerializationType.JSON) {
deserializedData = this.parse(data as string);
Expand Down Expand Up @@ -219,14 +219,14 @@ export class DataConnection extends BaseConnection implements IDataConnection {
if (this.serialization === SerializationType.JSON) {
this._bufferedSend(this.stringify(data));
} else if (this.serialization === SerializationType.Binary || this.serialization === SerializationType.BinaryUTF8) {
const blob = util.pack(data);
const blob = Utils.pack(data);

if (!chunked && blob.size > util.chunkedMTU) {
if (!chunked && blob.size > Utils.chunkedMTU) {
this._sendChunks(blob);
return;
}

if (!util.supports.binaryBlob) {
if (!Utils.supports.binaryBlob) {
// We only do this if we really need to (e.g. blobs are not supported),
// because this conversion is costly.
this._encodingQueue.enque(blob);
Expand Down Expand Up @@ -295,7 +295,7 @@ export class DataConnection extends BaseConnection implements IDataConnection {
}

private _sendChunks(blob: Blob): void {
const blobs = util.chunk(blob);
const blobs = Utils.chunk(blob);
logger.log(`DC#${this.connectionId} Try to send ${blobs.length} chunks...`);

for (let blob of blobs) {
Expand Down
14 changes: 5 additions & 9 deletions lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import { util } from './util';
import { Utils } from './utils';
import { Peer } from './peer';

export const peerjs = {
Peer,
util,
};
export { Peer, Utils };

export default Peer;

if (typeof window !== 'undefined') {
(window as any).peerjs = peerjs;
/** @deprecated Should use peerjs namespace */
(window as any).Peer = Peer;
if (typeof window === 'object') {
// @ts-expect-error
window.Peer = Peer;
}
4 changes: 2 additions & 2 deletions lib/mediaconnection.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { util } from './util';
import { Utils } from './utils';
import logger from './logger';
import { Negotiator } from './negotiator';
import { ConnectionType, ConnectionEventType, ServerMessageType } from './enums';
Expand Down Expand Up @@ -32,7 +32,7 @@ export class MediaConnection extends BaseConnection {
super(peerId, provider, options);

this._localStream = this.options._stream;
this.connectionId = this.options.connectionId || MediaConnection.ID_PREFIX + util.randomToken();
this.connectionId = this.options.connectionId || MediaConnection.ID_PREFIX + Utils.randomToken();

this._negotiator = new Negotiator(this);

Expand Down
5 changes: 3 additions & 2 deletions lib/negotiator.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { util } from './util';
import logger from './logger';
import type { MediaConnection } from './mediaconnection';
import type { DataConnection } from './dataconnection';
import { ConnectionType, PeerErrorType, ConnectionEventType, ServerMessageType } from './enums';
import { BaseConnection } from './baseconnection';

function noop(): void {}

/**
* Manages all negotiations between Peers.
*/
Expand Down Expand Up @@ -95,7 +96,7 @@ export class Negotiator {
logger.log('iceConnectionState changed to disconnected on the connection with ' + peerId);
break;
case 'completed':
peerConnection.onicecandidate = util.noop;
peerConnection.onicecandidate = noop;
break;
}

Expand Down
20 changes: 10 additions & 10 deletions lib/peer.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { EventEmitter } from 'eventemitter3';
import { util } from './util';
import { Utils } from './utils';
import logger, { LogLevel } from './logger';
import { Socket } from './socket';
import { MediaConnection } from './mediaconnection';
Expand Down Expand Up @@ -95,12 +95,12 @@ export class Peer extends EventEmitter {
// Configurize options
options = {
debug: 0, // 1: Errors, 2: Warnings, 3: All logs
host: util.CLOUD_HOST,
port: util.CLOUD_PORT,
host: Utils.CLOUD_HOST,
port: Utils.CLOUD_PORT,
path: '/',
key: Peer.DEFAULT_KEY,
token: util.randomToken(),
config: util.defaultConfig,
token: Utils.randomToken(),
config: Utils.defaultConfig,
...options,
};
this._options = options;
Expand All @@ -121,9 +121,9 @@ export class Peer extends EventEmitter {
}

// Set whether we use SSL to same as current host
if (this._options.secure === undefined && this._options.host !== util.CLOUD_HOST) {
this._options.secure = util.isSecure();
} else if (this._options.host == util.CLOUD_HOST) {
if (this._options.secure === undefined && this._options.host !== Utils.CLOUD_HOST) {
this._options.secure = Utils.isSecure();
} else if (this._options.host == Utils.CLOUD_HOST) {
this._options.secure = true;
}
// Set a custom log function if present
Expand All @@ -138,13 +138,13 @@ export class Peer extends EventEmitter {

// Sanity checks
// Ensure WebRTC supported
if (!util.supports.audioVideo && !util.supports.data) {
if (!Utils.supports.audioVideo && !Utils.supports.data) {
this._delayedAbort(PeerErrorType.BrowserIncompatible, 'The current browser does not support WebRTC');
return;
}

// Ensure alphanumeric id
if (!!userId && !util.validateId(userId)) {
if (!!userId && !Utils.validateId(userId)) {
this._delayedAbort(PeerErrorType.InvalidID, `ID "${userId}" is invalid`);
return;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/servermessage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ServerMessageType } from './enums';

export class ServerMessage {
export interface ServerMessage {
type: ServerMessageType;
payload: any;
src: string;
Expand Down
6 changes: 5 additions & 1 deletion lib/supports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ export const Supports = new (class {
}

isUnifiedPlanSupported(): boolean {
if (!window.RTCRtpTransceiver || !('currentDirection' in RTCRtpTransceiver.prototype)) return false;
if (
(typeof window !== 'undefined' && !window.RTCRtpTransceiver) ||
!('currentDirection' in RTCRtpTransceiver.prototype)
)
return false;

let tempPc: RTCPeerConnection;
let supported = false;
Expand Down
16 changes: 6 additions & 10 deletions lib/util.ts → lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as BinaryPack from 'peerjs-js-binarypack';
import { Supports } from './supports';
import type { UtilSupportsObj } from '..';
import type { Features } from '..';

const DEFAULT_CONFIG = {
iceServers: [
Expand All @@ -10,22 +10,18 @@ const DEFAULT_CONFIG = {
sdpSemantics: 'unified-plan',
};

export const util = new (class {
noop(): void {}

export const Utils = new (class {
readonly CLOUD_HOST = '0.peerjs.com';
readonly CLOUD_PORT = 443;

// Browsers that need chunking:
readonly chunkedBrowsers = { Chrome: 1, chrome: 1 };
readonly chunkedMTU = 16300; // The original 60000 bytes setting does not work when sending data from Firefox to Chrome, which is "cut off" after 16384 bytes and delivered individually.

// Returns browser-agnostic default config
readonly defaultConfig = DEFAULT_CONFIG;

// Lists which features are supported
readonly supports = (function () {
const supported: UtilSupportsObj = {
readonly supports: Features = (function () {
const supported: Features = {
webRTC: Supports.isWebRTCSupported(),
audioVideo: true,
data: false,
Expand Down Expand Up @@ -83,13 +79,13 @@ export const util = new (class {
chunk(blob: Blob): { __peerData: number; n: number; total: number; data: Blob }[] {
const chunks = [];
const size = blob.size;
const total = Math.ceil(size / util.chunkedMTU);
const total = Math.ceil(size / Utils.chunkedMTU);

let index = 0;
let start = 0;

while (start < size) {
const end = Math.min(size, start + util.chunkedMTU);
const end = Math.min(size, start + Utils.chunkedMTU);
const b = blob.slice(start, end);

const chunk = {
Expand Down
Loading

0 comments on commit a930635

Please sign in to comment.