code
stringlengths
28
313k
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
74
language
stringclasses
1 value
repo
stringlengths
5
60
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
onServerRestart (cb) { this.onInfoMessage(WSv2.info.SERVER_RESTART, cb) }
Register a callback in case of a ws server restart message; Use this to call reconnect() if needed. (code 20051) @param {Function} cb - called on event trigger
onServerRestart
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onMaintenanceStart (cb) { this.onInfoMessage(WSv2.info.MAINTENANCE_START, cb) }
Register a callback in case of a 'maintenance started' message from the server. This is a good time to pause server packets until maintenance ends @param {Function} cb - called on event trigger
onMaintenanceStart
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onMaintenanceEnd (cb) { this.onInfoMessage(WSv2.info.MAINTENANCE_END, cb) }
Register a callback to be notified of a maintenance period ending @param {Function} cb - called on event trigger
onMaintenanceEnd
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
subscribe (channel, payload) { this.send(Object.assign({ event: 'subscribe', channel }, payload)) }
Subscribe to a channel with the given filter payload @param {string} channel - channel payload/data @param {object} payload - optional extra packet data @example const ws = new WSv2() ws.on('open', () => { ws.onTrades({ symbol: 'tBTCUSD' }, (trades) => { // ... }) ws.subscribe('trades', { symbol: 'tBTCUSD' }) }) await ws.open()
subscribe
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async subscribeTicker (symbol) { return this.managedSubscribe('ticker', symbol, { symbol }) }
Subscribe to a ticker data channel @param {string} symbol - symbol of ticker @returns {boolean} subscribed @see WSv2#managedSubscribe @example await ws.subscribeTicker('tBTCUSD')
subscribeTicker
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async subscribeTrades (symbol) { return this.managedSubscribe('trades', symbol, { symbol }) }
Subscribe to a trades data channel @param {string} symbol - symbol of market to monitor @returns {boolean} subscribed @see WSv2#managedSubscribe @example await ws.subscribeTrades('tBTCUSD')
subscribeTrades
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async subscribeOrderBook (symbol, prec = 'P0', len = '25') { return this.managedSubscribe('book', symbol, { symbol, len, prec }) }
Subscribe to an order book data channel @param {string} symbol - symbol of order book @param {string} prec - P0, P1, P2, or P3 (default P0) @param {string} len - 25 or 100 (default 25) @returns {boolean} subscribed @see WSv2#managedSubscribe @example await ws.subscribeOrderBook('tBTCUSD', 'R0', '25')
subscribeOrderBook
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async subscribeCandles (key) { return this.managedSubscribe('candles', key, { key }) }
Subscribe to a candle data channel @param {string} key - 'trade:5m:tBTCUSD' @returns {boolean} subscribed @see WSv2#managedSubscribe @example await ws.subscribeCandles('trade:5m:tBTCUSD')
subscribeCandles
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async subscribeStatus (key) { return this.managedSubscribe('status', key, { key }) }
Subscribe to a status data channel @param {string} key - i.e. 'liq:global' @returns {boolean} subscribed @see WSv2#managedSubscribe @example await ws.subscribeStatus('liq:global')
subscribeStatus
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
unsubscribe (chanId) { this.send({ event: 'unsubscribe', chanId: +chanId }) }
Unsubscribe from a channel by ID @param {number} chanId - ID of channel to unsubscribe from @example const id = ws.getDataChannelId('ticker', { symbol: 'tBTCUSD' }) if (id) { ws.unsubscribe(id) }
unsubscribe
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async unsubscribeTicker (symbol) { return this.managedUnsubscribe('ticker', symbol) }
Unsubscribe from a ticker data channel @param {string} symbol - symbol of ticker @returns {boolean} unsubscribed @see WSv2#subscribeTicker @example await ws.unsubscribeTicker('tBTCUSD')
unsubscribeTicker
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async unsubscribeTrades (symbol) { return this.managedUnsubscribe('trades', symbol) }
Unsubscribe from a trades data channel @param {string} symbol - symbol of market to unsubscribe from @returns {boolean} unsubscribed @see WSv2#subscribeTrades @example await ws.unsubcribeTrades('tBTCUSD')
unsubscribeTrades
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async unsubscribeOrderBook (symbol) { return this.managedUnsubscribe('book', symbol) }
Unsubscribe from an order book data channel @param {string} symbol - symbol of order book @returns {boolean} unsubscribed @see WSv2#subscribeOrderBook @example await ws.unsubcribeOrderBook('tBTCUSD')
unsubscribeOrderBook
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async unsubscribeCandles (symbol, frame) { return this.managedUnsubscribe('candles', `trade:${frame}:${symbol}`) }
@param {string} symbol - symbol of candles @param {string} frame - time frame @returns {boolean} unsubscribed @see WSv2#subscribeCandles @example await ws.unsubscribeCandles('tBTCUSD', '1m')
unsubscribeCandles
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async unsubscribeStatus (key) { return this.managedUnsubscribe('status', key) }
@param {string} key - key that was used in initial {@link WSv2#subscribeStatus} call @returns {boolean} unsubscribed @see WSv2#subscribeStatus
unsubscribeStatus
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
removeListeners (cbGID) { delete this._listeners[cbGID] }
Remove all listeners by callback group ID @param {string} cbGID - callback group to remove @example await ws.subscribeTrades({ symbol: 'tBTCUSD', cbGID: 42 }) await ws.subscribeTrades({ symbol: 'tLEOUSD', cbGID: 42 }) await ws.subscribeTrades({ symbol: 'tETHUSD', cbGID: 42 }) // ... ws.removeListeners(42)
removeListeners
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
requestCalc (prefixes) { this._sendCalc([0, 'calc', null, prefixes.map(p => [p])]) }
Request a calc operation to be performed on the specified indexes @param {string[]} prefixes - desired prefixes to be calculated
requestCalc
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
_sendCalc (msg) { debug('req calc: %j', msg) this._ws.send(JSON.stringify(msg)) }
Throttled call to ws.send, max 8 op/s @param {Array} msg - message @private
_sendCalc
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
async submitOrderMultiOp (opPayloads) { if (!this._isAuthenticated) { throw new Error('not authenticated') } // TODO: multi-op tracking this.send([0, 'ox_multi', null, opPayloads]) }
Sends the op payloads to the server as an 'ox_multi' command. A promise is returned and resolves immediately if authenticated, as no confirmation is available for this message type. @param {object[]} opPayloads - order operations @returns {Promise} p - rejects if not authenticated
submitOrderMultiOp
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
_flushOrderOps () { this._orderOpTimeout = null const packets = this._orderOpBuffer.map(p => [p[1], p[3]]) this._orderOpBuffer = [] if (packets.length <= 15) { return this.submitOrderMultiOp(packets) } const promises = [] while (packets.length > 0) { const opPackets = packets.splice(0, Math.min(packets.length, 15)) promises.push(this.submitOrderMultiOp(opPackets)) } return Promise.all(promises) }
Splits the op buffer into packets of max 15 ops each, and sends them down the wire. @returns {Promise} p - resolves after send @private
_flushOrderOps
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
notifyUI (opts = {}) { const { type, message, level, image, link, sound } = opts if (!_isString(type) || !_isString(message)) { throw new Error(`notified with invalid type/message: ${type}/${message}`) } if (!this._isOpen) { throw new Error('socket not open') } if (!this._isAuthenticated) { throw new Error('socket not authenticated') } this.send([0, 'n', null, { type: UCM_NOTIFICATION_TYPE, info: { type, message, level, image, link, sound } }]) }
Sends a broadcast notification, which will be received by any active UI websocket connections (at bitfinex.com), triggering a desktop notification. In the future our mobile app will also support spawning native push notifications in response to incoming ucm-notify-ui packets. @param {object} opts - options @param {string} [opts.message] - message to display @param {string} [opts.type] - notification type, 'ucm-*' for broadcasts @param {string} [opts.level] - 'info', 'error', or 'success' @param {string} [opts.image] - link to an image to be shown @param {string} [opts.link] - URL the notification should forward too @param {string} [opts.sound] - URL of sound to play @throws an error if given no type or message, or the instance is not open and authenticated
notifyUI
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
_registerListener (eventName, filter, modelClass, cbGID, cb) { if (!cbGID) cbGID = null if (!this._listeners[cbGID]) { this._listeners[cbGID] = { [eventName]: [] } } const listeners = this._listeners[cbGID] if (!listeners[eventName]) { listeners[eventName] = [] } const l = { cb, modelClass, filter } listeners[eventName].push(l) }
Adds a listener to the internal listener set, with an optional grouping for batch unsubscribes (GID) & automatic ws packet matching (filterKey) @param {string} eventName - as received on ws stream @param {object} filter - map of index & value in ws packet @param {object} modelClass - model to use for serialization @param {string} cbGID - listener group ID for mass removal @param {Function} cb - listener @private
_registerListener
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onInfoMessage (code, cb) { if (!this._infoListeners[code]) { this._infoListeners[code] = [] } this._infoListeners[code].push(cb) }
Registers a new callback to be called when a matching info message is received. @param {number} code - from #WSv2.info @param {Function} cb - callback
onInfoMessage
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onMessage ({ cbGID }, cb) { this._registerListener('', null, null, cbGID, cb) }
Register a generic handler to be called with each received message @param {object} opts - options @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback
onMessage
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onCandle ({ key, cbGID }, cb) { this._registerListener('candle', { 0: key }, Candle, cbGID, cb) }
Register a handler to be called with each received candle @param {object} opts - options @param {string} opts.key - candle set key, i.e. trade:30m:tBTCUSD @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-public-candle @see WSv2#subscribeCandles @see WSv2#unsubscribeCandles
onCandle
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onOrderBook ({ symbol, prec, len, cbGID }, cb) { this._registerListener('orderbook', { 0: symbol, 1: prec, 2: len }, OrderBook, cbGID, cb) }
Register a handler to be called with each received candle @param {object} opts - options @param {string} opts.symbol - book symbol @param {string} opts.prec - book precision, i.e. 'R0' @param {string} opts.len - book length, i.e. '25' @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-public-order-books @see WSv2#subscribeOrderBook @see WSv2#unsubscribeOrderBook
onOrderBook
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onOrderBookChecksum ({ symbol, prec, len, cbGID }, cb) { this._registerListener('ob_checksum', { 0: symbol, 1: prec, 2: len }, null, cbGID, cb) }
Register a handler to be called with each received order book checksum @param {object} opts - options @param {string} opts.symbol - book symbol @param {string} opts.prec - book precision, i.e. 'R0' @param {string} opts.len - book length, i.e. '25' @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-public-order-books @see WSv2#subscribeOrderBook @see WSv2#unsubscribeOrderBook
onOrderBookChecksum
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onTrades ({ symbol, pair, cbGID }, cb) { const id = pair || symbol || '' const model = id[0] === 'f' ? FundingTrade : PublicTrade this._registerListener('trades', { 0: id }, model, cbGID, cb) }
Register a handler to be called with each received trade (pair or symbol required) @param {object} opts - options @param {string} [opts.pair] - required if no symbol specified @param {string} [opts.symbol] - required if no pair specified @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-public-trades @see WSv2#subscribeTrades @see WSv2#unsubscribeTrades
onTrades
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onTradeEntry ({ pair, symbol, cbGID }, cb) { const id = pair || symbol || '' this._registerListener('trade-entry', { 0: id }, PublicTrade, cbGID, cb) }
Register a handler to be called on each trade `'te'` event @param {object} opts - options @param {string} [opts.pair] - required if no symbol specified @param {string} [opts.symbol] - required if no pair specified @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-public-trades @see WSv2#subscribeTrades @see WSv2#unsubscribeTrades
onTradeEntry
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onAccountTradeEntry ({ symbol, cbGID }, cb) { this._registerListener('auth-te', { 1: symbol }, Trade, cbGID, cb) }
Register a handler to be called on each personal trade `'te'` event @param {object} opts - options @param {string} [opts.pair] - required if no symbol specified @param {string} [opts.symbol] - required if no pair specified @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-public-trades
onAccountTradeEntry
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onAccountTradeUpdate ({ symbol, cbGID }, cb) { this._registerListener('auth-tu', { 1: symbol }, Trade, cbGID, cb) }
Register a handler to be called on each personal trade `'tu'` event @param {object} opts - options @param {string} [opts.pair] - required if no symbol specified @param {string} [opts.symbol] - required if no pair specified @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-trades
onAccountTradeUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onTicker ({ symbol = '', cbGID } = {}, cb) { const m = symbol[0] === 'f' ? FundingTicker : TradingTicker this._registerListener('ticker', { 0: symbol }, m, cbGID, cb) }
Register a handler to be called on each received ticker @param {object} opts - options @param {string} opts.symbol - symbol for tickers @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-public-ticker @see WSv2#subscribeTicker @see WSv2#unsubscribeTicker
onTicker
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onStatus ({ key = '', cbGID } = {}, cb) { this._registerListener('status', { 0: key }, null, cbGID, cb) }
Register a handler to be called on each message for the desired status feed. @param {object} opts - options @param {string} opts.key - key of feed to listen on @param {string|number} [opts.cbGID] - callback group ID @param {Function} cb - callback @see WSv2#subscribeStatus
onStatus
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onOrderSnapshot ({ symbol, id, cid, gid, cbGID }, cb) { this._registerListener('os', { 0: id, 1: gid, 2: cid, 3: symbol }, Order, cbGID, cb) }
Register a handler to be called on each full order snapshot (sent on auth) @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {number} [opts.id] - order ID to match @param {number} [opts.cid] - order client ID to match @param {number} [opts.gid] - order group ID to match @param {string|number} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-orders @see WSv2#auth
onOrderSnapshot
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onOrderUpdate ({ symbol, id, cid, gid, cbGID }, cb) { this._registerListener('ou', { 0: id, 1: gid, 2: cid, 3: symbol }, Order, cbGID, cb) }
Register a handler to be called on each order update packet @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {number} [opts.id] - order ID to match @param {number} [opts.cid] - order client ID to match @param {number} [opts.gid] - order group ID to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-orders @see WSv2#updateOrder
onOrderUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onOrderClose ({ symbol, id, cid, gid, cbGID }, cb) { this._registerListener('oc', { 0: id, 1: gid, 2: cid, 3: symbol }, Order, cbGID, cb) }
Register a handler to be called on each order close packet @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {number} [opts.id] - order ID to match @param {number} [opts.cid] - order client ID to match @param {number} [opts.gid] - order group ID to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-orders @see WSv2#cancelOrder
onOrderClose
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onPositionSnapshot ({ symbol, cbGID }, cb) { this._registerListener('ps', { 0: symbol }, Position, cbGID, cb) }
Register a handler to be called on each position snapshot (sent on auth) @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-position @see WSv2#auth
onPositionSnapshot
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onPositionNew ({ symbol, cbGID }, cb) { this._registerListener('pn', { 0: symbol }, Position, cbGID, cb) }
Register a handler to be called when a position is opened @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-position
onPositionNew
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onPositionUpdate ({ symbol, cbGID }, cb) { this._registerListener('pu', { 0: symbol }, Position, cbGID, cb) }
Register a handler to be called when a position is updated @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-position
onPositionUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onPositionClose ({ symbol, cbGID }, cb) { this._registerListener('pc', { 0: symbol }, Position, cbGID, cb) }
Register a handler to be called when a position is closed @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-position
onPositionClose
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingOfferSnapshot ({ symbol, cbGID }, cb) { this._registerListener('fos', { 1: symbol }, FundingOffer, cbGID, cb) }
Register a handler to be called on each fundign offer snapshot (sent on auth) @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-offers @see WSv2#auth
onFundingOfferSnapshot
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingOfferNew ({ symbol, cbGID }, cb) { this._registerListener('fon', { 1: symbol }, FundingOffer, cbGID, cb) }
Register a handler to be called when a funding offer is created @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-offers
onFundingOfferNew
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingOfferUpdate ({ symbol, cbGID }, cb) { this._registerListener('fou', { 1: symbol }, FundingOffer, cbGID, cb) }
Register a handler to be called when a funding offer is updated @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-offers
onFundingOfferUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingOfferClose ({ symbol, cbGID }, cb) { this._registerListener('foc', { 1: symbol }, FundingOffer, cbGID, cb) }
Register a handler to be called when a funding offer is closed @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-offers
onFundingOfferClose
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingCreditSnapshot ({ symbol, cbGID }, cb) { this._registerListener('fcs', { 1: symbol }, FundingCredit, cbGID, cb) }
Register a handler to be called on each funding credit snapshot (sent on auth) @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-credits @see WSv2#auth
onFundingCreditSnapshot
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingCreditNew ({ symbol, cbGID }, cb) { this._registerListener('fcn', { 1: symbol }, FundingCredit, cbGID, cb) }
Register a handler to be called when a funding credit is created @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-credits
onFundingCreditNew
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingCreditUpdate ({ symbol, cbGID }, cb) { this._registerListener('fcu', { 1: symbol }, FundingCredit, cbGID, cb) }
Register a handler to be called when a funding credit is updated @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-credits
onFundingCreditUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingCreditClose ({ symbol, cbGID }, cb) { this._registerListener('fcc', { 1: symbol }, FundingCredit, cbGID, cb) }
Register a handler to be called when a funding credit is closed @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-credits
onFundingCreditClose
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingLoanSnapshot ({ symbol, cbGID }, cb) { this._registerListener('fls', { 1: symbol }, FundingLoan, cbGID, cb) }
Register a handler to be called on each funding loan snapshot (sent on auth) @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-loans @see WSv2#auth
onFundingLoanSnapshot
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingLoanNew ({ symbol, cbGID }, cb) { this._registerListener('fln', { 1: symbol }, FundingLoan, cbGID, cb) }
Register a handler to be called when a funding loan is created @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-loans
onFundingLoanNew
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingLoanUpdate ({ symbol, cbGID }, cb) { this._registerListener('flu', { 1: symbol }, FundingLoan, cbGID, cb) }
Register a handler to be called when a funding loan is updated @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-loans
onFundingLoanUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingLoanClose ({ symbol, cbGID }, cb) { this._registerListener('flc', { 1: symbol }, FundingLoan, cbGID, cb) }
Register a handler to be called when a funding loan is closed @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-loans
onFundingLoanClose
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onWalletSnapshot ({ cbGID }, cb) { this._registerListener('ws', null, Wallet, cbGID, cb) }
Register a handler to be called on each wallet snapshot (sent on auth) @param {object} opts - options @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-wallets
onWalletSnapshot
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onWalletUpdate ({ cbGID }, cb) { this._registerListener('wu', null, Wallet, cbGID, cb) }
Register a handler to be called on each wallet update @param {object} opts - options @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-wallets
onWalletUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onBalanceInfoUpdate ({ cbGID }, cb) { this._registerListener('bu', null, BalanceInfo, cbGID, cb) }
Register a handler to be called on each balance info update @param {object} opts - options @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-balance
onBalanceInfoUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onMarginInfoUpdate ({ cbGID }, cb) { this._registerListener('miu', null, MarginInfo, cbGID, cb) }
Register a handler to be called on each margin info update @param {object} opts - options @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-margin
onMarginInfoUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingInfoUpdate ({ cbGID }, cb) { this._registerListener('fiu', null, FundingInfo, cbGID, cb) }
Register a handler to be called on each funding info update @param {object} opts - options @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-funding
onFundingInfoUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingTradeEntry ({ symbol, cbGID }, cb) { this._registerListener('fte', { 0: symbol }, FundingTrade, cbGID, cb) }
Register a handler to be called on each funding trade `'te'` event @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-funding-trades
onFundingTradeEntry
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onFundingTradeUpdate ({ symbol, cbGID }, cb) { this._registerListener('ftu', { 0: symbol }, FundingTrade, cbGID, cb) }
Register a handler to be called on each funding trade `'tu'` event @param {object} opts - options @param {string} [opts.symbol] - symbol to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-funding-trades
onFundingTradeUpdate
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
onNotification ({ type, cbGID }, cb) { this._registerListener('n', { 1: type }, Notification, cbGID, cb) }
Register a handler to be called on each notification @param {object} opts - options @param {string} [opts.type] - type to match @param {string} [opts.cbGID] - callback group id @param {Function} cb - callback @see https://docs.bitfinex.com/v2/reference#ws-auth-notifications
onNotification
javascript
bitfinexcom/bitfinex-api-node
lib/transports/ws2.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/transports/ws2.js
MIT
setSigFig = (number = 0, maxSigs = DEFAULT_SIG_FIGS) => { const n = +(number) if (!isFinite(n)) { return number } const value = n.toPrecision(maxSigs) return /e/.test(value) ? new Big(value).toString() : value }
Smartly set the precision (decimal) on a value based off of the significant digit maximum. For example, calling with 3.34 when the max sig figs allowed is 5 would return '3.3400', the representation number of decimals IF they weren't zeros. @param {number} number - number to manipulate @param {number} [maxSigs] - default 5 @returns {string} str
setSigFig
javascript
bitfinexcom/bitfinex-api-node
lib/util/precision.js
https://github.com/bitfinexcom/bitfinex-api-node/blob/master/lib/util/precision.js
MIT
function processResponse() { // attempt to parse the json now if(util.isJsonResponse(res)) { if(body) { try { body = JSON.parse(body); } catch (e) { return resolver.reject(errors.invalidJson()); } } } // salesforce returned an ok of some sort if(res.statusCode >= 200 && res.statusCode <= 204) { // attach the id back to the sobject on insert if(sobject) { if(sobject._reset) { sobject._reset(); } if(body && _.isObject(body) && body.id) { sobject._fields.id = body.id; } } return resolver.resolve(body); } // error handling var e; // error: no body if(!body) { e = new Error('Salesforce returned no body and status code ' + res.statusCode); // error: array body } else if (_.isArray(body) && body.length > 0) { e = new Error(body[0].message); e.errorCode = body[0].errorCode; e.body = body; // error: string body } else if(_.isString(body)) { e = new Error(body); e.errorCode = body; e.body = body; } else if (_.isObject(body) && findValueForKeyInObject(body, 'message', 0, 5) && findValueForKeyInObject(body, 'errorCode', 0, 5)) { e = new Error(findValueForKeyInObject(body, 'message')); e.body = findValueForKeyInObject(body, 'message'); e.errorCode = findValueForKeyInObject(body, 'errorCode'); } else { e = new Error('Salesforce returned an unrecognized error ' + res.statusCode); e.body = body; } e.statusCode = res.statusCode; // confirm auto-refresh support if(e.errorCode && (e.errorCode === 'INVALID_SESSION_ID' || e.errorCode === 'Bad_OAuth_Token') && self.autoRefresh === true && (opts.oauth.refresh_token || (self.getUsername() && self.getPassword())) && !opts._retryCount) { // attempt the autorefresh Connection.prototype.autoRefreshToken.call(self, opts, function(err2, res2) { if(err2) { return resolver.reject(err2); } else { opts._retryCount = 1; opts._resolver = resolver; return Connection.prototype._apiRequest.call(self, opts); } }); } else { return resolver.reject(e); } }
options: - sobject - uri - callback - oauth - multipart - method - encoding - body - qs - headers
processResponse
javascript
kevinohara80/nforce
index.js
https://github.com/kevinohara80/nforce/blob/master/index.js
MIT
authenticate = (username, password, securityToken) => new Promise((resolve, reject) => { // Authenticate using multi user mode org.authenticate( { username: username, password: password, securityToken: securityToken }, (error, response) => { if (!error) { resolve(response) } else { reject(error) } } ) })
Authenticate to login a user in the org @param {string} username - e.g. [email protected] @param {string} password @param {string} securityToken - Your user's security token. This can be reset in the org if needed.
authenticate
javascript
kevinohara80/nforce
examples/async-await-cruds.js
https://github.com/kevinohara80/nforce/blob/master/examples/async-await-cruds.js
MIT
query = (queryString, oauth) => new Promise((resolve, reject) => { org.query( { query: queryString, oauth: oauth }, (error, response) => { if (!error) { resolve(response.records) } else { reject(error) } } ) })
Perform a SOQL Query @param {string} queryString - SOQL query @param {object} oauth - OAuth string received from successful authentication
query
javascript
kevinohara80/nforce
examples/async-await-cruds.js
https://github.com/kevinohara80/nforce/blob/master/examples/async-await-cruds.js
MIT
createRecord = (sobjectName, recordData, oauth) => { const sobj = nforce.createSObject(sobjectName, recordData) return new Promise((resolve, reject) => { org.insert( { sobject: sobj, oauth: oauth }, (error, response) => { if (!error) { resolve(response) } else { reject(error) } } ) }) }
Create a record @param {string} sobjectName - Name of the SObject (e.g. Account) @param {object} recordData - Key value pair of Field Names and Field Values @param {object} oauth - OAuth string received from successful authentication
createRecord
javascript
kevinohara80/nforce
examples/async-await-cruds.js
https://github.com/kevinohara80/nforce/blob/master/examples/async-await-cruds.js
MIT
updateRecord = (sobjectName, recordDataWithID, oauth) => { const sobj = nforce.createSObject(sobjectName, recordDataWithID) return new Promise((resolve, reject) => { org.update( { sobject: sobj, oauth: oauth }, (error, response) => { if (!error) { resolve(response) } else { reject(error) } } ) }) }
Update a record @param {string} sobjectName - Name of the SObject (e.g. Account) @param {object} recordDataWithID - Key value pair of Field Names and Field Values @param {object} oauth - OAuth string received from successful authentication
updateRecord
javascript
kevinohara80/nforce
examples/async-await-cruds.js
https://github.com/kevinohara80/nforce/blob/master/examples/async-await-cruds.js
MIT
upsertRecord = (sobjectName, recordDataWithID, oauth) => { const sobj = nforce.createSObject(sobjectName) const recordId = !!recordDataWithID.id ? recordDataWithID.id : '' sobj.setExternalId('Id', recordId) Object.entries(recordDataWithID).map(([key, value]) => { sobj.set(key, value) }) return new Promise((resolve, reject) => { org.upsert( { sobject: sobj, oauth: oauth, requestOpts: { method: !recordId ? 'POST' : 'PATCH' } }, (error, response) => { if (!error) { if(!recordId) { resolve(response) } else { resolve(recordDataWithID) } } else { reject(error) } } ) }) }
Upsert a record @param {string} sobjectName - Name of the SObject (e.g. Account) @param {object} recordDataWithID - Key value pair of Field Names and Field Values @param {object} oauth - OAuth string received from successful authentication
upsertRecord
javascript
kevinohara80/nforce
examples/async-await-cruds.js
https://github.com/kevinohara80/nforce/blob/master/examples/async-await-cruds.js
MIT
deleteRecord = (sobjectName, recordDataWithID, oauth) => { const sobj = nforce.createSObject(sobjectName, recordDataWithID) return new Promise((resolve, reject) => { org.delete( { sobject: sobj, oauth: oauth }, (error, response) => { if (!error) { resolve(response) } else { reject(error) } } ) }) }
Delete a record @param {string} sobjectName - Name of the SObject (e.g. Account) @param {object} recordDataWithID - Key value pair of Field Names and Field Values @param {object} oauth - OAuth string received from successful authentication
deleteRecord
javascript
kevinohara80/nforce
examples/async-await-cruds.js
https://github.com/kevinohara80/nforce/blob/master/examples/async-await-cruds.js
MIT
Usage = (props) => { return <HelloWorld /> }
!!!!!!!!!!!!!!!!!!!!!!!!!!! DO NOT DELETE OR CHANGE THIS. This is how you would use your above component and the output of this code is displayed on the browser
Usage
javascript
tyroprogrammer/learn-react-app
src/exercise/solution/01-HelloWorld-solution.js
https://github.com/tyroprogrammer/learn-react-app/blob/master/src/exercise/solution/01-HelloWorld-solution.js
MIT
install(app) { app.component('Swiper', Swiper); app.component('SwiperSlide', SwiperSlide); }
@file vue-awesome-swiper @author Surmon <https://github.com/surmon-china>
install
javascript
surmon-china/vue-awesome-swiper
index.js
https://github.com/surmon-china/vue-awesome-swiper/blob/master/index.js
MIT
render = async (fullMarkdown, extraOptions = {}) => { const { yamlOptions, markdown: contentOnlyMarkdown } = parseYamlFrontMatter(fullMarkdown); const options = Object.assign(getSlideOptions(yamlOptions), extraOptions); const { title } = options; const themeUrl = getThemeUrl(options.theme, options.assetsDir, options.base); const highlightThemeUrl = getHighlightThemeUrl(options.highlightTheme); const scriptPaths = getScriptPaths(options.scripts, options.assetsDir, options.base); const cssPaths = getCssPaths(options.css, options.assetsDir, options.base); const revealOptions = Object.assign({}, getRevealOptions(options.revealOptions), yamlOptions.revealOptions); const slidifyOptions = _.pick(options, Object.keys(slidifyAttributeNames)); let slidifyAttributes = []; for (const [key, value] of Object.entries(slidifyOptions)) { const escaped_value = value.replace(/\n/g, '\\n').replace(/\r/g, '\\r'); slidifyAttributes.push(`${slidifyAttributeNames[key]}="${escaped_value}"`); } const preprocessorFn = await getPreprocessor(options.preprocessor); const processedMarkdown = await preprocessorFn(contentOnlyMarkdown, options); const revealOptionsStr = JSON.stringify(revealOptions); const mermaidOptionsStr = options.mermaid === false ? undefined : JSON.stringify(options.mermaid); const template = await getTemplate(options.template); const context = Object.assign(options, { title, slidifyAttributes: slidifyAttributes.join(' '), markdown: processedMarkdown, themeUrl, highlightThemeUrl, scriptPaths, cssPaths, revealOptionsStr, mermaidOptionsStr, watch: getWatch() }); const markup = Mustache.render(template, context); return markup; }
Renders the given markdown content into HTML. @param {string} fullMarkdown - The contents of the markdown file, including a possible YAML front matter @param {Object} extraOptions - Additional options (mostly used by tests) @returns {string} The rendered HTML compatible with reveal.js
render
javascript
webpro/reveal-md
lib/render.js
https://github.com/webpro/reveal-md/blob/master/lib/render.js
MIT
replaceArgs = (cmd, shell) => { const replacements = { f: this._getFile(shell), d: this._getFolder(shell), m: this._getMountFolder(shell) } return cmd.replace(/\$([fdm])\b/g, match => `"${replacements[match.slice(1)]}"`) }
Implementing this plugin requires three types of compatibility: 1. Abstracting operating system differences to support Windows and Linux. 2. Abstracting shell differences to support cmd, WSL, and bash, including nested shell calls. 3. Abstracting parameter differences, where cmd uses %VAR% and bash uses $VAR.
replaceArgs
javascript
obgnail/typora_plugin
plugin/commander.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/commander.js
MIT
constructor(plugin, formatBrushString) { this.utils = plugin.utils this.formatBrushObj = this.parseStyleString(formatBrushString) }
This code contains workarounds and hacks to address specific behaviors of Typora. Understanding the intricacies may be challenging. This documentation outlines the implementation logic for future modifications. Core Idea: Simplify the problem by initially focusing on single-line selections. 1. Single-Line Selection Scenarios: Consider the example: `123<span style="color:#FF0000;">abc</span>defg` Four selection possibilities exist: a. No selection. b. Standard selection (e.g., "efg" - anything not covered by c and d). c. Selection within an existing styled span (e.g., "abc"). d. Selection encompassing an entire styled span (e.g., `<span style="color:#FF0000;">abc</span>`). 2. Handling Simple Scenarios (a, b, and c): a. No selection: Insert an empty styled span (`<span style="XXX"></span>`) at the cursor. b. Standard selection: Wrap the selected text (e.g., "efg") with a styled span: `<span style="XXX">efg</span>`. Then, insert it back into the document. c. Selection within a span: Transform the selection into scenario d. For example, "abc" becomes `<span style="color:#FF0000;">abc</span>`. 3. Handling Scenario d (Selecting an Existing Span): a. Deconstruct the example `123<span style="color:#FF0000;">abc</span>defg` into: - `beforeText`: "123" (Text before the span) - `innerText`: "abc" (Text inside the span) - `outerText`: `<span style="color:#FF0000;">abc</span>` (The entire span element) - `styleObject`: A JavaScript object representing the CSS style of the span (e.g., `{ color: '#FF0000' }`) b. Modify the `styleObject` as needed to apply the new styling. c. Reconstruct the `outerText` using the updated `innerText` and `styleObject`. Insert this new `outerText` back into the document. d. Use the `beforeText` and modified `styleObject` to determine the final position of the `innerText`. Move the bookmark (selection) to correctly re-select the `innerText`. e. The above steps are encapsulated in the `setInlineStyle` function. 4. Handling Multi-Line Selections: When the user selects text across multiple lines and potentially multiple tags, the process involves: a. Breaking the multi-line selection into individual lines. b. Applying the `setInlineStyle` function to each line. Implementation details for multi-line handling (`genRanges` function): a. Use `TreeWalker` along with the `range` object's `commonAncestorContainer`, `startContainer`, and `endContainer` to get an array of all selected nodes (`nodeList`). b. Filter out unnecessary text nodes within `<span md-inline="softbreak" class="md-softbreak"> </span>` tags (generated by shift+enter for soft line breaks). c. Split the `nodeList` into lines based on `node.classList.contains("md-softbreak")` (soft breaks) and `!!node.getAttribute("cid")` (hard breaks). Use `range.setStart(startContainer, startOffset)` and `range.setEnd(endContainer, endOffset)` to define the selection range for each line. d. The `startContainer` and `endContainer` will be TEXT_NODEs. Filter out any ELEMENT_NODEs to get an array of lines (`selectLines`). e. `selectLines` is a 2D array where each element is an array of TEXT_NODEs for a single line. The `startContainer` and `endContainer` correspond to the first and last TEXT_NODEs of each line, respectively. f. Special handling is required for the first and last lines, as they might not be fully selected. g. After splitting, you'll have the `startContainer`, `startOffset`, `endContainer`, and `endOffset` for each individual line. 5. Addressing Typora's DOM Manipulation Issues: Typora modifies the paragraph's `innerHTML` after inserting a span, invalidating the previously obtained TEXT_NODEs in the ranges. The solution is: a. The `textContent` of the paragraph remains unchanged after the span insertion. Record the position of the old TEXT_NODEs in the document *before* inserting the span. b. After Typora updates the DOM, use the recorded positions to find the *new* TEXT_NODEs. c. Replace the old TEXT_NODEs with the new TEXT_NODEs in the ranges. d. Now the (updated) TEXT_NODEs are valid. Proceed to call `setInlineStyle`. e. The above process is implemented in `setMultilineStyle`. `recordTEXTPosition` handles the recording, and `renewRange` handles the replacement. 6. Overall Styling Process: The main function `setStyle` orchestrates the entire process, calling `genRanges`, `setMultilineStyle`, and the helper functions as needed.
constructor
javascript
obgnail/typora_plugin
plugin/text_stylize.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/text_stylize.js
MIT
innerSelected = () => { if (line.substring(bookmark.start, bookmark.end + suffix.length).endsWith(suffix)) { const result = beforeText.match(/<span .*?>/g); if (!result) return; const last = result[result.length - 1]; if (last && beforeText.endsWith(last)) { return last } } }
There are four possible user selection scenarios, for example: `123<span style="color:#FF0000;">abc</span>defg` a. No selection. b. Standard selection (e.g., "efg"). c. Selection within an existing styled span (e.g., "abc"): Modify the outer text. d. Selection encompassing an entire styled span (e.g., `<span style="color:#FF0000;">abc</span>`): Modify the inner text.
innerSelected
javascript
obgnail/typora_plugin
plugin/text_stylize.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/text_stylize.js
MIT
_getLatestVersion = async () => { const resp = await this.utils.fetch(url, this.requestOption); return resp.json() }
Force update: skip the check and directly update using the URL.
_getLatestVersion
javascript
obgnail/typora_plugin
plugin/updater.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/updater.js
MIT
initGlobalVars = settings => { // "global" is a general setting, not a plugin setting Object.defineProperty(settings, "global", { enumerable: false }) global.BasePlugin = BasePlugin global.BaseCustomPlugin = BaseCustomPlugin global.LoadPlugins = LoadPlugins global.__plugins__ = null global.__plugin_utils__ = utils global.__plugin_i18n__ = i18n global.__plugin_settings__ = settings }
Initializes global variables. The plugin system exposes the following global variables, but only 3 are actually useful: BasePlugin, BaseCustomPlugin, and LoadPlugins. The remaining variables are exposed by the static class `utils` and should never be referenced by business plugins. Furthermore, `utils` is also an instance property of BasePlugin and BaseCustomPlugin, so `utils` itself doesn't need to be exposed. Since they will never be referenced by business plugins, why are they set as global variables? Answer: For debugging convenience.
initGlobalVars
javascript
obgnail/typora_plugin
plugin/global/core/index.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/index.js
MIT
warn = () => { const incompatible = utils.compareVersion(utils.typoraVersion, "0.9.98") < 0 if (incompatible) { const msg = i18n.t("global", "incompatibilityWarning") utils.notification.show(msg, "warning", 5000) } }
For Typora versions below 0.9.98, a compatibility warning is issued when running the plugin system.
warn
javascript
obgnail/typora_plugin
plugin/global/core/index.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/index.js
MIT
LoadPlugin = async (fixedName, setting, isBasePlugin) => { const path = isBasePlugin ? "./plugin" : "./plugin/custom/plugins" const { plugin } = utils.requireFilePath(path, fixedName) if (!plugin) { return new Error(`There is not ${fixedName} in ${path}`) } const instance = new plugin(fixedName, setting, i18n.bind(fixedName)) const error = await instance.beforeProcess() if (error === utils.stopLoadPluginError) { return } utils.registerStyle(instance.fixedName, instance.style()) const renderArgs = instance.styleTemplate() if (renderArgs) { await utils.styleTemplater.register(instance.fixedName, { ...renderArgs, this: instance }) } utils.insertElement(instance.html()) if (isBasePlugin) { utils.hotkeyHub.register(instance.hotkey()) } instance.init() instance.process() instance.afterProcess() return instance }
Cleanup, generally used for memory reclamation, used infrequently.
LoadPlugin
javascript
obgnail/typora_plugin
plugin/global/core/plugin.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/plugin.js
MIT
constructor(utils, i18n) { this.utils = utils; this.i18n = i18n; this.diagramModeFlag = "custom_diagram"; // can be any value, just a flag this.panel = `<div class="md-diagram-panel md-fences-adv-panel"><div class="md-diagram-panel-header"></div><div class="md-diagram-panel-preview"></div><div class="md-diagram-panel-error"></div></div>`; this.exitInteractiveStrategies = ["click_exit_button"]; this.parsers = new Map(); // {lang: parser} this.langMapping = new Map(); // {lang: mappingLang} // this.pending = new Set(); // cid // this.timeout = 300; }
Dynamically register and unregister new code block diagram.
constructor
javascript
obgnail/typora_plugin
plugin/global/core/utils/diagramParser.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
MIT
after = mode => { if (!mode) return mode const isObj = typeof mode === "object" const originLang = isObj ? mode.name : mode const mappingLang = this.langMapping.get(originLang) if (!mappingLang) { return mode } if (!isObj) { return mappingLang } mode.name = mappingLang return mode }
If the fenceEnhance plugin is disabled and EXIT_INTERACTIVE_MODE === click_exit_button, then force all charts to disable interactive mode.
after
javascript
obgnail/typora_plugin
plugin/global/core/utils/diagramParser.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
MIT
afterExport = () => { setTimeout(() => { for (const lang of this.parsers.keys()) { this.refreshAllLangFence(lang) } }, 300) }
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
afterExport
javascript
obgnail/typora_plugin
plugin/global/core/utils/diagramParser.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
MIT
constructor(utils) { this.utils = utils this.htmlHelpers = new Map() this.nativeHelpers = new Map() this.isAsync = undefined }
Dynamically register additional actions on export.
constructor
javascript
obgnail/typora_plugin
plugin/global/core/utils/exportHelper.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/exportHelper.js
MIT
async function walk(dir) { const files = await readdir(dir) const promises = files.map(async file => { const path = Path.join(dir, file) const stats = await stat(path) if (stats.isFile()) { if (fileFilter(path, stats)) { const params = await paramsBuilder(path, file, dir, stats) await callback(params) } } else if (stats.isDirectory()) { if (dirFilter(file)) { await walk(path) } } }) await Promise.all(promises) }
@param {boolean} shouldSave - Whether to save the content. @param {string} contentType - The content type (e.g., 'markdown', 'html'). @param {boolean} skipSetContent - Whether to skip setting the content. @param {any} saveContext - Contextual information for saving (optional). @returns {string} - The content of the editor.
walk
javascript
obgnail/typora_plugin
plugin/global/core/utils/index.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
MIT
imageReplacement = (_, alt, src) => { if (!this.isNetworkImage(src) && !this.isSpecialImage(src)) { src = PATH.resolve(dir || this.getCurrentDirPath(), src); } return `<img alt="${alt}" src="${src}">` }
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
imageReplacement
javascript
obgnail/typora_plugin
plugin/global/core/utils/index.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
MIT
constructor(utils) { this.utils = utils }
Handles migration operations during the upgrade process.
constructor
javascript
obgnail/typora_plugin
plugin/global/core/utils/migrate.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/migrate.js
MIT
constructor(utils) { this.utils = utils; this.recorders = new Map(); // map[name]recorder }
Dynamically register and unregister element state recorders (only effective when the window_tab plugin is enabled). Functionality: Record the state of elements before the user switches tabs, and restore the state of the elements when the user switches back. For example: plugin `collapse_paragraph`: It is necessary to record which chapters are folded before the user switches tabs, and then automatically fold the chapters back after the user switches back to maintain consistency.
constructor
javascript
obgnail/typora_plugin
plugin/global/core/utils/stateRecorder.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/stateRecorder.js
MIT
constructor(utils) { this.utils = utils; this.parsers = new Map(); this.defaultHeight = "230px"; this.defaultBackgroundColor = "#F8F8F8"; this.regexp = /^\/\/{height:"(?<height>.*?)",width:"(?<width>.*?)"}/; }
Dynamically register and unregister third-party code block diagram (derived from DiagramParser).
constructor
javascript
obgnail/typora_plugin
plugin/global/core/utils/thirdPartyDiagramParser.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/thirdPartyDiagramParser.js
MIT
getLifeCycleFn = (fnName) => () => { for (const parser of this.parsers.values()) { if (!parser[fnName]) continue parser.instanceMap.forEach((instance, cid) => { const preview = this.utils.entities.querySelectorInWrite(`.md-fences[cid=${cid}] .md-diagram-panel-preview`) if (preview) { parser[fnName](preview, instance) } }) } }
Since JS doesn't support interfaces, interface functions are passed as parameters. @param {string} lang: Language. @param {string} mappingLang: Language to map to. @param {boolean} destroyWhenUpdate: Whether to clear the HTML in the preview before updating. @param {boolean} interactiveMode: When in interactive mode, code blocks will not automatically expand. @param {string} checkSelector: Selector to check if the target Element exists under the current fence. @param {string|function($pre):string} wrapElement: If the target Element does not exist, create it. @param {function(): Promise<null>} lazyLoadFunc: Lazy load third-party resources. @param {function(cid, content, $pre): Promise} setStyleFunc: Set styles. @param {function(cid, content, $pre): Promise} beforeRenderFunc: Execute before rendering. @param {function($wrap, string, meta): instance} createFunc: Create a diagram instance, passing in the target Element and the content of the fence. @param {function($wrap, string, instance, meta): instance} updateFunc: Update the diagram instance when the content is updated. @param {function(Object): null} destroyFunc: Destroy the diagram instance, passing in the diagram instance. @param {function(Element, instance): null} beforeExportToNative: Preparation operations before Pandoc export (e.g., adjusting diagram size, color, etc.). @param {function(Element, instance): null} beforeExportToHTML: Preparation operations before HTML export (e.g., adjusting diagram size, color, etc.). @param {function(): string} extraStyleGetter: Get extra CSS for export. @param {function(): string} versionGetter: Get the version.
getLifeCycleFn
javascript
obgnail/typora_plugin
plugin/global/core/utils/thirdPartyDiagramParser.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/thirdPartyDiagramParser.js
MIT
translateFieldBaseProps = (field, pluginI18N) => { baseProps.forEach(prop => { const propVal = field[prop] if (propVal != null) { const commonVal = commonI18N[prop][propVal] const pluginVal = pluginI18N[propVal] field[prop] = commonVal || pluginVal } }) }
Will NOT modify the schemas structure, just i18n
translateFieldBaseProps
javascript
obgnail/typora_plugin
plugin/preferences/index.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
MIT
uninstall = async () => { const { FsExtra } = this.utils.Package const remove = '<script src="./plugin/index.js" defer="defer"></script>' const windowHTML = this.utils.joinPath("./window.html") const pluginFolder = this.utils.joinPath("./plugin") try { const content = await FsExtra.readFile(windowHTML, "utf-8") const newContent = content.replace(remove, "") await FsExtra.writeFile(windowHTML, newContent) await FsExtra.remove(pluginFolder) } catch (e) { alert(e.toString()) return } const message = this.i18n._t("global", "success.uninstall") const confirm = this.i18n._t("global", "confirm") const op = { type: "info", title: "typora plugin", message, buttons: [confirm] } await this.utils.showMessageBox(op) this.utils.restartTypora(false) }
Callback functions for type="action" settings in schema
uninstall
javascript
obgnail/typora_plugin
plugin/preferences/index.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
MIT
_incompatibleSwitch = (field, settings, tooltip = this.i18n._t("settings", "$tooltip.lowVersion")) => { field.disabled = true field.tooltip = tooltip settings[field.key] = false }
PreProcessors for specific settings in schema
_incompatibleSwitch
javascript
obgnail/typora_plugin
plugin/preferences/index.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
MIT
constructor() { const TYPE = { OR: "OR", AND: "AND", NOT: "NOT", PAREN_OPEN: "PAREN_OPEN", PAREN_CLOSE: "PAREN_CLOSE", KEYWORD: "KEYWORD", PHRASE: "PHRASE", REGEXP: "REGEXP", QUALIFIER: "QUALIFIER", } this.TYPE = TYPE const { OR, AND, NOT, QUALIFIER, PAREN_OPEN, PAREN_CLOSE } = TYPE this.INVALID_POSITION = { FIRST: new Set([OR, AND, PAREN_CLOSE]), LAST: new Set([OR, AND, NOT, PAREN_OPEN, QUALIFIER]), FOLLOW: { [OR]: new Set([OR, AND, PAREN_CLOSE]), [AND]: new Set([OR, AND, PAREN_CLOSE]), [NOT]: new Set([OR, AND, NOT, PAREN_CLOSE]), [PAREN_OPEN]: new Set([OR, AND, PAREN_CLOSE]), [QUALIFIER]: new Set([OR, AND, NOT, PAREN_CLOSE, QUALIFIER]), }, AND: { PREV: new Set([OR, AND, NOT, PAREN_OPEN, QUALIFIER]), NEXT: new Set([OR, AND, NOT, PAREN_CLOSE]), }, } this.setQualifier() }
grammar: <query> ::= <expression> <expression> ::= <term> ( <or> <term> )* <term> ::= <factor> ( <conjunction> <factor> )* <factor> ::= <qualifier>? <match> <qualifier> ::= <scope> <operator> <match> ::= <keyword> | '"'<keyword>'"' | '/'<regexp>'/' | '('<expression>')' <conjunction> ::= <and> | <not> <and> ::= 'AND' | ' ' <or> ::= 'OR' | '|' <not> ::= 'NOT' | '-' <keyword> ::= [^\\s"()|]+ <regexp> ::= [^/]+ <operator> ::= ':' | '=' | '>=' | '<=' | '>' | '<' <scope> ::= 'default' | 'file' | 'path' | 'ext' | 'content' | 'size' | 'time'
constructor
javascript
obgnail/typora_plugin
plugin/search_multi/parser.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/parser.js
MIT
constructor(plugin) { this.MIXIN = QualifierMixin this.config = plugin.config this.utils = plugin.utils this.i18n = plugin.i18n this.parser = new Parser() this.qualifiers = new Map() }
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly) 1. Parse: Parses the input to generate an Abstract Syntax Tree (AST) 2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01') 3. Validate: Validates the AST for correctness 4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult` 5. Query: Retrieves file data, resulting in `queryResult` 6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5) A qualifier has the following attributes: {string} scope: The query scope {string} name: A descriptive name for explanation purposes {string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none` {boolean} is_meta: Indicates if the qualifier scope is a metadata property {boolean} need_read_file: Determines if the qualifier needs to read file content {number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex {function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop` {function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp` {function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp` {function} query: Retrieves data from source and obtain `queryResult` {function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare` {function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default {function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
constructor
javascript
obgnail/typora_plugin
plugin/search_multi/searcher.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
MIT
optimize(ast) { if (!ast) return const { OR, AND } = this.parser.TYPE const setCost = node => { if (!node) return setCost(node.left) setCost(node.right) const rootCost = node.cost || 1 const leftCost = (node.left && node.left.cost) || 1 const rightCost = (node.right && node.right.cost) || 1 node.cost = Math.max(rootCost, leftCost, rightCost) } const getDataNodes = (cur, root, dataNodes = []) => { if (cur.type === root.type) { if (cur.right) { getDataNodes(cur.right, root, dataNodes) } if (cur.left) { getDataNodes(cur.left, root, dataNodes) } } else { dataNodes.push(cur) } return dataNodes } const rebuild = node => { if (!node) return if (node.type === OR || node.type === AND) { const dataNodes = getDataNodes(node, node) if (dataNodes.length > 1) { dataNodes.sort((a, b) => a.cost - b.cost) let newNode = dataNodes.shift() while (dataNodes.length) { const right = dataNodes.shift() newNode = { type: node.type, left: newNode, right: right, cost: right.cost } } node.left = newNode.left node.right = newNode.right node.cost = newNode.cost } } rebuild(node.right) rebuild(node.left) } setCost(ast) rebuild(ast) return ast }
Process OR/AND nodes by: 1. Gathering data child nodes into `dataNodes` 2. Sorting `dataNodes` by `cost` 3. Rebuilding the subtree based on `dataNodes` to favor low-cost operations
optimize
javascript
obgnail/typora_plugin
plugin/search_multi/searcher.js
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
MIT
function setRoomMode(room) { if(room){ SystemPrompt.select(settings.system_prompt_preset_room); is_room = true; $("#option_select_chat").css("display", "none"); }else{ SystemPrompt.select(settings.system_prompt_preset_chat); is_room = false; $("#option_select_chat").css("display", "block"); $("#select_chat").css("display", "block"); } // Needed since we need to update the winNotes (Notes on chat or room, switcing whether saveChat() or saveChatRoom() is used) // getSettings(); if(!is_room) winNotes = new Notes({ root: document.getElementById("shadow_notes_popup"), save: saveChat.bind(this) }); else winNotes = new Notes({ root: document.getElementById("shadow_notes_popup"), save: saveChatRoom.bind(this) }); }
Function to change the context/mode from/to "room" or "character", given parameter value. This function does not affect the character/room list, which should be handled separately. Will update the is_room variable. @param {*} room Switch to "room" mode if true
setRoomMode
javascript
TavernAI/TavernAI
public/script.js
https://github.com/TavernAI/TavernAI/blob/master/public/script.js
MIT
function setPromtString(){ mesSendString = ''; mesExmString = ''; for(let j = 0; j < count_exm_add; j++){ mesExmString+=mesExamplesArray[j]; } for(let j = 0; j < mesSend.length; j++){ mesSendString+=mesSend[j]['mes']; if(mesSend[j]['image_for_recognition'] !== undefined){ imageRecognitionBudgetTokens += 85; } if(mesSend[j]['system_prompt'] !== undefined){ if(mesSend[j]['system_prompt'].length > 0) mesSendString+=mesSend[j]['system_prompt']+'\n'; } if(mesSend[j]['jailbreak_prompt'] !== undefined){ if(mesSend[j]['jailbreak_prompt'].length > 0) mesSendString+=mesSend[j]['jailbreak_prompt']+'\n'; } if((type === 'force_name2' || isNeedToAddName2AfterLastMessage) && j === mesSend.length-1){ mesSendString+= name2+': '; } } }
Base replace*** if(mesExamples !== undefined){ if(mesExamples.length > 0){ if(is_pyg){ mesExamples = mesExamples.replace(/{{user}}:\s/gi, 'You: '); mesExamples = mesExamples.replace(/<USER>:\s/gi, 'You: '); } mesExamples = mesExamples.replace(/You:\s/gi, name1+": "); mesExamples = mesExamples.replace(/{{user}}/gi, name1); mesExamples = mesExamples.replace(/{{char}}/gi, name2); mesExamples = mesExamples.replace(/<USER>/gi, name1); mesExamples = mesExamples.replace(/<BOT>/gi, name2); //mesExamples = mesExamples.replaceAll('<START>', '[An example of how '+name2+' responds]'); let blocks = mesExamples.split(/<START>/gi); mesExamplesArray = blocks.slice(1).map(block => `<START>\n${block.trim()}\n`); } } if(charDescription !== undefined){ if(charDescription.length > 0){ charDescription = charDescription.replace(/{{user}}/gi, name1); charDescription = charDescription.replace(/{{char}}/gi, name2); charDescription = charDescription.replace(/<USER>/gi, name1); charDescription = charDescription.replace(/<BOT>/gi, name2); } } if(charPersonality !== undefined){ if(charPersonality.length > 0){ charPersonality = charPersonality.replace(/{{user}}/gi, name1); charPersonality = charPersonality.replace(/{{char}}/gi, name2); charPersonality = charPersonality.replace(/<USER>/gi, name1); charPersonality = charPersonality.replace(/<BOT>/gi, name2); } } if(Scenario !== undefined){ if(Scenario.length > 0){ Scenario = Scenario.replace(/{{user}}/gi, name1); Scenario = Scenario.replace(/{{char}}/gi, name2); Scenario = Scenario.replace(/<USER>/gi, name1); Scenario = Scenario.replace(/<BOT>/gi, name2); } } if(is_pyg){ if(charDescription.length > 0){ storyString = name2+"'s Persona: "+charDescription+"\n"; } if(charPersonality.length > 0){ storyString+= 'Personality: '+charPersonality+'\n'; } if(Scenario.length > 0){ storyString+= 'Scenario: '+Scenario+'\n'; } }else{ if(charDescription !== undefined){ if(charPersonality.length > 0){ charPersonality = name2+"'s personality: "+charPersonality;//"["+name2+"'s personality: "+charPersonality+"]"; } } if(charDescription !== undefined){ if($.trim(charDescription).length > 0){ if(charDescription.slice(-1) !== ']' || charDescription.substr(0,1) !== '['){ //charDescription = '['+charDescription+']'; } storyString+=charDescription+'\n'; } } if(count_view_mes < topAnchorDepth){ storyString+=charPersonality+'\n'; } } if(main_api == 'kobold' || main_api == 'webui') { if(prepend.length) { storyString = prepend.join("\n") + "\n" + storyString; } if(append.length) { storyString = storyString + append.join("\n") + "\n"; } storyString = storyString.replace(/\n+/g, "\n"); } if(SystemPrompt.system_depth >= SystemPrompt.system_depth_max){ let sp_string = ""; sp_string = SystemPrompt.system_prompt.replace(/{{user}}/gi, name1) //System prompt .replace(/{{char}}/gi, name2) .replace(/<USER>/gi, name1) .replace(/<BOT>/gi, name2); storyString = sp_string+'\n'+storyString; } var count_exm_add = 0; var chat2 = []; var j = 0; for(var i = chat.length-1; i >= 0; i--){ if(j == 0){ chat[j]['mes'] = chat[j]['mes'].replace(/{{user}}/gi, name1); chat[j]['mes'] = chat[j]['mes'].replace(/{{char}}/gi, name2); chat[j]['mes'] = chat[j]['mes'].replace(/<USER>/gi, name1); chat[j]['mes'] = chat[j]['mes'].replace(/<BOT>/gi, name2); } let this_mes_ch_name = ''; if(chat[j]['is_user']){ this_mes_ch_name = name1; }else{ if(!is_room) this_mes_ch_name = name2; else this_mes_ch_name = Characters.id[chat[j]['chid']].name; } chat2[i] = {}; if(chat[j]['is_name']){ chat2[i]['mes'] = this_mes_ch_name+': '+chat[j]['mes']+'\n'; }else{ chat2[i]['mes'] = chat[j]['mes']+'\n'; } if(chat[j]['image_for_recognition'] !== undefined && isModelHaveImageRecognition()){ chat2[i]['image_for_recognition'] = chat[j]['image_for_recognition']; } j++; } //chat2 = chat2.reverse(); var this_max_context = 4096; if(main_api == 'kobold') this_max_context = max_context; if(main_api == 'webui') this_max_context = max_context_webui; if(main_api == 'horde') this_max_context = max_context; if(main_api == 'novel'){ if(novel_tier === 1){ this_max_context = 1024; }else{ this_max_context = 2048-60;//fix for fat tokens if(model_novel === 'krake-v2'){ this_max_context-=160; } if(model_novel === 'clio-v1' || model_novel === 'kayra-v1'){ this_max_context = 8000;//FunkEngine Fixing for what I suspect may be our failure to include JBs/prompts in token counts here as well, specific with kayra-vi 2023-11-30 @Zando in discord. this_max_context-=160;//fix for fat tokens } } } if(main_api == 'openai' || main_api == 'proxy') this_max_context = max_context_openai; if(main_api == 'claude') this_max_context = 100000; var i = 0; let mesExmString = ''; count_exm_add = 0; if(keep_dialog_examples){ for(let iii = 0; iii < mesExamplesArray.length; iii++){ mesExmString = mesExmString+mesExamplesArray[iii]; if(!is_pyg){ // mesExamplesArray[iii] = mesExamplesArray[iii].replace(/<START>/i, 'This is how '+name2+' should talk');//An example of how '+name2+' responds } count_exm_add++; } } if(type == 'swipe'){ chat2.shift(); } var isNeedToAddName2AfterLastMessage = false; runGenerate = function(cycleGenerationPromt = ''){ generatedPromtCache+=cycleGenerationPromt; if(generatedPromtCache.length == 0){ chatString = ""; arrMes = arrMes.reverse(); var is_add_personality = false; if (inject && inject.length && arrMes.length) { let thisInject = { mes: inject }; arrMes.splice(arrMes.length - 1, 0, thisInject); } arrMes.forEach(function(item, i, arr) {//For added anchors and others if((i >= arrMes.length-1 && $.trim(item['mes']).substr(0, (name1+":").length) != name1+":" && (main_api !== 'openai' && main_api !== 'proxy')) || (i >= arrMes.length-1 && $.trim(item['mes']).substr(0, (name1+":").length) != name1+":" && (main_api === 'openai' || main_api === 'proxy') && SystemPrompt.jailbreak_prompt.length === 0)){ if(textareaText == ""){ item['mes'] = item['mes'].substr(0,item['mes'].length-1); } } if(i === arrMes.length-topAnchorDepth && count_view_mes>=topAnchorDepth && !is_add_personality){ is_add_personality = true; //chatString = chatString.substr(0,chatString.length-1); //anchorAndPersonality = "[Genre: roleplay chat][Tone: very long messages with descriptions]"; if((anchorTop != "" || charPersonality != "") && !is_pyg){ if(anchorTop != "") charPersonality+=' '; item['mes']+="["+charPersonality+anchorTop+']\n'; } } if(i >= arrMes.length-1 && count_view_mes>8 && $.trim(item['mes']).substr(0, (name1+":").length) == name1+":" && !is_pyg){//For add anchor in end item['mes'] = item['mes'].substr(0,item['mes'].length-1); //chatString+=postAnchor+"\n";//"[Writing style: very long messages]\n"; item['mes'] =item['mes']+ anchorBottom+"\n"; } /* if(!free_char_name_mode && !((main_api === 'openai' || main_api === 'proxy') && isOpenAIChatModel())){ if(i >= arrMes.length-1 && $.trim(item['mes']).substr(0, (name1+":").length) == name1+":"){//for add name2 when user sent item['mes'] =item['mes']+name2+":"; } if(i >= arrMes.length-1 && $.trim(item['mes']).substr(0, (name1+":").length) != name1+":"){//for add name2 when continue if(textareaText == ""){ item['mes'] =item['mes']+'\n'+name2+":"; } } }
setPromtString
javascript
TavernAI/TavernAI
public/script.js
https://github.com/TavernAI/TavernAI/blob/master/public/script.js
MIT
async function getChatRoom(filename) { //console.log(characters[Characters.selectedID].chat); jQuery.ajax({ type: 'POST', url: '/getchatroom', data: JSON.stringify({ room_filename: filename }), beforeSend: function(){ //$('#create_button').attr('value','Creating...'); }, cache: false, timeout: requestTimeout, dataType: "json", contentType: "application/json", success: function(data){ // console.log(data); //chat.length = 0; // if(is_room) // { // Rooms.selectedIDs.forEach(function(curId, i) { // if(!Characters.id.includes(curId)) // { // let msg = "Cannot load room. Some characters expected are missing. Please check if you have all the characters."; // callPopup(msg, "alert"); // return; // } // }); // } if(data[0] !== undefined){ // Rooms.selectedCharacterNames = chat[0]['character_names']; // Rooms.selectedCharacters = getIDsByNames(chat[0]['character_names']); // console.log(data[0]['character_names']); // console.log(Characters.id); let selectedCharactersIdBuffer = getIDsByFilenames(data[0]['character_files']); let isMissingChars = false; selectedCharactersIdBuffer.forEach(function(curId, i) { if(curId < 0) // If name doesn't exist in the Characters.id objects array, then curId will be -1 { let msg = "Cannot load room. Some characters expected are missing. Please check if you have all the characters.\nRequired Characters: "; let chNameBuffer = ""; for(var i = 0; i < selectedCharactersIdBuffer.length; i++) { chNameBuffer = Characters.id[curId].name; // selectedCharactersIdBuffer.length is equal to data[0]['character_names'].length // if(i < selectedCharactersIdBuffer.length - 1) // msg += data[0]['character_names'][i] + ", "; // else // msg += data[0]['character_names'][i] + "."; if(i < selectedCharactersIdBuffer.length - 1) msg += chNameBuffer + ", "; else msg += chNameBuffer + "."; } callPopup(msg, "alert"); isMissingChars = true; return; } }); // Don't continue if one or more characters is missing if(isMissingChars) return; // Below block of code is for removing the redundant character_names attribute in selected room if exists, and removing the flag updated from the response. if(data[0]['updated']) { delete Rooms.id[Rooms.getIDbyFilename(filename + ".jsonl")].chat[0].character_names; Rooms.id[Rooms.getIDbyFilename(filename + ".jsonl")].chat[0].character_files = data[0]['character_files']; delete data[0].updated; // The flag should now no longer be needed, and must be removed before the next process. } // console.log("Incorrect/Error"); clearChat(); chat.length = 0; for (let key in data) { chat.push(data[key]); } //chat = data; // const ch_ext = ".webp"; // Assumed that character files would always have .webp extension // Characters.selectedID = Characters.getIDbyFilename(chat[0]['character_names'][0]+ch_ext); // Rooms.selectedCharacterNames = chat[0]['character_names']; Rooms.selectedCharacters = getIDsByFilenames(chat[0]['character_files']); let chNames = []; Rooms.selectedCharacters.forEach(function(curId, i) { chNames.push(Characters.id[curId].name); }); Rooms.selectedCharacterNames = chNames; Rooms.activeCharacterIdInit(chat[chat.length-1]); chat_create_date = chat[0]['create_date']; winNotes.text = chat[0].notes || ""; winNotes.strategy = chat[0].notes_type || "discr"; if(!winNotes.text || !winNotes.text.length) { let defaultWpp = '[Character("'+Characters.id[Characters.selectedID].name+'"){}]'; try { let parsed = WPP.parse(Characters.id[Characters.selectedID].description); if(parsed[0] && parsed[0].type && parsed[0].type.length && parsed[0].name && parsed[0].name.length) { defaultWpp = '[' + parsed[0].type + '("' + parsed[0].name + '"){}]'; } } catch(e) { /* ignore error */ } winNotes.wppText = defaultWpp; } chat.shift(); assignIDsByFilenames(); }else{ chat_create_date = Date.now(); } //console.log(chat); getChatResult(); loadRoomSelectedCharacters(); saveChatRoom(); // console.log(data[0]); textareaAutosize($('#room_scenario')); }, error: function (jqXHR, exception) { getChatResult(); console.log(exception); console.log(jqXHR); } }); }
Note that the clearChat() function (and chat.length = 0 assignment) is already called in this function, calling it before calling this function is redundant
getChatRoom
javascript
TavernAI/TavernAI
public/script.js
https://github.com/TavernAI/TavernAI/blob/master/public/script.js
MIT
function triggerLoadOrError(e) { triggerEvent(e.type, $(this).off(load_error, triggerLoadOrError)); }
Trigger onload/onerror handler @param {Event} e
triggerLoadOrError
javascript
TavernAI/TavernAI
public/scripts/jquery.lazyloadxt.min.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/jquery.lazyloadxt.min.js
MIT
function timeoutLazyElements() { if (waitingMode > 1) { waitingMode = 1; checkLazyElements(); setTimeout(timeoutLazyElements, options.throttle); } else { waitingMode = 0; } }
Run check of lazy elements after timeout
timeoutLazyElements
javascript
TavernAI/TavernAI
public/scripts/jquery.lazyloadxt.min.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/jquery.lazyloadxt.min.js
MIT
function getDefaultWhiteList() { return { a: ["target", "href", "title"], abbr: ["title"], address: [], area: ["shape", "coords", "href", "alt"], article: [], aside: [], audio: [ "autoplay", "controls", "crossorigin", "loop", "muted", "preload", "src", ], b: [], bdi: ["dir"], bdo: ["dir"], big: [], blockquote: ["cite"], br: [], caption: [], center: [], cite: [], code: [], col: ["align", "valign", "span", "width"], colgroup: ["align", "valign", "span", "width"], dd: [], del: ["datetime"], details: ["open"], div: [], dl: [], dt: [], em: [], figcaption: [], figure: [], font: ["color", "size", "face"], footer: [], h1: [], h2: [], h3: [], h4: [], h5: [], h6: [], header: [], hr: [], i: [], img: ["src", "alt", "title", "width", "height"], ins: ["datetime"], li: [], mark: [], nav: [], ol: [], p: [], pre: [], s: [], section: [], small: [], span: [], sub: [], summary: [], sup: [], strong: [], strike: [], table: ["width", "border", "align", "valign"], tbody: ["align", "valign"], td: ["width", "rowspan", "colspan", "align", "valign"], tfoot: ["align", "valign"], th: ["width", "rowspan", "colspan", "align", "valign"], thead: ["align", "valign"], tr: ["rowspan", "align", "valign"], tt: [], u: [], ul: [], video: [ "autoplay", "controls", "crossorigin", "loop", "muted", "playsinline", "poster", "preload", "src", "height", "width", ], }; }
default settings @author Zongmin Lei<[email protected]>
getDefaultWhiteList
javascript
TavernAI/TavernAI
public/scripts/xss.js
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
MIT