code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
isSpawnedDaemonDead = (ipfsd) => {
if (typeof ipfsd.subprocess === 'undefined') throw new Error('undefined ipfsd.subprocess, unable to reason about startup errors')
if (ipfsd.subprocess === null) return false // not spawned yet or remote
if (ipfsd.subprocess?.failed) return true // explicit failure
// detect when spawned ipfsd process is gone/dead
// by inspecting its pid - it should be alive
const { pid } = ipfsd.subprocess
try {
// signal 0 throws if process is missing, noop otherwise
process.kill(pid, 0)
return false
} catch (e) {
return true
}
}
|
Start IPFS, collects the logs, detects errors and migrations.
@param {import('ipfsd-ctl').Controller} ipfsd
@returns {Promise<IpfsLogs>}
|
isSpawnedDaemonDead
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/daemon.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/daemon.js
|
MIT
|
async function startDaemon (opts) {
const ipfsd = await getIpfsd(opts.flags, opts.path)
if (ipfsd === null) {
app.quit()
return { ipfsd: undefined, err: new Error('get ipfsd failed'), id: undefined, logs: '' }
}
let { err, logs, id } = await startIpfsWithLogs(ipfsd)
if (err) {
if (!err.message.includes('ECONNREFUSED') && !err.message.includes('ERR_CONNECTION_REFUSED')) {
return { ipfsd, err, logs, id }
}
if (!configExists(ipfsd)) {
dialogs.cannotConnectToApiDialog(ipfsd.apiAddr.toString())
return { ipfsd, err, logs, id }
}
logger.info('[daemon] removing api file')
removeApiFile(ipfsd)
const errLogs = await startIpfsWithLogs(ipfsd)
err = errLogs.err
logs = errLogs.logs
id = errLogs.id
}
// If we have an error here, it should have been handled by startIpfsWithLogs.
return { ipfsd, err, logs, id }
}
|
Start the IPFS daemon.
@param {any} opts
@returns {Promise<{ ipfsd: import('ipfsd-ctl').Controller|undefined } & IpfsLogs>}
|
startDaemon
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/daemon.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/daemon.js
|
MIT
|
function cannotConnectToApiDialog (addr) {
hideOtherWindows()
showDialog({
title: i18n.t('cannotConnectToApiDialog.title'),
message: i18n.t('cannotConnectToApiDialog.message', { addr }),
type: 'error',
buttons: [
i18n.t('quit')
]
})
}
|
Dialog to show when the daemon cannot connect to remote API.
@param {string} addr
|
cannotConnectToApiDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/dialogs.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/dialogs.js
|
MIT
|
function multipleBusyPortsDialog () {
hideOtherWindows()
const opt = showDialog({
title: i18n.t('multipleBusyPortsDialog.title'),
message: i18n.t('multipleBusyPortsDialog.message'),
type: 'error',
buttons: [
i18n.t('multipleBusyPortsDialog.action'),
i18n.t('quit')
]
})
return opt === 0
}
|
Dialog to show when there are multiple busy ports.
@returns {boolean} open the configuration file
|
multipleBusyPortsDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/dialogs.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/dialogs.js
|
MIT
|
function busyPortDialog (port, alt) {
hideOtherWindows()
const opt = showDialog({
title: i18n.t('busyPortDialog.title'),
message: i18n.t('busyPortDialog.message', { port, alt }),
type: 'error',
buttons: [
i18n.t('busyPortDialog.action', { port, alt }),
i18n.t('quit')
]
})
return opt === 0
}
|
Dialog to show when there is a busy port and we offer an alternative.
@param {Number} port is the busy port
@param {Number} alt is the alternative free port
@returns {boolean} use the alternative port
|
busyPortDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/dialogs.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/dialogs.js
|
MIT
|
function busyPortsDialog (port1, alt1, port2, alt2) {
hideOtherWindows()
const opt = showDialog({
title: i18n.t('busyPortsDialog.title'),
message: i18n.t('busyPortsDialog.message', { port1, alt1, port2, alt2 }),
type: 'error',
buttons: [
i18n.t('busyPortsDialog.action', { port1, alt1, port2, alt2 }),
i18n.t('quit')
]
})
return opt === 0
}
|
Dialog to show when there are two busy ports and we offer an alternative.
@param {Number} port1 is the busy port 1
@param {Number} alt1 is the alternative free port 1
@param {Number} port2 is the busy port 2
@param {Number} alt2 is the alternative free port 2
@returns {boolean} use the alternative port
|
busyPortsDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/dialogs.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/dialogs.js
|
MIT
|
function hideWindowsAndShowDialog (i18nKey, opts) {
hideOtherWindows()
showDialog({
title: i18n.t(`${i18nKey}.title`),
message: i18n.t(`${i18nKey}.message`, opts),
buttons: [i18n.t('quit')]
})
}
|
Show the dialog with the text from the i18nKey, using the
options opts.
@param {string} i18nKey
@param {any} opts
|
hideWindowsAndShowDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/dialogs.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/dialogs.js
|
MIT
|
function repositoryIsPrivateDialog (path) {
hideWindowsAndShowDialog('privateNetworkDialog', { path })
}
|
Dialog to show when the repository is part of a private network.
@param {string} path
|
repositoryIsPrivateDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/dialogs.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/dialogs.js
|
MIT
|
function repositoryMustBeDirectoryDialog (path) {
hideWindowsAndShowDialog('repositoryMustBeDirectoryDialog', { path })
}
|
Dialog to show when we detect that the repository is not a directory.
@param {string} path
|
repositoryMustBeDirectoryDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/dialogs.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/dialogs.js
|
MIT
|
function repositoryConfigurationIsMissingDialog (path) {
hideWindowsAndShowDialog('repositoryConfigurationIsMissingDialog', { path })
}
|
Dialog to show when we detect that the configuration file is missing.
@param {string} path
|
repositoryConfigurationIsMissingDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/dialogs.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/dialogs.js
|
MIT
|
function repositoryIsInvalidDialog (path) {
hideWindowsAndShowDialog('invalidRepositoryDialog', { path })
}
|
Dialog to show when we detect that the repository is invalid, but we
are not sure what the problem is.
@param {string} path
|
repositoryIsInvalidDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/dialogs.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/dialogs.js
|
MIT
|
function showMigrationPrompt (logs, error = false, done = false) {
// Generate random id
const id = crypto.randomBytes(16).toString('hex')
const loadWindow = (logs, error = false, done = false) => {
if (!window) {
window = new BrowserWindow({
show: false,
width: 800,
height: 438,
useContentSize: true,
resizable: false,
autoHideMenuBar: true,
fullscreenable: false,
backgroundColor: getBackgroundColor(),
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
window.on('close', () => {
dock.hide()
window = null
})
window.once('ready-to-show', () => {
dock.show()
window.show()
})
}
const page = error ? errorTemplate(logs) : inProgressTemplate(logs, id, done)
const data = `data:text/html;base64,${Buffer.from(page, 'utf8').toString('base64')}`
window.loadURL(data)
}
loadWindow(logs, error, done)
return {
update: logs => {
if (window) {
window.webContents.send(id, logs)
return true
}
return false
},
loadWindow
}
}
|
Show migration prompt.
@param {string} logs
@param {boolean} error
@param {boolean} done
@returns {MigrationPrompt}
|
showMigrationPrompt
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/migration-prompt.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/migration-prompt.js
|
MIT
|
loadWindow = (logs, error = false, done = false) => {
if (!window) {
window = new BrowserWindow({
show: false,
width: 800,
height: 438,
useContentSize: true,
resizable: false,
autoHideMenuBar: true,
fullscreenable: false,
backgroundColor: getBackgroundColor(),
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
window.on('close', () => {
dock.hide()
window = null
})
window.once('ready-to-show', () => {
dock.show()
window.show()
})
}
const page = error ? errorTemplate(logs) : inProgressTemplate(logs, id, done)
const data = `data:text/html;base64,${Buffer.from(page, 'utf8').toString('base64')}`
window.loadURL(data)
}
|
Show migration prompt.
@param {string} logs
@param {boolean} error
@param {boolean} done
@returns {MigrationPrompt}
|
loadWindow
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/migration-prompt.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/migration-prompt.js
|
MIT
|
loadWindow = (logs, error = false, done = false) => {
if (!window) {
window = new BrowserWindow({
show: false,
width: 800,
height: 438,
useContentSize: true,
resizable: false,
autoHideMenuBar: true,
fullscreenable: false,
backgroundColor: getBackgroundColor(),
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
window.on('close', () => {
dock.hide()
window = null
})
window.once('ready-to-show', () => {
dock.show()
window.show()
})
}
const page = error ? errorTemplate(logs) : inProgressTemplate(logs, id, done)
const data = `data:text/html;base64,${Buffer.from(page, 'utf8').toString('base64')}`
window.loadURL(data)
}
|
Show migration prompt.
@param {string} logs
@param {boolean} error
@param {boolean} done
@returns {MigrationPrompt}
|
loadWindow
|
javascript
|
ipfs/ipfs-desktop
|
src/daemon/migration-prompt.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/daemon/migration-prompt.js
|
MIT
|
function criticalErrorDialog (e) {
if (hasErrored) return
hasErrored = true
const option = dialog({
title: i18n.t('ipfsDesktopHasShutdownDialog.title'),
message: i18n.t('ipfsDesktopHasShutdownDialog.message'),
type: 'error',
buttons: [
i18n.t('restartIpfsDesktop'),
i18n.t('close'),
i18n.t('reportTheError')
]
})
if (option === 0) {
app.relaunch()
} else if (option === 2) {
shell.openExternal(generateErrorIssueUrl(e))
}
app.exit(1)
}
|
This will fail and throw another application error if electron hasn't booted up properly.
@param {Error} e
@returns
|
criticalErrorDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/dialogs/errors.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/dialogs/errors.js
|
MIT
|
function recoverableErrorDialog (e, options) {
const cfg = {
title: i18n.t('recoverableErrorDialog.title'),
message: i18n.t('recoverableErrorDialog.message'),
type: 'error',
buttons: [
i18n.t('close'),
i18n.t('reportTheError'),
i18n.t('openLogs')
]
}
if (options) {
if (options.title) {
cfg.title = options.title
}
if (options.message) {
cfg.message = options.message
}
}
const option = dialog(cfg)
if (option === 1) {
shell.openExternal(generateErrorIssueUrl(e))
} else if (option === 2) {
shell.openPath(path.join(app.getPath('userData'), 'combined.log'))
}
}
|
This will fail and throw another application error if electron hasn't booted up properly.
@param {Error} e
@returns
|
recoverableErrorDialog
|
javascript
|
ipfs/ipfs-desktop
|
src/dialogs/errors.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/src/dialogs/errors.js
|
MIT
|
async function startApp ({ repoPath } = {}) {
const home = tmp.dirSync({ prefix: 'tmp_home_', unsafeCleanup: true }).name
if (!repoPath) {
repoPath = path.join(home, '.ipfs')
}
app = await electron.launch({
args: [path.join(__dirname, '../../src/index.js')],
env: Object.assign({}, process.env, {
NODE_ENV: 'test',
HOME: home,
IPFS_PATH: repoPath
})
})
return { app, repoPath, home }
}
|
@param {Object} [param0]
@param {string} param0.repoPath
@returns {Promise<{ app: Awaited<ReturnType<import('playwright')._electron['launch']>>, repoPath: string, home: string }>
|
startApp
|
javascript
|
ipfs/ipfs-desktop
|
test/e2e/launch.e2e.test.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/test/e2e/launch.e2e.test.js
|
MIT
|
async function daemonReady (app) {
const peerId = await app.evaluate(async ({ ipcMain }) => new Promise((resolve, reject) => {
ipcMain.on('ipfsd', (status, peerId) => {
switch (status) {
// NOTE: this code runs inside the main process of electron, so we cannot use
// things we've imported outside of this function. The hard coded values can be
// found in src/daemon/consts.js.
case 3:
reject(new Error('starting daemon failed'))
break
case 2:
resolve(peerId)
break
}
})
}))
return { peerId }
}
|
@param {Awaited<ReturnType<import('playwright')._electron['launch']>>} app
@returns {Promise<{ peerId: string }>
|
daemonReady
|
javascript
|
ipfs/ipfs-desktop
|
test/e2e/launch.e2e.test.js
|
https://github.com/ipfs/ipfs-desktop/blob/master/test/e2e/launch.e2e.test.js
|
MIT
|
function flattenTree({ tree, simple, radio, showPartialState, hierarchical, rootPrefixId }) {
const forest = Array.isArray(tree) ? tree : [tree]
// eslint-disable-next-line no-use-before-define
return walkNodes({
nodes: forest,
simple,
radio,
showPartialState,
hierarchical,
rootPrefixId,
})
}
|
Converts a nested node into an associative array with pointers to child and parent nodes
Given:
```
const tree = [
{
label: 'item1',
value: 'value1',
children: [
{
label: 'item1-1',
value: 'value1-1',
children: [
{
label: 'item1-1-1',
value: 'value1-1-1'
},
{
label: 'item1-1-2',
value: 'value1-1-2'
}
]
},
{
label: 'item1-2',
value: 'value1-2'
}
]
},
{
label: 'item2',
value: 'value2',
children: [
{
label: 'item2-1',
value: 'value2-1',
children: [
{
label: 'item2-1-1',
value: 'value2-1-1'
},
{
label: 'item2-1-2',
value: 'value2-1-2'
},
{
label: 'item2-1-3',
value: 'item2-1-3',
children: [
{
label: 'item2-1-3-1',
value: 'value2-1-3-1'
}
]
}
]
},
{
label: 'item2-2',
value: 'value2-2'
}
]
}
]
```
results in
```
{
"0": {
_id: "0",
_parent: null,
_children: [
"0-0",
"0-1"
],
label: "item1",
value: "value1"
},
"1": {
_id: "1",
_parent: null,
_children: [
"1-0",
"1-1"
],
label: "item2",
value: "value2"
},
"0-0": {
_id: "0-0",
_parent: "0",
_children: [
"0-0-0",
"0-0-1"
],
label: "item1-1",
value: "value1-1"
},
"0-1": {
_id: "0-1",
_parent: "0",
label: "item1-2",
value: "value1-2"
},
"0-0-0": {
_id: "0-0-0",
_parent: "0-0",
label: "item1-1-1",
value: "value1-1-1"
},
"0-0-1": {
_id: "0-0-1",
_parent: "0-0",
label: "item1-1-2",
value: "value1-1-2"
},
"1-0": {
_id: "1-0",
_parent: "1",
_children: [
"1-0-0",
"1-0-1",
"1-0-2"
],
label: "item2-1",
value: "value2-1"
},
"1-1": {
_id: "1-1",
_parent: "1",
label: "item2-2",
value: "value2-2"
},
"1-0-0": {
_id: "1-0-0",
_parent: "1-0",
label: "item2-1-1",
value: "value2-1-1"
},
"1-0-1": {
_id: "1-0-1",
_parent: "1-0",
label: "item2-1-2",
value: "value2-1-2"
},
"1-0-2": {
_id: "1-0-2",
_parent: "1-0",
_children: [
"1-0-2-0"
],
label: "item2-1-3",
value: "value2-1-3"
},
"1-0-2-0": {
_id: "1-0-2-0",
_parent: "1-0-2",
label: "item2-1-3-1",
value: "value2-1-3-1"
}
}
```
@param {[type]} tree The incoming tree object
@param {[bool]} simple Whether its in Single select mode (simple dropdown)
@param {[bool]} radio Whether its in Radio select mode (radio dropdown)
@param {[bool]} showPartialState Whether to show partially checked state
@param {[string]} rootPrefixId The prefix to use when setting root node ids
@return {object} The flattened list
|
flattenTree
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/flatten-tree.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/flatten-tree.js
|
MIT
|
function setInitialStateProps(node, parent = {}, inheritChecked = true) {
const stateProps = inheritChecked ? ['checked', 'disabled'] : ['disabled']
for (let index = 0; index < stateProps.length; index++) {
const prop = stateProps[index]
// if and only if, node doesn't explicitly define a prop, grab it from parent
if (node[prop] === undefined && parent[prop] !== undefined) {
node[prop] = parent[prop]
}
}
}
|
If the node didn't specify anything on its own
figure out the initial state based on parent
@param {object} node [current node]
@param {object} parent [node's immediate parent]
@param {bool} inheritChecked [if checked should be inherited]
|
setInitialStateProps
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/flatten-tree.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/flatten-tree.js
|
MIT
|
function walkNodes({
nodes,
parent,
depth = 0,
simple,
radio,
showPartialState,
hierarchical,
rootPrefixId,
_rv = { list: new Map(), defaultValues: [], singleSelectedNode: null },
}) {
const single = simple || radio
nodes.forEach((node, i) => {
node._depth = depth
if (parent) {
node._id = node.id || `${parent._id}-${i}`
node._parent = parent._id
parent._children.push(node._id)
} else {
node._id = node.id || `${rootPrefixId ? `${rootPrefixId}-${i}` : i}`
}
if (single && node.checked) {
if (_rv.singleSelectedNode) {
node.checked = false
} else {
_rv.singleSelectedNode = node
}
}
if (single && node.isDefaultValue && _rv.singleSelectedNode && !_rv.singleSelectedNode.isDefaultValue) {
// Default value has precedence, uncheck previous value
_rv.singleSelectedNode.checked = false
_rv.singleSelectedNode = null
}
if (node.isDefaultValue && (!single || _rv.defaultValues.length === 0)) {
_rv.defaultValues.push(node._id)
node.checked = true
if (single) {
_rv.singleSelectedNode = node
}
}
if (!hierarchical || radio) setInitialStateProps(node, parent, !radio)
_rv.list.set(node._id, node)
if (!simple && node.children) {
node._children = []
walkNodes({
nodes: node.children,
parent: node,
depth: depth + 1,
radio,
showPartialState,
hierarchical,
_rv,
})
if (showPartialState && !node.checked) {
node.partial = getPartialState(node)
// re-check if all children are checked. if so, check thyself
if (!single && !isEmpty(node.children) && node.children.every(c => c.checked)) {
node.checked = true
}
}
node.children = undefined
}
})
return _rv
}
|
If the node didn't specify anything on its own
figure out the initial state based on parent
@param {object} node [current node]
@param {object} parent [node's immediate parent]
@param {bool} inheritChecked [if checked should be inherited]
|
walkNodes
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/flatten-tree.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/flatten-tree.js
|
MIT
|
unCheckParents(node) {
let parent = node._parent
while (parent) {
const next = this.getNodeById(parent)
next.checked = false
next.partial = getPartialState(next, '_children', this.getNodeById.bind(this))
parent = next._parent
}
}
|
Walks up the tree unchecking parent nodes
@param {[type]} node [description]
@return {[type]} [description]
|
unCheckParents
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/index.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/index.js
|
MIT
|
partialCheckParents(node) {
let parent = node._parent
while (parent) {
const next = this.getNodeById(parent)
next.checked = next._children.every(c => this.getNodeById(c).checked)
next.partial = getPartialState(next, '_children', this.getNodeById.bind(this))
parent = next._parent
}
}
|
Walks up the tree setting partial state on parent nodes
@param {[type]} node [description]
@return {[type]} [description]
|
partialCheckParents
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/index.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/index.js
|
MIT
|
toggleChildren(id, state) {
const node = this.getNodeById(id)
node.checked = state
if (this.showPartialState) {
node.partial = false
}
if (!isEmpty(node._children)) {
node._children.forEach(id => this.toggleChildren(id, state))
}
}
|
Walks up the tree setting partial state on parent nodes
@param {[type]} node [description]
@return {[type]} [description]
|
toggleChildren
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/index.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/index.js
|
MIT
|
toggleNodeExpandState(id) {
const node = this.getNodeById(id)
node.expanded = !node.expanded
if (!node.expanded) this.collapseChildren(node)
return this.tree
}
|
Walks up the tree setting partial state on parent nodes
@param {[type]} node [description]
@return {[type]} [description]
|
toggleNodeExpandState
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/index.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/index.js
|
MIT
|
collapseChildren(node) {
node.expanded = false
if (!isEmpty(node._children)) {
node._children.forEach(c => this.collapseChildren(this.getNodeById(c)))
}
}
|
Walks up the tree setting partial state on parent nodes
@param {[type]} node [description]
@return {[type]} [description]
|
collapseChildren
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/index.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/index.js
|
MIT
|
get tags() {
if (this.radioSelect || this.simpleSelect) {
if (this.currentChecked) {
return [this.getNodeById(this.currentChecked)]
}
return []
}
return nodeVisitor.getNodesMatching(this.tree, (node, key, visited) => {
if (node.checked && !this.hierarchical) {
// Parent node, so no need to walk children
nodeVisitor.markSubTreeVisited(node, visited, id => this.getNodeById(id))
}
return node.checked
})
}
|
Walks up the tree setting partial state on parent nodes
@param {[type]} node [description]
@return {[type]} [description]
|
tags
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/index.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/index.js
|
MIT
|
getTreeAndTags() {
return { tree: this.tree, tags: this.tags }
}
|
Walks up the tree setting partial state on parent nodes
@param {[type]} node [description]
@return {[type]} [description]
|
getTreeAndTags
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/index.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/index.js
|
MIT
|
handleNavigationKey(currentFocus, tree, key, readOnly, markSubTreeOnNonExpanded, onToggleChecked, onToggleExpanded) {
const prevFocus = currentFocus && this.getNodeById(currentFocus)
const getNodeById = id => this.getNodeById(id)
const action = keyboardNavigation.getAction(prevFocus, key)
if (FocusActionNames.has(action)) {
const newFocus = keyboardNavigation.handleFocusNavigationkey(
tree,
action,
prevFocus,
getNodeById,
markSubTreeOnNonExpanded
)
return newFocus
}
if (!prevFocus || !tree.has(prevFocus._id)) {
// No current focus or not visible
return currentFocus
}
return keyboardNavigation.handleToggleNavigationkey(action, prevFocus, readOnly, onToggleChecked, onToggleExpanded)
}
|
Walks up the tree setting partial state on parent nodes
@param {[type]} node [description]
@return {[type]} [description]
|
handleNavigationKey
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/index.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/index.js
|
MIT
|
_getAddOnMatch(matches, searchTerm) {
let isMatch = (node, term) => node.label.toLowerCase().indexOf(term) >= 0
if (typeof this.searchPredicate === 'function') {
isMatch = this.searchPredicate
}
return node => {
if (isMatch(node, searchTerm)) {
matches.push(node._id)
}
}
}
|
Walks up the tree setting partial state on parent nodes
@param {[type]} node [description]
@return {[type]} [description]
|
_getAddOnMatch
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/tree-manager/index.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/tree-manager/index.js
|
MIT
|
later = () => {
timeout = null
func(...args)
}
|
Modified debounce that always invokes on leading edge
See unmodified: https://gist.github.com/mrchief/a7e8938ee96774f05644905b37f09536
|
later
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/utils/debounce.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/utils/debounce.js
|
MIT
|
later = () => {
timeout = null
func(...args)
}
|
Modified debounce that always invokes on leading edge
See unmodified: https://gist.github.com/mrchief/a7e8938ee96774f05644905b37f09536
|
later
|
javascript
|
dowjones/react-dropdown-tree-select
|
src/utils/debounce.js
|
https://github.com/dowjones/react-dropdown-tree-select/blob/master/src/utils/debounce.js
|
MIT
|
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms, 'done');
});
}
|
Tiemout
@param int ms
@return Promise<any>
|
timeout
|
javascript
|
unruledboy/WebFrontEndStack
|
index.js
|
https://github.com/unruledboy/WebFrontEndStack/blob/master/index.js
|
Apache-2.0
|
function buildReadme(object, language, deep) {
let deeper = deep + 1;
let deepString = new Array(deeper).join("\t") + "- ";
let ret = [];
let lang = "";
if (object.languages) {
lang = object.languages[language];
}
lang = lang || object.name;
ret.push((function (deepString, name, url, github) {
let haveUrl = !!url;
let haveGitHub = !!github;
let ret = [];
ret.push(deepString);
ret.push((haveUrl ? "[" : "") + name + (haveUrl ? "](" + url + ")" : ""));
ret.push((haveGitHub ? " [\[GitHub\]](" + github + ")" : ""));
return ret.join("");
})(deepString, lang, object.url, object.github));
if (object.children) {
object.children.map((value, index) => {
ret.push(buildReadme(value, language, deeper));
});
}
return ret.join("\n");
}
|
Recursion to generate readme
@param object object
@param string language
@param int deep
@return string
|
buildReadme
|
javascript
|
unruledboy/WebFrontEndStack
|
index.js
|
https://github.com/unruledboy/WebFrontEndStack/blob/master/index.js
|
Apache-2.0
|
function phantomjs(language) {
let displayLanguage = language === "" ? "en" : language;
let promise = new Promise((resolve, reject) => {
return phantom.createAsync().then((phantom) => {
return phantom.createPageAsync();
}).then((objects) => {
console.log("Setting viewportSize..");
return objects.page.setAsync('viewportSize', {
width: pageWidth,
height: pageHeight
});
}).then((objects) => {
console.log("Opening " + httpServer + "?locale=" + language + " for " + displayLanguage);
return objects.page.openAsync(httpServer + "?locale=" + language);
}).then((objects) => {
console.log("Rendered HTML, the image will be saved after 2 seconds.");
if (objects.ret[0] != "success") {
throw objects.ret[0];
}
return timeout(2000).then(() => {
return objects.page.renderAsync(path.join(__dirname, 'Web Front End Stack' + (language === "" ? "" : ".") + language + '.png'));
});
}).then((objects) => {
console.log("The image(" + displayLanguage + ") saved successfully!");
objects.page.close();
objects.phantom.exit();
resolve();
});
});
return promise;
}
|
For running phantomjs to take a screenshot for the webpage
@return Promise<any>
|
phantomjs
|
javascript
|
unruledboy/WebFrontEndStack
|
index.js
|
https://github.com/unruledboy/WebFrontEndStack/blob/master/index.js
|
Apache-2.0
|
function readme(language) {
let extension = (language === "" ? "" : ".") + language;
let promise = new Promise((resolve, reject) => {
fs.readFile('./README' + extension + '.md', "utf-8", (err, content) => {
if (err) return reject(err);
resolve(content);
});
});
return promise.then((fileContent) => {
let ret = buildReadme(jsonData, language, 0);
fileContent = fileContent.replace(/<\!--BUILD_START-->[\d\D]+?<\!--BUILD_END-->/, "{%BuildStart%}");
fs.writeFileSync('./README' + extension + '.md', fileContent.replace("{%BuildStart%}", "<!--BUILD_START-->\n\n" + ret + "\n\n<!--BUILD_END-->", "utf-8"));
console.log('Readme (' + language + ') built successfully!');
});
}
|
To rebuild the README.md
@return Promise<any>
|
readme
|
javascript
|
unruledboy/WebFrontEndStack
|
index.js
|
https://github.com/unruledboy/WebFrontEndStack/blob/master/index.js
|
Apache-2.0
|
function server() {
return new Promise((resolve, reject) => {
return app
.set('port', options.port)
.set('view engine', 'html')
.use(Express.static(path.join(__dirname, '/ux')))
.use('/', function (req, res) {
res.redirect('/WebFrontEndStack.htm?locale=' + req.query.locale);
})
.listen(options.port, function () {
console.info('Express started on: http://127.0.0.1:' + options.port);
resolve(app);
});
});
}
|
To start an express server
@return Promise<any>
|
server
|
javascript
|
unruledboy/WebFrontEndStack
|
index.js
|
https://github.com/unruledboy/WebFrontEndStack/blob/master/index.js
|
Apache-2.0
|
async function up(knex) {
const hasRole = await knex.schema.hasColumn("users", "role");
if (!hasRole) {
await knex.transaction(async function(trx) {
await trx.schema.alterTable("users", table => {
table
.enu("role", [ROLES.USER, ROLES.ADMIN])
.notNullable()
.defaultTo(ROLES.USER);
});
if (typeof process.env.ADMIN_EMAILS === "string") {
const adminEmails = process.env.ADMIN_EMAILS.split(",").map((e) => e.trim());
const adminRoleQuery = trx("users").update("role", ROLES.ADMIN);
adminEmails.forEach((adminEmail, index) => {
if (index === 0) {
adminRoleQuery.where("email", adminEmail);
} else {
adminRoleQuery.orWhere("email", adminEmail);
}
});
await adminRoleQuery;
}
});
}
}
|
@param { import("knex").Knex } knex
@returns { Promise<void> }
|
up
|
javascript
|
thedevs-network/kutt
|
server/migrations/20241103083933_user-roles.js
|
https://github.com/thedevs-network/kutt/blob/master/server/migrations/20241103083933_user-roles.js
|
MIT
|
async function up(knex) {
// make apikey unique
await knex.schema.alterTable("users", function(table) {
table.unique("apikey");
});
// IF NOT EXISTS is not available on MySQL So if you're
// using MySQL you should make sure you don't have these indexes already
const ifNotExists = isMySQL ? "" : "IF NOT EXISTS";
// create them separately because one string with break lines didn't work on MySQL
await Promise.all([
knex.raw(`CREATE INDEX ${ifNotExists} links_domain_id_index ON links (domain_id);`),
knex.raw(`CREATE INDEX ${ifNotExists} links_user_id_index ON links (user_id);`),
knex.raw(`CREATE INDEX ${ifNotExists} links_address_index ON links (address);`),
knex.raw(`CREATE INDEX ${ifNotExists} links_expire_in_index ON links (expire_in);`),
knex.raw(`CREATE INDEX ${ifNotExists} domains_address_index ON domains (address);`),
knex.raw(`CREATE INDEX ${ifNotExists} domains_user_id_index ON domains (user_id);`),
knex.raw(`CREATE INDEX ${ifNotExists} hosts_address_index ON hosts (address);`),
knex.raw(`CREATE INDEX ${ifNotExists} visits_link_id_index ON visits (link_id);`),
]);
}
|
@param { import("knex").Knex } knex
@returns { Promise<void> }
|
up
|
javascript
|
thedevs-network/kutt
|
server/migrations/20241223062111_indexes.js
|
https://github.com/thedevs-network/kutt/blob/master/server/migrations/20241223062111_indexes.js
|
MIT
|
async function down(knex) {
await knex.schema.alterTable("users", function(table) {
table.dropUnique(["apikey"]);
});
await Promise.all([
knex.raw(`DROP INDEX links_domain_id_index;`),
knex.raw(`DROP INDEX links_user_id_index;`),
knex.raw(`DROP INDEX links_address_index;`),
knex.raw(`DROP INDEX links_expire_in_index;`),
knex.raw(`DROP INDEX domains_address_index;`),
knex.raw(`DROP INDEX domains_user_id_index;`),
knex.raw(`DROP INDEX hosts_address_index;`),
knex.raw(`DROP INDEX visits_link_id_index;`),
]);
}
|
@param { import("knex").Knex } knex
@returns { Promise<void> }
|
down
|
javascript
|
thedevs-network/kutt
|
server/migrations/20241223062111_indexes.js
|
https://github.com/thedevs-network/kutt/blob/master/server/migrations/20241223062111_indexes.js
|
MIT
|
async function up(knex) {
const hasUserIDColumn = await knex.schema.hasColumn("visits", "user_id");
if (hasUserIDColumn) return;
await knex.schema.alterTable("visits", function(table) {
table
.integer("user_id")
.unsigned();
table
.foreign("user_id")
.references("id")
.inTable("users")
.onDelete("CASCADE")
.withKeyName("visits_user_id_foreign");
});
const [{ count }] = await knex("visits").count("* as count");
const count_number = parseInt(count);
if (Number.isNaN(count_number) || count_number === 0) return;
if (count_number < 1_000_000) {
const last_visit = await knex("visits").orderBy("id", "desc").first();
const size = 100_000;
const loops = Math.floor(last_visit.id / size) + 1;
await Promise.all(
new Array(loops).fill(null).map((_, i) => {
return knex("visits")
.fromRaw(knex.raw("visits v"))
.update({ user_id: knex.ref("links.user_id") })
.updateFrom("links")
.where("links.id", knex.ref("link_id"))
.andWhereBetween("v.id", [i * size, (i * size) + size]);
})
);
} else {
console.warn(
"MIGRATION WARN:" +
"Skipped adding user_id to visits due to high volume of visits and the potential risk of locking the database.\n" +
"Please refer to Kutt's migration guide for more information."
);
}
}
|
@param { import("knex").Knex } knex
@returns { Promise<void> }
|
up
|
javascript
|
thedevs-network/kutt
|
server/migrations/20241223103044_visits_user_id.js
|
https://github.com/thedevs-network/kutt/blob/master/server/migrations/20241223103044_visits_user_id.js
|
MIT
|
async function up(knex) {
// IF NOT EXISTS is not available on MySQL So if you're
// using MySQL you should make sure you don't have these indexes already
const ifNotExists = isMySQL ? "" : "IF NOT EXISTS";
await knex.raw(`
CREATE INDEX ${ifNotExists} visits_user_id_index ON visits (user_id);
`);
}
|
@param { import("knex").Knex } knex
@returns { Promise<void> }
|
up
|
javascript
|
thedevs-network/kutt
|
server/migrations/20241223155527_visits_user_id_index.js
|
https://github.com/thedevs-network/kutt/blob/master/server/migrations/20241223155527_visits_user_id_index.js
|
MIT
|
async function down(knex) {
await knex.raw(`
DROP INDEX visits_user_id_index;
`);
}
|
@param { import("knex").Knex } knex
@returns { Promise<void> }
|
down
|
javascript
|
thedevs-network/kutt
|
server/migrations/20241223155527_visits_user_id_index.js
|
https://github.com/thedevs-network/kutt/blob/master/server/migrations/20241223155527_visits_user_id_index.js
|
MIT
|
populate_bounce_message_with_headers (from, to, reason, header, cb) {
const CRLF = '\r\n';
const originalMessageId = header.get('Message-Id');
const bounce_msg_ = config.get('outbound.bounce_message', 'data');
const bounce_msg_html_ = config.get('outbound.bounce_message_html', 'data');
const bounce_msg_image_ = config.get('outbound.bounce_message_image', 'data');
const bounce_header_lines = [];
const bounce_body_lines = [];
const bounce_html_lines = [];
const bounce_image_lines = [];
let bounce_headers_done = false;
const values = {
date: utils.date_to_str(new Date()),
me: net_utils.get_primary_host_name(),
from,
to,
subject: header.get_decoded('Subject').trim(),
recipients: this.todo.rcpt_to.join(', '),
reason,
extended_reason: this.todo.rcpt_to.map(recip => {
if (recip.reason) {
return `${recip.original}: ${recip.reason}`;
}
}).join('\n'),
pid: process.pid,
msgid: `<${utils.uuid()}@${net_utils.get_primary_host_name()}>`,
};
bounce_msg_.forEach(line => {
line = line.replace(/\{(\w+)\}/g, (i, word) => values[word] || '?');
if (bounce_headers_done == false && line == '') {
bounce_headers_done = true;
}
else if (bounce_headers_done == false) {
bounce_header_lines.push(line);
}
else if (bounce_headers_done == true) {
bounce_body_lines.push(line);
}
});
const escaped_chars = {
"&": "amp",
"<": "lt",
">": "gt",
'"': 'quot',
"'": 'apos',
"\r": '#10',
"\n": '#13'
};
const escape_pattern = new RegExp(`[${Object.keys(escaped_chars).join('')}]`, 'g');
bounce_msg_html_.forEach(line => {
line = line.replace(/\{(\w+)\}/g, (i, word) => {
if (word in values) {
return String(values[word]).replace(escape_pattern, m => `&${escaped_chars[m]};`);
}
else {
return '?';
}
});
bounce_html_lines.push(line);
});
bounce_msg_image_.forEach(line => {
bounce_image_lines.push(line)
});
const boundary = `boundary_${utils.uuid()}`;
const bounce_body = [];
bounce_header_lines.forEach(line => {
bounce_body.push(`${line}${CRLF}`);
});
bounce_body.push(`Content-Type: multipart/report; report-type=delivery-status;${CRLF} boundary="${boundary}"${CRLF}`);
// Adding references to original msg id
if (originalMessageId != '') {
bounce_body.push(`References: ${originalMessageId.replace(/(\r?\n)*$/, '')}${CRLF}`);
}
bounce_body.push(CRLF);
bounce_body.push(`This is a MIME-encapsulated message.${CRLF}`);
bounce_body.push(CRLF);
let boundary_incr = '';
if (bounce_html_lines.length > 1) {
boundary_incr = 'a';
bounce_body.push(`--${boundary}${CRLF}`);
bounce_body.push(`Content-Type: multipart/related; boundary="${boundary}${boundary_incr}"${CRLF}`);
bounce_body.push(CRLF);
bounce_body.push(`--${boundary}${boundary_incr}${CRLF}`);
boundary_incr = 'b';
bounce_body.push(`Content-Type: multipart/alternative; boundary="${boundary}${boundary_incr}"${CRLF}`);
bounce_body.push(CRLF);
}
bounce_body.push(`--${boundary}${boundary_incr}${CRLF}`);
bounce_body.push(`Content-Type: text/plain; charset=us-ascii${CRLF}`);
bounce_body.push(CRLF);
bounce_body_lines.forEach(line => {
bounce_body.push(`${line}${CRLF}`);
});
bounce_body.push(CRLF);
if (bounce_html_lines.length > 1) {
bounce_body.push(`--${boundary}${boundary_incr}${CRLF}`);
bounce_body.push(`Content-Type: text/html; charset=us-ascii${CRLF}`);
bounce_body.push(CRLF);
bounce_html_lines.forEach(line => {
bounce_body.push(`${line}${CRLF}`);
});
bounce_body.push(CRLF);
bounce_body.push(`--${boundary}${boundary_incr}--${CRLF}`);
if (bounce_image_lines.length > 1) {
boundary_incr = 'a';
bounce_body.push(`--${boundary}${boundary_incr}${CRLF}`);
//bounce_body.push(`Content-Type: text/html; charset=us-ascii${CRLF}`);
//bounce_body.push(CRLF);
bounce_image_lines.forEach(line => {
bounce_body.push(`${line}${CRLF}`);
});
bounce_body.push(CRLF);
bounce_body.push(`--${boundary}${boundary_incr}--${CRLF}`);
}
}
bounce_body.push(`--${boundary}${CRLF}`);
bounce_body.push(`Content-type: message/delivery-status${CRLF}`);
bounce_body.push(CRLF);
if (originalMessageId != '') {
bounce_body.push(`Original-Envelope-Id: ${originalMessageId.replace(/(\r?\n)*$/, '')}${CRLF}`);
}
bounce_body.push(`Reporting-MTA: dns;${net_utils.get_primary_host_name()}${CRLF}`);
if (this.todo.queue_time) {
bounce_body.push(`Arrival-Date: ${utils.date_to_str(new Date(this.todo.queue_time))}${CRLF}`);
}
this.todo.rcpt_to.forEach(rcpt_to => {
bounce_body.push(CRLF);
bounce_body.push(`Final-Recipient: rfc822;${rcpt_to.address()}${CRLF}`);
let dsn_action = null;
if (rcpt_to.dsn_action) {
dsn_action = rcpt_to.dsn_action;
}
else if (rcpt_to.dsn_code) {
if (/^5/.exec(rcpt_to.dsn_code)) {
dsn_action = 'failed';
}
else if (/^4/.exec(rcpt_to.dsn_code)) {
dsn_action = 'delayed';
}
else if (/^2/.exec(rcpt_to.dsn_code)) {
dsn_action = 'delivered';
}
}
else if (rcpt_to.dsn_smtp_code) {
if (/^5/.exec(rcpt_to.dsn_smtp_code)) {
dsn_action = 'failed';
}
else if (/^4/.exec(rcpt_to.dsn_smtp_code)) {
dsn_action = 'delayed';
}
else if (/^2/.exec(rcpt_to.dsn_smtp_code)) {
dsn_action = 'delivered';
}
}
if (dsn_action != null) {
bounce_body.push(`Action: ${dsn_action}${CRLF}`);
}
if (rcpt_to.dsn_status) {
let { dsn_status } = rcpt_to;
if (rcpt_to.dsn_code || rcpt_to.dsn_msg) {
dsn_status += " (";
if (rcpt_to.dsn_code) {
dsn_status += rcpt_to.dsn_code;
}
if (rcpt_to.dsn_code || rcpt_to.dsn_msg) {
dsn_status += " ";
}
if (rcpt_to.dsn_msg) {
dsn_status += rcpt_to.dsn_msg;
}
dsn_status += ")";
}
bounce_body.push(`Status: ${dsn_status}${CRLF}`);
}
if (rcpt_to.dsn_remote_mta) {
bounce_body.push(`Remote-MTA: ${rcpt_to.dsn_remote_mta}${CRLF}`);
}
let diag_code = null;
if (rcpt_to.dsn_smtp_code || rcpt_to.dsn_smtp_extc || rcpt_to.dsn_smtp_response) {
diag_code = "smtp;";
if (rcpt_to.dsn_smtp_code) {
diag_code += `${rcpt_to.dsn_smtp_code} `;
}
if (rcpt_to.dsn_smtp_extc) {
diag_code += `${rcpt_to.dsn_smtp_extc} `;
}
if (rcpt_to.dsn_smtp_response) {
diag_code += `${rcpt_to.dsn_smtp_response} `;
}
}
if (diag_code != null) {
bounce_body.push(`Diagnostic-Code: ${diag_code}${CRLF}`);
}
});
bounce_body.push(CRLF);
bounce_body.push(`--${boundary}${CRLF}`);
bounce_body.push(`Content-Description: Undelivered Message Headers${CRLF}`);
bounce_body.push(`Content-Type: text/rfc822-headers${CRLF}`);
bounce_body.push(CRLF);
header.header_list.forEach(line => {
bounce_body.push(line);
});
bounce_body.push(CRLF);
bounce_body.push(`--${boundary}--${CRLF}`);
cb(null, bounce_body);
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
populate_bounce_message_with_headers
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
bounce (err, opts) {
this.loginfo(`bouncing mail: ${err}`);
if (!this.todo) {
this.once('ready', () => { this._bounce(err, opts); });
return;
}
this._bounce(err, opts);
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
bounce
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
_bounce (err, opts) {
err = new Error(err);
if (opts) {
err.mx = opts.mx;
err.deferred_rcpt = opts.fail_recips;
err.bounced_rcpt = opts.bounce_recips;
}
this.bounce_error = err;
plugins.run_hooks("bounce", this, err);
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
_bounce
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
bounce_respond (retval, msg) {
if (retval !== constants.cont) {
this.loginfo(`Plugin responded with: ${retval}. Not sending bounce.`);
return this.discard(); // calls next_cb
}
const self = this;
const err = this.bounce_error;
if (!this.todo.mail_from.user) {
// double bounce - mail was already a bounce
return this.double_bounce("Mail was already a bounce");
}
const from = new Address ('<>');
const recip = new Address (this.todo.mail_from.user, this.todo.mail_from.host);
this.populate_bounce_message(from, recip, err, function (err2, data_lines) {
if (err2) {
return self.double_bounce(`Error populating bounce message: ${err2}`);
}
outbound.send_email(from, recip, data_lines.join(''), (code, msg2) => {
if (code === constants.deny) {
// failed to even queue the mail
return self.double_bounce("Unable to queue the bounce message. Not sending bounce!");
}
self.discard();
}, {origin: this});
});
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
bounce_respond
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
double_bounce (err) {
this.lognotice(`Double bounce: ${err}`);
fs.unlink(this.path, () => {});
this.next_cb();
// TODO: fill this in... ?
// One strategy is perhaps log to an mbox file. What do other servers do?
// Another strategy might be delivery "plugins" to cope with this.
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
double_bounce
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
delivered (ip, port, mode, host, response, ok_recips, fail_recips, bounce_recips, secured, authenticated) {
const delay = (Date.now() - this.todo.queue_time)/1000;
this.lognotice({
'delivered file': this.filename,
'domain': this.todo.domain,
host,
ip,
port,
mode,
'tls': ((secured) ? 'Y' : 'N'),
'auth': ((authenticated) ? 'Y' : 'N'),
response,
delay,
'fails': this.num_failures,
'rcpts': `${ok_recips.length}/${fail_recips.length}/${bounce_recips.length}`
});
plugins.run_hooks("delivered", this, [host, ip, response, delay, port, mode, ok_recips, secured, authenticated]);
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
delivered
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
discard () {
this.refcount--;
if (this.refcount === 0) {
// Remove the file.
fs.unlink(this.path, () => {});
this.next_cb();
}
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
discard
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
convert_temp_failed_to_bounce (err, extra) {
this.todo.rcpt_to.forEach(rcpt_to => {
rcpt_to.dsn_action = 'failed';
if (rcpt_to.dsn_status) {
rcpt_to.dsn_status = (`${rcpt_to.dsn_status}`).replace(/^4/, '5');
}
});
return this.bounce(err, extra);
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
convert_temp_failed_to_bounce
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
temp_fail (err, extra) {
logger.debug(this, `Temp fail for: ${err}`);
this.num_failures++;
// Test for max failures which is configurable.
if (this.num_failures > (obc.cfg.temp_fail_intervals.length)) {
return this.convert_temp_failed_to_bounce(`Too many failures (${err})`, extra);
}
const delay = obc.cfg.temp_fail_intervals[this.num_failures-1];
plugins.run_hooks('deferred', this, {delay, err});
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
temp_fail
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
deferred_respond (retval, msg, params) {
if (retval !== constants.cont && retval !== constants.denysoft) {
this.loginfo(`plugin responded with: ${retval}. Not deferring. Deleting mail.`);
return this.discard(); // calls next_cb
}
let delay = params.delay * 1000;
if (retval === constants.denysoft) {
delay = parseInt(msg, 10) * 1000;
}
this.loginfo(`Temp failing ${this.filename} for ${delay/1000} seconds: ${params.err}`);
const parts = _qfile.parts(this.filename);
parts.next_attempt = Date.now() + delay;
parts.attempts = this.num_failures;
const new_filename = _qfile.name(parts);
fs.rename(this.path, path.join(queue_dir, new_filename), err => {
if (err) {
return this.bounce(`Error re-queueing email: ${err}`);
}
this.path = path.join(queue_dir, new_filename);
this.filename = new_filename;
this.next_cb();
temp_fail_queue.add(this.filename, delay, () => { delivery_queue.push(this); });
});
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
deferred_respond
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
delivered_respond (retval, msg) {
if (retval !== constants.cont && retval !== constants.ok) {
this.logwarn(
"delivered plugin responded",
{ retval, msg }
);
}
this.discard();
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
delivered_respond
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
get_force_tls (mx) {
if (!mx.exchange) return false
if (!obtls.cfg.force_tls_hosts) return false
if (net_utils.ip_in_list(obtls.cfg.force_tls_hosts, mx.exchange)) {
this.logdebug(`Forcing TLS for host ${mx.exchange}`);
return true;
}
if (mx.from_dns) {
// the MX was looked up in DNS and already resolved to IP(s).
// This checks the hostname.
if (net_utils.ip_in_list(obtls.cfg.force_tls_hosts, mx.from_dns)) {
this.logdebug(`Forcing TLS for host ${mx.from_dns}`);
return true;
}
}
if (net_utils.ip_in_list(obtls.cfg.force_tls_hosts, this.todo.domain)) {
this.logdebug(`Forcing TLS for domain ${this.todo.domain}`);
return true;
}
return false
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
get_force_tls
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
sort_mx (mx_list) {
// MXs must be sorted by priority.
const sorted = mx_list.sort((a,b) => a.priority - b.priority);
// Matched priorities must be randomly shuffled.
// This isn't a very good shuffle but it'll do for now.
for (let i=0,l=sorted.length-1; i<l; i++) {
if (sorted[i].priority === sorted[i+1].priority) {
if (Math.round(Math.random())) { // 0 or 1
const j = sorted[i];
sorted[i] = sorted[i+1];
sorted[i+1] = j;
}
}
}
return sorted;
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
sort_mx
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
split_to_new_recipients (recipients, response, cb) {
const hmail = this;
if (recipients.length === hmail.todo.rcpt_to.length) {
// Split to new for no reason - increase refcount and return self
hmail.refcount++;
return cb(hmail);
}
const fname = _qfile.name();
const tmp_path = path.join(queue_dir, `${_qfile.platformDOT}${fname}`);
const ws = new FsyncWriteStream(tmp_path, { flags: constants.WRITE_EXCL });
function err_handler (err, location) {
logger.error(this, `Error while splitting to new recipients (${location}): ${err}`);
hmail.todo.rcpt_to.forEach(rcpt => {
hmail.extend_rcpt_with_dsn(rcpt, DSN.sys_unspecified(`Error splitting to new recipients: ${err}`));
});
hmail.bounce(`Error splitting to new recipients: ${err}`);
}
ws.on('error', err => { err_handler(err, "tmp file writer");});
let writing = false;
function write_more () {
if (writing) return;
writing = true;
const rs = hmail.data_stream();
rs.pipe(ws, {end: false});
rs.on('error', err => {
err_handler(err, "hmail.data_stream reader");
});
rs.on('end', () => {
ws.on('close', () => {
const dest_path = path.join(queue_dir, fname);
fs.rename(tmp_path, dest_path, err => {
if (err) {
err_handler(err, "tmp file rename");
return
}
const split_mail = new HMailItem (fname, dest_path, hmail.notes);
split_mail.once('ready', () => {
cb(split_mail);
});
});
});
ws.destroySoon();
});
}
ws.on('error', err => {
logger.error(this, `Unable to write queue file (${fname}): ${err}`);
ws.destroy();
hmail.todo.rcpt_to.forEach(rcpt => {
hmail.extend_rcpt_with_dsn(rcpt, DSN.sys_unspecified(`Error re-queueing some recipients: ${err}`));
});
hmail.bounce(`Error re-queueing some recipients: ${err}`);
});
const new_todo = JSON.parse(JSON.stringify(hmail.todo));
new_todo.rcpt_to = recipients;
outbound.build_todo(new_todo, ws, write_more);
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
split_to_new_recipients
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
function err_handler (err, location) {
logger.error(this, `Error while splitting to new recipients (${location}): ${err}`);
hmail.todo.rcpt_to.forEach(rcpt => {
hmail.extend_rcpt_with_dsn(rcpt, DSN.sys_unspecified(`Error splitting to new recipients: ${err}`));
});
hmail.bounce(`Error splitting to new recipients: ${err}`);
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
err_handler
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
function write_more () {
if (writing) return;
writing = true;
const rs = hmail.data_stream();
rs.pipe(ws, {end: false});
rs.on('error', err => {
err_handler(err, "hmail.data_stream reader");
});
rs.on('end', () => {
ws.on('close', () => {
const dest_path = path.join(queue_dir, fname);
fs.rename(tmp_path, dest_path, err => {
if (err) {
err_handler(err, "tmp file rename");
return
}
const split_mail = new HMailItem (fname, dest_path, hmail.notes);
split_mail.once('ready', () => {
cb(split_mail);
});
});
});
ws.destroySoon();
});
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
write_more
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
function cram_md5_response (username, password, challenge) {
const crypto = require('crypto');
const c = utils.unbase64(challenge);
const hmac = crypto.createHmac('md5', password);
hmac.update(c);
const digest = hmac.digest('hex');
return utils.base64(`${username} ${digest}`);
}
|
Generates a bounce message
hmail.todo.rcpt_to objects should be extended as follows:
- dsn_action
- dsn_status
- dsn_code
- dsn_msg
- dsn_remote_mta
Upstream code/message goes here:
- dsn_smtp_code
- dsn_smtp_extc
- dsn_smtp_response
@param from
@param to
@param reason
@param header
@param cb - a callback for fn(err, message_body_lines)
|
cram_md5_response
|
javascript
|
haraka/Haraka
|
outbound/hmail.js
|
https://github.com/haraka/Haraka/blob/master/outbound/hmail.js
|
MIT
|
function getNextEntryFromPlaybook (ofType, playbook) {
if (playbook.length == 0) {
return false;
}
if (playbook[0].from == ofType) {
return playbook.shift();
}
return false;
}
|
runs a socket.write
@param socket
@param test
@param playbook
|
getNextEntryFromPlaybook
|
javascript
|
haraka/Haraka
|
test/fixtures/util_hmailitem.js
|
https://github.com/haraka/Haraka/blob/master/test/fixtures/util_hmailitem.js
|
MIT
|
function getGlobal() {
return this;
}
|
Default timeout interval in milliseconds for waitsFor() blocks.
|
getGlobal
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
spyObj = function() {
spyObj.wasCalled = true;
spyObj.callCount++;
var args = jasmine.util.argsToArray(arguments);
spyObj.mostRecentCall.object = this;
spyObj.mostRecentCall.args = args;
spyObj.argsForCall.push(args);
spyObj.calls.push({object: this, args: args});
return spyObj.plan.apply(this, arguments);
}
|
Resets all of a spy's the tracking variables so that it can be used again.
@example
spyOn(foo, 'bar');
foo.bar();
expect(foo.bar.callCount).toEqual(1);
foo.bar.reset();
expect(foo.bar.callCount).toEqual(0);
|
spyObj
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
spyOn = function(obj, methodName) {
return jasmine.getEnv().currentSpec.spyOn(obj, methodName);
}
|
Function that installs a spy on an existing object's method name. Used within a Spec to create a spy.
@example
// spy example
var foo = {
not: function(bool) { return !bool; }
}
spyOn(foo, 'not'); // actual foo.not will not be called, execution stops
@see jasmine.createSpy
@param obj
@param methodName
@returns a Jasmine spy that can be chained with all spy methods
|
spyOn
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
it = function(desc, func) {
return jasmine.getEnv().it(desc, func);
}
|
Creates a Jasmine spec that will be added to the current suite.
// TODO: pending tests
@example
it('should be true', function() {
expect(true).toEqual(true);
});
@param {String} desc description of this specification
@param {Function} func defines the preconditions and expectations of the spec
|
it
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
xit = function(desc, func) {
return jasmine.getEnv().xit(desc, func);
}
|
Creates a <em>disabled</em> Jasmine spec.
A convenience method that allows existing specs to be disabled temporarily during development.
@param {String} desc description of this specification
@param {Function} func defines the preconditions and expectations of the spec
|
xit
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
expect = function(actual) {
return jasmine.getEnv().currentSpec.expect(actual);
}
|
Starts a chain for a Jasmine expectation.
It is passed an Object that is the actual value and should chain to one of the many
jasmine.Matchers functions.
@param {Object} actual Actual value to test against and expected value
|
expect
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) {
jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments);
}
|
Waits for the latchFunction to return true before proceeding to the next block.
@param {Function} latchFunction
@param {String} optional_timeoutMessage
@param {Number} optional_timeout
|
waitsFor
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
describe = function(description, specDefinitions) {
return jasmine.getEnv().describe(description, specDefinitions);
}
|
Defines a suite of specifications.
Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared
are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization
of setup in some tests.
@example
// TODO: a simple suite
// TODO: a simple suite with a nested describe block
@param {String} description A string, usually the class under test.
@param {Function} specDefinitions function that defines several specs.
|
describe
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
xdescribe = function(description, specDefinitions) {
return jasmine.getEnv().xdescribe(description, specDefinitions);
}
|
Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development.
@param {String} description A string, usually the class under test.
@param {Function} specDefinitions function that defines several specs.
|
xdescribe
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
function tryIt(f) {
try {
return f();
} catch(e) {
}
return null;
}
|
Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development.
@param {String} description A string, usually the class under test.
@param {Function} specDefinitions function that defines several specs.
|
tryIt
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
hasKey = function(obj, keyName) {
return obj !== null && obj[keyName] !== jasmine.undefined;
}
|
Register a reporter to receive status updates from Jasmine.
@param {jasmine.Reporter} reporter An object which will receive status updates.
|
hasKey
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
onComplete = function () {
if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) {
completedSynchronously = true;
return;
}
if (self.blocks[self.index].abort) {
self.abort = true;
}
self.offset = 0;
self.index++;
var now = new Date().getTime();
if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) {
self.env.lastUpdate = now;
self.env.setTimeout(function() {
self.next_();
}, 0);
} else {
if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) {
goAgain = true;
} else {
self.next_();
}
}
}
|
Formats a value in a nice, human-readable string.
@param value
|
onComplete
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
newMatchersClass = function() {
parent.apply(this, arguments);
}
|
Waits for the latchFunction to return true before proceeding to the next block.
@param {Function} latchFunction
@param {String} optional_timeoutMessage
@param {Number} optional_timeout
|
newMatchersClass
|
javascript
|
PaulKinlan/WebIntents
|
lib/jasmine/jasmine.js
|
https://github.com/PaulKinlan/WebIntents/blob/master/lib/jasmine/jasmine.js
|
Apache-2.0
|
constructor() {
super();
// this.attachShadow({mode: "open"});
// this.shadowRoot.innerHTML = `:host { display: none }`;
}
|
Special type of delayed element that actually triggers an action when it's current
|
constructor
|
javascript
|
LeaVerou/inspire.js
|
plugins/delayed-actions/plugin.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/delayed-actions/plugin.js
|
MIT
|
static get observedAttributes() {
return ["type", "target", "class"];
}
|
Special type of delayed element that actually triggers an action when it's current
|
observedAttributes
|
javascript
|
LeaVerou/inspire.js
|
plugins/delayed-actions/plugin.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/delayed-actions/plugin.js
|
MIT
|
get type() {
return this.getAttribute("type");
}
|
Special type of delayed element that actually triggers an action when it's current
|
type
|
javascript
|
LeaVerou/inspire.js
|
plugins/delayed-actions/plugin.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/delayed-actions/plugin.js
|
MIT
|
set type(type) {
this.setAttribute("type", type);
}
|
Special type of delayed element that actually triggers an action when it's current
|
type
|
javascript
|
LeaVerou/inspire.js
|
plugins/delayed-actions/plugin.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/delayed-actions/plugin.js
|
MIT
|
get target() {
return this.getAttribute("target");
}
|
Special type of delayed element that actually triggers an action when it's current
|
target
|
javascript
|
LeaVerou/inspire.js
|
plugins/delayed-actions/plugin.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/delayed-actions/plugin.js
|
MIT
|
set target(target) {
this.setAttribute("target", target);
}
|
Special type of delayed element that actually triggers an action when it's current
|
target
|
javascript
|
LeaVerou/inspire.js
|
plugins/delayed-actions/plugin.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/delayed-actions/plugin.js
|
MIT
|
trigger() {
if (this.#triggered > 0 && this.hasAttribute("once")) {
return;
}
this.#triggered++;
let type = this.type || "click";
let slide = this.closest(".slide");
let targetSelector = this.target;
if (!targetSelector) {
throw new InvalidStateError("No target specified");
}
let target = slide.querySelector(targetSelector);
if (target) {
// TODO use correct constructor
target.dispatchEvent(new Event(type));
}
}
|
Special type of delayed element that actually triggers an action when it's current
|
trigger
|
javascript
|
LeaVerou/inspire.js
|
plugins/delayed-actions/plugin.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/delayed-actions/plugin.js
|
MIT
|
connectedCallback() {
this.classList.add("delayed");
this.innerHTML = `<slot></slot>`;
}
|
Special type of delayed element that actually triggers an action when it's current
|
connectedCallback
|
javascript
|
LeaVerou/inspire.js
|
plugins/delayed-actions/plugin.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/delayed-actions/plugin.js
|
MIT
|
attributeChangedCallback(name, oldValue, newValue) {
if (name === "class") {
if (this.classList.contains("current")) {
this.trigger();
}
}
}
|
Special type of delayed element that actually triggers an action when it's current
|
attributeChangedCallback
|
javascript
|
LeaVerou/inspire.js
|
plugins/delayed-actions/plugin.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/delayed-actions/plugin.js
|
MIT
|
static init (container) {
if (!container.demo) {
container.demo = new LiveDemo(container);
}
return container.demo;
}
|
/";
}
if (this.style.sheet) {
let scope = this.editors.css.textarea.getAttribute("data-scope") || `#${this.container.id} .demo-target `;
for (let rule of this.style.sheet.cssRules) {
LiveDemo.scopeRule(rule, this.container, scope);
}
}
else {
console.log("FAIL on", this.container.id, this.style.outerHTML, this.style.media);
}
}
}
}
updateIframe() {
this.iframe.srcdoc = this.getHTMLPage();
return new Promise(resolve => {
this.iframe.onload = resolve;
}).then(evt => {
this.style = $("style#live", this.iframe.contentDocument);
return evt;
});
}
get html() {
if (!this.editors.markup) {
// No HTML editor
return "";
}
var editor = this.editors.markup.source;
if (editor) {
let prepend = editor.dataset.prepend? editor.dataset.prepend + "\n" : "";
let append = editor.dataset.append? "\n" + editor.dataset.append : "";
return `${prepend}${editor.value}${append}`;
}
else {
return this.element.innerHTML;
}
}
get css() {
return this.editors.css?.value;
}
get js() {
return (this.editors.js || this.editors.javascript)?.value;
}
get title() {
return (this.container.title || this.container.dataset.title || "") + " Demo";
}
getHTMLPage({title, inline} = {}) {
return LiveDemo.getHTMLPage({
html: this.html,
css: this.css,
extraCSS: this.extraCSS,
baseCSS: this.baseCSS,
js: this.js,
title: title || this.title,
inline,
noBase: this.noBase,
module: /^\s*import/m.test(this.js),
});
}
openEditor(id) {
for (let i in this.editors) {
this.editors[i].wrapper.classList.toggle("collapsed", i !== id);
}
}
async play (script) {
if (!this.replayer) {
let Replayer = await import("https://rety.verou.me/src/replayer.js").then(m => m.default);
// let editors = Object.fromEntries(Object.entries(this.editors).map(([id, editor]) => [id, editor.textarea]));
let editors = Object.values(this.editors).map(editor => editor.textarea);
this.replayer = new Replayer(editors, this.replayerOptions);
}
return this.replayer.runAll(script);
}
static createEditor(container, label, o = {}) {
var lang = o.lang || label;
let textarea = create({
html: `<textarea id="${container.id}-${label}-editor" class="language-${lang} editor" data-lang="${lang}">${o.fromSource()}</textarea>`,
in: o.container || container,
value: o.fromSource(),
events: {
input: o.toSource
}
});
return new Prism.Live(textarea);
}
static createURL(html, useDataURI, type = "text/html") {
html = html.replace(/​/g, "");
if (useDataURI) {
return `data:${type},${encodeURIComponent(html)}`;
}
else {
return URL.createObjectURL(new Blob([html], {type}));
}
}
static scopeRule(rule, container, scope) {
let selector = rule.selectorText;
if (rule.cssRules) {
// If this rule contains rules, scope those too
// Mainly useful for @supports and @media
for (let innerRule of rule.cssRules) {
LiveDemo.scopeRule(innerRule, container, scope);
}
}
if (selector && rule instanceof CSSStyleRule) {
let shouldScope = !(
selector.includes("#") // don't do anything if the selector already contains an id
|| [":root", "body"].includes(selector) // don't scope these
);
let env = {context: this, rule, container, scope, shouldScope};
LiveDemo.hooks.run("scoperule", env);
if ("returnValue" in env) {
return env.returnValue;
}
if (env.shouldScope && selector.indexOf(scope) !== 0) {
rule.selectorText = selector.split(",").map(s => `${scope} ${s}`).join(", ");
}
}
}
static getHTMLPage ({html="", css="", baseCSS = LiveDemo.baseCSS, extraCSS="", js="", title="Demo", inline = true, noBase = false, module = false} = {}) {
baseCSS = baseCSS + (baseCSS && extraCSS? "\n" : "") + extraCSS;
// Hoist imports to top
let imports = [];
baseCSS.replace(/@import .+;/g, $0 => {
imports.push($0);
return "";
});
if (imports.length > 0) {
baseCSS = [...imports, baseCSS].join("\n");
}
if (css !== "undefined") {
css = `<style id=live>
${css}
</style>`;
}
return `<!DOCTYPE html>
<html lang="en">
<head>
${noBase? "" : `<base href="${location.href}" />`}
<meta charset="UTF-8">
<title>${title}</title>
<style>
/* Base styles, not related to demo
|
init
|
javascript
|
LeaVerou/inspire.js
|
plugins/live-demo/live-demo.js
|
https://github.com/LeaVerou/inspire.js/blob/master/plugins/live-demo/live-demo.js
|
MIT
|
hashchange(evt) {
_.goto(location.hash.substr(1) || 0);
}
|
Keyboard navigation
Home : First slide
End : Last slide
Space/Up/Right arrow : Next item/slide
Ctrl + Space/Up/Right arrow : Next slide
Down/Left arrow : Previous item/slide
Ctrl + Down/Left arrow : Previous slide
(Shift instead of Ctrl works too)
|
hashchange
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
end() {
_.goto(_.slides.length - 1);
}
|
Keyboard navigation
Home : First slide
End : Last slide
Space/Up/Right arrow : Next item/slide
Ctrl + Space/Up/Right arrow : Next slide
Down/Left arrow : Previous item/slide
Ctrl + Down/Left arrow : Previous slide
(Shift instead of Ctrl works too)
|
end
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
next (hard) {
if (!hard && _.items.length) {
_.nextItem();
}
else {
_.goto(_.index + 1);
_.item = 0;
// Mark all items as not displayed, if there are any
_.items.forEach(item => item.classList.remove("displayed", "current"));
}
}
|
@param hard {Boolean} Whether to advance to the next slide (true) or
just the next step (which could very well be showing a list item)
|
next
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
nextItem() {
this.delayedLast = this.currentSlide.matches(".delayed-last, .delayed-last *");
if (_.item < _.items.length || this.delayedLast && _.item === _.items.length) {
_.gotoItem(++_.item);
}
else {
// Finished all slide items, go to next slide
_.item = 0;
_.next(true);
}
}
|
@param hard {Boolean} Whether to advance to the next slide (true) or
just the next step (which could very well be showing a list item)
|
nextItem
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
previous (hard) {
if (!hard && _.item > 0) {
_.previousItem();
}
else {
_.goto(_.index - 1);
_.item = _.items.length;
// Mark all items as displayed, if there are any
if (_.items.length) {
_.items.forEach(item => item.classList.add("displayed"));
_.items.forEach(item => item.classList.remove("future"));
// Mark the last one as current
let lastItem = _.items[_.items.length - 1];
lastItem.classList.remove("displayed");
lastItem.classList.add("current");
}
}
}
|
@param hard {Boolean} Whether to advance to the next slide (true) or
just the next step (which could very well be showing a list item)
|
previous
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
async on (ref) {
if (/^[\w-]+$/.test(ref)) {
console.warn("Inspire.on() expects a selector now, not an id");
ref = "#" + ref;
}
if (_.currentSlide === ref || _.currentSlide?.matches(ref)) {
return _.currentSlide;
}
return new Promise(resolve => {
let callback = evt => {
if (ref === evt.target || typeof ref === "string" && evt.target.matches(ref)) {
resolve(evt.target);
evt.target.removeEventListener("slidechange", callback);
}
};
document.body.addEventListener("slidechange", callback);
});
}
|
Run code once on a slide when the slide is active
@param {String | HTMLElement} ref CSS selector or slide element
@returns {Promise<HTMLElement>} The slide that was activated
|
on
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
callback = evt => {
if (ref === evt.target || typeof ref === "string" && evt.target.matches(ref)) {
resolve(evt.target);
evt.target.removeEventListener("slidechange", callback);
}
}
|
Run code once on a slide when the slide is active
@param {String | HTMLElement} ref CSS selector or slide element
@returns {Promise<HTMLElement>} The slide that was activated
|
callback
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
callback = evt => {
if (ref === evt.target || typeof ref === "string" && evt.target.matches(ref)) {
resolve(evt.target);
evt.target.removeEventListener("slidechange", callback);
}
}
|
Run code once on a slide when the slide is active
@param {String | HTMLElement} ref CSS selector or slide element
@returns {Promise<HTMLElement>} The slide that was activated
|
callback
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
for (selector, callback) {
let slides = $$(`.slide:has(${ selector})`);
for (let slide of slides) {
_.on(slide).then(slide => {
for (let element of $$(selector, slide)) {
callback(element);
}
});
}
return slides;
}
|
Run code for specific elements, once, only when the slide they appear in becomes active
@param {string} selector
@param {function} callback
@returns {HTMLElement[]} The slides that contain elements matching the selector
|
for
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
updateItems () {
_.items = $$(".delayed, .delayed-children > *", _.currentSlide);
_.items = _.items.sort((a, b) => {
return (a.getAttribute("data-index") || 0) - (b.getAttribute("data-index") || 0);
});
document.documentElement.style.setProperty("--total-items", _.items.length);
document.documentElement.classList.toggle("has-items", _.items.length > 0);
if (_.items.length > 0) {
document.documentElement.style.setProperty("--items-done", 0);
}
else {
document.documentElement.style.removeProperty("--items-done");
}
for (let element of _.items) {
if (!element.matches(".current, .displayed")) {
element.classList.add("future");
}
}
}
|
Run code for specific elements, once, only when the slide they appear in becomes active
@param {string} selector
@param {function} callback
@returns {HTMLElement[]} The slides that contain elements matching the selector
|
updateItems
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
adjustFontSize() {
let slide = _.currentSlide;
if (!slide || document.body.matches(".show-thumbnails") || slide.matches(".dont-resize")) {
return;
}
let cs = getComputedStyle(slide);
if (cs.getPropertyValue("--dont-resize") || cs.getPropertyValue("--font-sizing")?.trim() === "fixed" || cs.overflow === "hidden" || cs.overflow === "clip") {
return;
}
slide.style.fontSize = "";
if (slide.scrollHeight <= innerHeight && slide.scrollWidth <= innerWidth) {
return;
}
let size = parseInt(getComputedStyle(slide).fontSize);
let prev = {scrollHeight: slide.scrollHeight, scrollWidth: slide.scrollWidth};
let limit = 0;
for (
let factor = size / parseInt(getComputedStyle(document.body).fontSize);
(slide.scrollHeight > innerHeight || slide.scrollWidth > innerWidth) && factor >= 1;
factor -= .1
) {
slide.style.fontSize = factor * 100 + "%";
if (prev && prev.scrollHeight <= slide.scrollHeight && prev.scrollWidth <= slide.scrollWidth) {
// Reducing font-size is having no effect, abort mission after a few more tries
if (++limit > 5) {
break;
}
}
else {
limit = 0;
prev = null;
}
}
}
|
Go to a specific item in the current slide
@param {number} which 1-based index of the item to go to (0 means no items are current, just the slide itself)
|
adjustFontSize
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
get currentSlide() {
return _.slides?.[_.slide];
}
|
Go to a specific item in the current slide
@param {number} which 1-based index of the item to go to (0 means no items are current, just the slide itself)
|
currentSlide
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
getSlideById(id) {
id = id[0] === "#"? id : "#" + id;
return $(".slide" + id);
}
|
Go to a specific item in the current slide
@param {number} which 1-based index of the item to go to (0 means no items are current, just the slide itself)
|
getSlideById
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
getSlide(element) {
return element.closest(".slide");
}
|
Go to a specific item in the current slide
@param {number} which 1-based index of the item to go to (0 means no items are current, just the slide itself)
|
getSlide
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
function processAutoplayVideos (root) {
// Are there any autoplay videos?
let videos = root.matches("video[autoplay]") ? [root] : $$("video[autoplay]", root);
for (let video of videos) {
let delayed = video.closest(".delayed, .delayed-children > *");
if (delayed?.classList.contains("future")) {
// Video is in a future item, don't autoplay
continue;
}
if (video.currentTime > 0) {
video.currentTime = 0;
}
if (video.paused) {
video.play().catch(() => {
video.addEventListener("click", evt => {
video.play();
}, {once: true});
});
}
}
return videos;
}
|
Go to a specific item in the current slide
@param {number} which 1-based index of the item to go to (0 means no items are current, just the slide itself)
|
processAutoplayVideos
|
javascript
|
LeaVerou/inspire.js
|
src/inspire.js
|
https://github.com/LeaVerou/inspire.js/blob/master/src/inspire.js
|
MIT
|
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
|
Creates shortcut functions to a cipher's object interface.
@param {Cipher} cipher The cipher to create a helper for.
@return {Object} An object with encrypt and decrypt shortcut functions.
@static
@example
var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
|
selectCipherStrategy
|
javascript
|
tangyoha/telegram_media_downloader
|
module/static/aes/crypto-js-master/cipher-core.js
|
https://github.com/tangyoha/telegram_media_downloader/blob/master/module/static/aes/crypto-js-master/cipher-core.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.