Initial commit

This commit is contained in:
Paul Fey 2025-06-20 09:47:10 +02:00
commit c310cd7943
19 changed files with 3939 additions and 0 deletions

67
shared/data.js Normal file
View file

@ -0,0 +1,67 @@
export function json2buf(json) {
return str2buf(json2str(json))
}
export function json2bin(json) {
return str2bin(json2str(json))
}
export function len(binOrBuf) {
return binOrBuf.byteLength
}
export function buf2json(buf) {
return str2json(buf2str(buf))
}
export function str2json(str) {
return JSON.parse(str)
}
export function json2str(json) {
return JSON.stringify(json)
}
export function str2buf(str) {
return Buffer.from(str, 'utf-8')
}
export function buf2str(buf) {
return buf.toString('utf-8')
}
export function bin2buf(bin) {
return Buffer.from(bin)
}
export function buf2bin(buf) {
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
}
export function buf2hex(buf) {
return buf.toString('hex')
}
export function bin2hex(bin) {
return buf2hex(bin2buf(bin))
}
export function bin2json(bin) {
return buf2json(bin2buf(bin))
}
export function bin2str(bin) {
return buf2str(bin2buf(bin))
}
export function str2bin(str) {
return buf2bin(str2buf(str))
}
export function allocOfBin(size = 0) {
return Buffer.alloc(size).buffer
}
export function allocOfBuf(size = 0) {
return Buffer.alloc(size)
}

35
shared/defer.js Normal file
View file

@ -0,0 +1,35 @@
export function Deferred() {
const defer = {}
defer.promise = new Promise(function (resolve, reject) {
defer.resolve = resolve
defer.reject = reject
})
return defer
}
export function delay(ms) {
const defer = Deferred()
setTimeout(defer.resolve, ms)
return defer.promise
}
export function timeout(ms, cb) {
const defer = Deferred()
ms = ms || 1000
const wait = setTimeout(() => {
clearTimeout(wait)
if (cb) {
cb && cb(defer.resolve, defer.reject)
} else {
defer.reject('Timed out in ' + ms + 'ms.')
}
}, ms)
return defer.promise
}

View file

@ -0,0 +1,6 @@
import './es6-promise'
ES6Promise.polyfill()
Promise._setScheduler(function (flush) {
flush && flush()
})

1149
shared/es6-promise.js Normal file

File diff suppressed because it is too large Load diff

42
shared/event.js Normal file
View file

@ -0,0 +1,42 @@
export class EventBus {
constructor() {
this.map = new Map()
}
on(type, cb) {
if (this.map.has(type)) {
this.map.get(type).push(cb)
} else {
this.map.set(type, [cb])
}
}
off(type, cb) {
if (type) {
if (cb) {
const cbs = this.map.get(type)
if (!cbs) return
const index = cbs.findIndex((i) => i === cb)
if (index >= 0) {
cbs.splice(index, 1)
}
} else {
this.map.delete(type)
}
} else {
this.map.clear()
}
}
emit(type, ...args) {
for (let cb of this.map.get(type) ? this.map.get(type) : []) {
cb && cb(...args)
}
}
count(type) {
return this.map.get(type) ? this.map.get(type).length : 0
}
}

1145
shared/message-side.js Normal file

File diff suppressed because it is too large Load diff

1151
shared/message.js Normal file

File diff suppressed because it is too large Load diff