mirror of
https://github.com/socketio/socket.io.git
synced 2026-04-30 03:00:39 -04:00
The yeast() method could generate the same string twice when used in
two different iframes, which can cause Safari to only send one HTTP
request (deduplication) and trigger an HTTP 400 error afterwards since
the two iframes share the same session ID.
This new method, combining 5 chars from the timestamp and 3 chars from
Math.random() should be sufficient for our use case.
Related: https://github.com/socketio/engine.io/issues/690
See also: 874484cc1e
66 lines
1.7 KiB
TypeScript
66 lines
1.7 KiB
TypeScript
import { globalThisShim as globalThis } from "./globals.node.js";
|
|
|
|
export function pick(obj, ...attr) {
|
|
return attr.reduce((acc, k) => {
|
|
if (obj.hasOwnProperty(k)) {
|
|
acc[k] = obj[k];
|
|
}
|
|
return acc;
|
|
}, {});
|
|
}
|
|
|
|
// Keep a reference to the real timeout functions so they can be used when overridden
|
|
const NATIVE_SET_TIMEOUT = globalThis.setTimeout;
|
|
const NATIVE_CLEAR_TIMEOUT = globalThis.clearTimeout;
|
|
|
|
export function installTimerFunctions(obj, opts) {
|
|
if (opts.useNativeTimers) {
|
|
obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis);
|
|
obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis);
|
|
} else {
|
|
obj.setTimeoutFn = globalThis.setTimeout.bind(globalThis);
|
|
obj.clearTimeoutFn = globalThis.clearTimeout.bind(globalThis);
|
|
}
|
|
}
|
|
|
|
// base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
|
|
const BASE64_OVERHEAD = 1.33;
|
|
|
|
// we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
|
|
export function byteLength(obj) {
|
|
if (typeof obj === "string") {
|
|
return utf8Length(obj);
|
|
}
|
|
// arraybuffer or blob
|
|
return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
|
|
}
|
|
|
|
function utf8Length(str) {
|
|
let c = 0,
|
|
length = 0;
|
|
for (let i = 0, l = str.length; i < l; i++) {
|
|
c = str.charCodeAt(i);
|
|
if (c < 0x80) {
|
|
length += 1;
|
|
} else if (c < 0x800) {
|
|
length += 2;
|
|
} else if (c < 0xd800 || c >= 0xe000) {
|
|
length += 3;
|
|
} else {
|
|
i++;
|
|
length += 4;
|
|
}
|
|
}
|
|
return length;
|
|
}
|
|
|
|
/**
|
|
* Generates a random 8-characters string.
|
|
*/
|
|
export function randomString() {
|
|
return (
|
|
Date.now().toString(36).substring(3) +
|
|
Math.random().toString(36).substring(2, 5)
|
|
);
|
|
}
|