id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
4,800
moleculerjs/moleculer
src/middlewares/circuit-breaker.js
success
function success(item, ctx) { item.count++; if (item.state === C.CIRCUIT_HALF_OPEN_WAIT) circuitClose(item, ctx); else checkThreshold(item, ctx); }
javascript
function success(item, ctx) { item.count++; if (item.state === C.CIRCUIT_HALF_OPEN_WAIT) circuitClose(item, ctx); else checkThreshold(item, ctx); }
[ "function", "success", "(", "item", ",", "ctx", ")", "{", "item", ".", "count", "++", ";", "if", "(", "item", ".", "state", "===", "C", ".", "CIRCUIT_HALF_OPEN_WAIT", ")", "circuitClose", "(", "item", ",", "ctx", ")", ";", "else", "checkThreshold", "(", "item", ",", "ctx", ")", ";", "}" ]
Increment request counter and switch CB to CLOSE if it is on HALF_OPEN_WAIT. @param {Object} item @param {Context} ctx
[ "Increment", "request", "counter", "and", "switch", "CB", "to", "CLOSE", "if", "it", "is", "on", "HALF_OPEN_WAIT", "." ]
f95aadc2d61b0d0e3c643a43c3ed28bca6425cde
https://github.com/moleculerjs/moleculer/blob/f95aadc2d61b0d0e3c643a43c3ed28bca6425cde/src/middlewares/circuit-breaker.js#L93-L100
4,801
moleculerjs/moleculer
src/middlewares/circuit-breaker.js
checkThreshold
function checkThreshold(item, ctx) { if (item.count >= item.opts.minRequestCount) { const rate = item.failures / item.count; if (rate >= item.opts.threshold) trip(item, ctx); } }
javascript
function checkThreshold(item, ctx) { if (item.count >= item.opts.minRequestCount) { const rate = item.failures / item.count; if (rate >= item.opts.threshold) trip(item, ctx); } }
[ "function", "checkThreshold", "(", "item", ",", "ctx", ")", "{", "if", "(", "item", ".", "count", ">=", "item", ".", "opts", ".", "minRequestCount", ")", "{", "const", "rate", "=", "item", ".", "failures", "/", "item", ".", "count", ";", "if", "(", "rate", ">=", "item", ".", "opts", ".", "threshold", ")", "trip", "(", "item", ",", "ctx", ")", ";", "}", "}" ]
Check circuit-breaker failure threshold of Endpoint @param {Object} item @param {Context} ctx
[ "Check", "circuit", "-", "breaker", "failure", "threshold", "of", "Endpoint" ]
f95aadc2d61b0d0e3c643a43c3ed28bca6425cde
https://github.com/moleculerjs/moleculer/blob/f95aadc2d61b0d0e3c643a43c3ed28bca6425cde/src/middlewares/circuit-breaker.js#L108-L114
4,802
moleculerjs/moleculer
src/middlewares/circuit-breaker.js
trip
function trip(item, ctx) { item.state = C.CIRCUIT_OPEN; item.ep.state = false; if (item.cbTimer) { clearTimeout(item.cbTimer); item.cbTimer = null; } item.cbTimer = setTimeout(() => halfOpen(item, ctx), item.opts.halfOpenTime); item.cbTimer.unref(); const rate = item.count > 0 ? item.failures / item.count : 0; logger.debug(`Circuit breaker has been opened on '${item.ep.name}' endpoint.`, { nodeID: item.ep.id, action: item.ep.action.name, failures: item.failures, count: item.count, rate }); broker.broadcast("$circuit-breaker.opened", { nodeID: item.ep.id, action: item.ep.action.name, failures: item.failures, count: item.count, rate }); }
javascript
function trip(item, ctx) { item.state = C.CIRCUIT_OPEN; item.ep.state = false; if (item.cbTimer) { clearTimeout(item.cbTimer); item.cbTimer = null; } item.cbTimer = setTimeout(() => halfOpen(item, ctx), item.opts.halfOpenTime); item.cbTimer.unref(); const rate = item.count > 0 ? item.failures / item.count : 0; logger.debug(`Circuit breaker has been opened on '${item.ep.name}' endpoint.`, { nodeID: item.ep.id, action: item.ep.action.name, failures: item.failures, count: item.count, rate }); broker.broadcast("$circuit-breaker.opened", { nodeID: item.ep.id, action: item.ep.action.name, failures: item.failures, count: item.count, rate }); }
[ "function", "trip", "(", "item", ",", "ctx", ")", "{", "item", ".", "state", "=", "C", ".", "CIRCUIT_OPEN", ";", "item", ".", "ep", ".", "state", "=", "false", ";", "if", "(", "item", ".", "cbTimer", ")", "{", "clearTimeout", "(", "item", ".", "cbTimer", ")", ";", "item", ".", "cbTimer", "=", "null", ";", "}", "item", ".", "cbTimer", "=", "setTimeout", "(", "(", ")", "=>", "halfOpen", "(", "item", ",", "ctx", ")", ",", "item", ".", "opts", ".", "halfOpenTime", ")", ";", "item", ".", "cbTimer", ".", "unref", "(", ")", ";", "const", "rate", "=", "item", ".", "count", ">", "0", "?", "item", ".", "failures", "/", "item", ".", "count", ":", "0", ";", "logger", ".", "debug", "(", "`", "${", "item", ".", "ep", ".", "name", "}", "`", ",", "{", "nodeID", ":", "item", ".", "ep", ".", "id", ",", "action", ":", "item", ".", "ep", ".", "action", ".", "name", ",", "failures", ":", "item", ".", "failures", ",", "count", ":", "item", ".", "count", ",", "rate", "}", ")", ";", "broker", ".", "broadcast", "(", "\"$circuit-breaker.opened\"", ",", "{", "nodeID", ":", "item", ".", "ep", ".", "id", ",", "action", ":", "item", ".", "ep", ".", "action", ".", "name", ",", "failures", ":", "item", ".", "failures", ",", "count", ":", "item", ".", "count", ",", "rate", "}", ")", ";", "}" ]
Trip the circuit-breaker, change the status to open @param {Object} item @param {Context} ctx
[ "Trip", "the", "circuit", "-", "breaker", "change", "the", "status", "to", "open" ]
f95aadc2d61b0d0e3c643a43c3ed28bca6425cde
https://github.com/moleculerjs/moleculer/blob/f95aadc2d61b0d0e3c643a43c3ed28bca6425cde/src/middlewares/circuit-breaker.js#L122-L137
4,803
moleculerjs/moleculer
src/middlewares/circuit-breaker.js
halfOpen
function halfOpen(item) { item.state = C.CIRCUIT_HALF_OPEN; item.ep.state = true; logger.debug(`Circuit breaker has been half-opened on '${item.ep.name}' endpoint.`, { nodeID: item.ep.id, action: item.ep.action.name }); broker.broadcast("$circuit-breaker.half-opened", { nodeID: item.ep.id, action: item.ep.action.name }); if (item.cbTimer) { clearTimeout(item.cbTimer); item.cbTimer = null; } }
javascript
function halfOpen(item) { item.state = C.CIRCUIT_HALF_OPEN; item.ep.state = true; logger.debug(`Circuit breaker has been half-opened on '${item.ep.name}' endpoint.`, { nodeID: item.ep.id, action: item.ep.action.name }); broker.broadcast("$circuit-breaker.half-opened", { nodeID: item.ep.id, action: item.ep.action.name }); if (item.cbTimer) { clearTimeout(item.cbTimer); item.cbTimer = null; } }
[ "function", "halfOpen", "(", "item", ")", "{", "item", ".", "state", "=", "C", ".", "CIRCUIT_HALF_OPEN", ";", "item", ".", "ep", ".", "state", "=", "true", ";", "logger", ".", "debug", "(", "`", "${", "item", ".", "ep", ".", "name", "}", "`", ",", "{", "nodeID", ":", "item", ".", "ep", ".", "id", ",", "action", ":", "item", ".", "ep", ".", "action", ".", "name", "}", ")", ";", "broker", ".", "broadcast", "(", "\"$circuit-breaker.half-opened\"", ",", "{", "nodeID", ":", "item", ".", "ep", ".", "id", ",", "action", ":", "item", ".", "ep", ".", "action", ".", "name", "}", ")", ";", "if", "(", "item", ".", "cbTimer", ")", "{", "clearTimeout", "(", "item", ".", "cbTimer", ")", ";", "item", ".", "cbTimer", "=", "null", ";", "}", "}" ]
Change circuit-breaker status to half-open @param {Object} item @param {Context} ctx
[ "Change", "circuit", "-", "breaker", "status", "to", "half", "-", "open" ]
f95aadc2d61b0d0e3c643a43c3ed28bca6425cde
https://github.com/moleculerjs/moleculer/blob/f95aadc2d61b0d0e3c643a43c3ed28bca6425cde/src/middlewares/circuit-breaker.js#L145-L157
4,804
moleculerjs/moleculer
src/middlewares/circuit-breaker.js
halfOpenWait
function halfOpenWait(item, ctx) { item.state = C.CIRCUIT_HALF_OPEN_WAIT; item.ep.state = false; // Anti-stick protection item.cbTimer = setTimeout(() => halfOpen(item, ctx), item.opts.halfOpenTime); item.cbTimer.unref(); }
javascript
function halfOpenWait(item, ctx) { item.state = C.CIRCUIT_HALF_OPEN_WAIT; item.ep.state = false; // Anti-stick protection item.cbTimer = setTimeout(() => halfOpen(item, ctx), item.opts.halfOpenTime); item.cbTimer.unref(); }
[ "function", "halfOpenWait", "(", "item", ",", "ctx", ")", "{", "item", ".", "state", "=", "C", ".", "CIRCUIT_HALF_OPEN_WAIT", ";", "item", ".", "ep", ".", "state", "=", "false", ";", "// Anti-stick protection", "item", ".", "cbTimer", "=", "setTimeout", "(", "(", ")", "=>", "halfOpen", "(", "item", ",", "ctx", ")", ",", "item", ".", "opts", ".", "halfOpenTime", ")", ";", "item", ".", "cbTimer", ".", "unref", "(", ")", ";", "}" ]
Change circuit-breaker status to half-open waiting. First request is invoked after half-open. @param {Object} item @param {Context} ctx
[ "Change", "circuit", "-", "breaker", "status", "to", "half", "-", "open", "waiting", ".", "First", "request", "is", "invoked", "after", "half", "-", "open", "." ]
f95aadc2d61b0d0e3c643a43c3ed28bca6425cde
https://github.com/moleculerjs/moleculer/blob/f95aadc2d61b0d0e3c643a43c3ed28bca6425cde/src/middlewares/circuit-breaker.js#L165-L172
4,805
moleculerjs/moleculer
src/middlewares/circuit-breaker.js
circuitClose
function circuitClose(item) { item.state = C.CIRCUIT_CLOSE; item.ep.state = true; item.failures = 0; item.count = 0; logger.debug(`Circuit breaker has been closed on '${item.ep.name}' endpoint.`, { nodeID: item.ep.id, action: item.ep.action.name }); broker.broadcast("$circuit-breaker.closed", { nodeID: item.ep.id, action: item.ep.action.name }); if (item.cbTimer) { clearTimeout(item.cbTimer); item.cbTimer = null; } }
javascript
function circuitClose(item) { item.state = C.CIRCUIT_CLOSE; item.ep.state = true; item.failures = 0; item.count = 0; logger.debug(`Circuit breaker has been closed on '${item.ep.name}' endpoint.`, { nodeID: item.ep.id, action: item.ep.action.name }); broker.broadcast("$circuit-breaker.closed", { nodeID: item.ep.id, action: item.ep.action.name }); if (item.cbTimer) { clearTimeout(item.cbTimer); item.cbTimer = null; } }
[ "function", "circuitClose", "(", "item", ")", "{", "item", ".", "state", "=", "C", ".", "CIRCUIT_CLOSE", ";", "item", ".", "ep", ".", "state", "=", "true", ";", "item", ".", "failures", "=", "0", ";", "item", ".", "count", "=", "0", ";", "logger", ".", "debug", "(", "`", "${", "item", ".", "ep", ".", "name", "}", "`", ",", "{", "nodeID", ":", "item", ".", "ep", ".", "id", ",", "action", ":", "item", ".", "ep", ".", "action", ".", "name", "}", ")", ";", "broker", ".", "broadcast", "(", "\"$circuit-breaker.closed\"", ",", "{", "nodeID", ":", "item", ".", "ep", ".", "id", ",", "action", ":", "item", ".", "ep", ".", "action", ".", "name", "}", ")", ";", "if", "(", "item", ".", "cbTimer", ")", "{", "clearTimeout", "(", "item", ".", "cbTimer", ")", ";", "item", ".", "cbTimer", "=", "null", ";", "}", "}" ]
Change circuit-breaker status to close @param {Object} item @param {Context} ctx
[ "Change", "circuit", "-", "breaker", "status", "to", "close" ]
f95aadc2d61b0d0e3c643a43c3ed28bca6425cde
https://github.com/moleculerjs/moleculer/blob/f95aadc2d61b0d0e3c643a43c3ed28bca6425cde/src/middlewares/circuit-breaker.js#L180-L194
4,806
moleculerjs/moleculer
src/middlewares/circuit-breaker.js
wrapCBMiddleware
function wrapCBMiddleware(handler, action) { // Merge action option and broker options const opts = Object.assign({}, this.options.circuitBreaker || {}, action.circuitBreaker || {}); if (opts.enabled) { return function circuitBreakerMiddleware(ctx) { // Get endpoint state item const ep = ctx.endpoint; const item = getEpState(ep, opts); // Handle half-open state in circuit breaker if (item.state == C.CIRCUIT_HALF_OPEN) { halfOpenWait(item, ctx); } // Call the handler return handler(ctx).then(res => { const item = getEpState(ep, opts); success(item, ctx); return res; }).catch(err => { if (opts.check && opts.check(err)) { // Failure if error is created locally (not came from a 3rd node error) if (item && (!err.nodeID || err.nodeID == ctx.nodeID)) { const item = getEpState(ep, opts); failure(item, err, ctx); } } return this.Promise.reject(err); }); }.bind(this); } return handler; }
javascript
function wrapCBMiddleware(handler, action) { // Merge action option and broker options const opts = Object.assign({}, this.options.circuitBreaker || {}, action.circuitBreaker || {}); if (opts.enabled) { return function circuitBreakerMiddleware(ctx) { // Get endpoint state item const ep = ctx.endpoint; const item = getEpState(ep, opts); // Handle half-open state in circuit breaker if (item.state == C.CIRCUIT_HALF_OPEN) { halfOpenWait(item, ctx); } // Call the handler return handler(ctx).then(res => { const item = getEpState(ep, opts); success(item, ctx); return res; }).catch(err => { if (opts.check && opts.check(err)) { // Failure if error is created locally (not came from a 3rd node error) if (item && (!err.nodeID || err.nodeID == ctx.nodeID)) { const item = getEpState(ep, opts); failure(item, err, ctx); } } return this.Promise.reject(err); }); }.bind(this); } return handler; }
[ "function", "wrapCBMiddleware", "(", "handler", ",", "action", ")", "{", "// Merge action option and broker options", "const", "opts", "=", "Object", ".", "assign", "(", "{", "}", ",", "this", ".", "options", ".", "circuitBreaker", "||", "{", "}", ",", "action", ".", "circuitBreaker", "||", "{", "}", ")", ";", "if", "(", "opts", ".", "enabled", ")", "{", "return", "function", "circuitBreakerMiddleware", "(", "ctx", ")", "{", "// Get endpoint state item", "const", "ep", "=", "ctx", ".", "endpoint", ";", "const", "item", "=", "getEpState", "(", "ep", ",", "opts", ")", ";", "// Handle half-open state in circuit breaker", "if", "(", "item", ".", "state", "==", "C", ".", "CIRCUIT_HALF_OPEN", ")", "{", "halfOpenWait", "(", "item", ",", "ctx", ")", ";", "}", "// Call the handler", "return", "handler", "(", "ctx", ")", ".", "then", "(", "res", "=>", "{", "const", "item", "=", "getEpState", "(", "ep", ",", "opts", ")", ";", "success", "(", "item", ",", "ctx", ")", ";", "return", "res", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "if", "(", "opts", ".", "check", "&&", "opts", ".", "check", "(", "err", ")", ")", "{", "// Failure if error is created locally (not came from a 3rd node error)", "if", "(", "item", "&&", "(", "!", "err", ".", "nodeID", "||", "err", ".", "nodeID", "==", "ctx", ".", "nodeID", ")", ")", "{", "const", "item", "=", "getEpState", "(", "ep", ",", "opts", ")", ";", "failure", "(", "item", ",", "err", ",", "ctx", ")", ";", "}", "}", "return", "this", ".", "Promise", ".", "reject", "(", "err", ")", ";", "}", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}", "return", "handler", ";", "}" ]
Middleware wrapper function @param {Function} handler @param {Action} action @returns {Function}
[ "Middleware", "wrapper", "function" ]
f95aadc2d61b0d0e3c643a43c3ed28bca6425cde
https://github.com/moleculerjs/moleculer/blob/f95aadc2d61b0d0e3c643a43c3ed28bca6425cde/src/middlewares/circuit-breaker.js#L203-L238
4,807
postmanlabs/newman
lib/run/options.js
function (value, options, callback) { /** * The post collection load handler. * * @param {?Error} err - An Error instance / null, passed from the collection loader. * @param {Object} collection - The collection / raw JSON object, passed from the collection loader. * @returns {*} */ var done = function (err, collection) { if (err) { return callback(err); } // ensure that the collection option is present before starting a run if (!_.isObject(collection)) { return callback(new Error(COLLECTION_LOAD_ERROR_MESSAGE)); } // ensure that the collection reference is an SDK instance // @todo - should this be handled by config loaders? collection = new Collection(Collection.isCollection(collection) ? // if the option contain an instance of collection, we simply clone it for future use // create a collection in case it is not one. user can send v2 JSON as a source and that will be // converted to a collection collection.toJSON() : collection); callback(null, collection); }; // if the collection has been specified as an object, convert to V2 if necessary and return the result if (_.isObject(value)) { return processCollection(value, done); } externalLoader('collection', value, options, function (err, data) { if (err) { return done(err); } if (!_.isObject(data)) { return done(new Error(COLLECTION_LOAD_ERROR_MESSAGE)); } return processCollection(data, done); }); }
javascript
function (value, options, callback) { /** * The post collection load handler. * * @param {?Error} err - An Error instance / null, passed from the collection loader. * @param {Object} collection - The collection / raw JSON object, passed from the collection loader. * @returns {*} */ var done = function (err, collection) { if (err) { return callback(err); } // ensure that the collection option is present before starting a run if (!_.isObject(collection)) { return callback(new Error(COLLECTION_LOAD_ERROR_MESSAGE)); } // ensure that the collection reference is an SDK instance // @todo - should this be handled by config loaders? collection = new Collection(Collection.isCollection(collection) ? // if the option contain an instance of collection, we simply clone it for future use // create a collection in case it is not one. user can send v2 JSON as a source and that will be // converted to a collection collection.toJSON() : collection); callback(null, collection); }; // if the collection has been specified as an object, convert to V2 if necessary and return the result if (_.isObject(value)) { return processCollection(value, done); } externalLoader('collection', value, options, function (err, data) { if (err) { return done(err); } if (!_.isObject(data)) { return done(new Error(COLLECTION_LOAD_ERROR_MESSAGE)); } return processCollection(data, done); }); }
[ "function", "(", "value", ",", "options", ",", "callback", ")", "{", "/**\n * The post collection load handler.\n *\n * @param {?Error} err - An Error instance / null, passed from the collection loader.\n * @param {Object} collection - The collection / raw JSON object, passed from the collection loader.\n * @returns {*}\n */", "var", "done", "=", "function", "(", "err", ",", "collection", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "// ensure that the collection option is present before starting a run", "if", "(", "!", "_", ".", "isObject", "(", "collection", ")", ")", "{", "return", "callback", "(", "new", "Error", "(", "COLLECTION_LOAD_ERROR_MESSAGE", ")", ")", ";", "}", "// ensure that the collection reference is an SDK instance", "// @todo - should this be handled by config loaders?", "collection", "=", "new", "Collection", "(", "Collection", ".", "isCollection", "(", "collection", ")", "?", "// if the option contain an instance of collection, we simply clone it for future use", "// create a collection in case it is not one. user can send v2 JSON as a source and that will be", "// converted to a collection", "collection", ".", "toJSON", "(", ")", ":", "collection", ")", ";", "callback", "(", "null", ",", "collection", ")", ";", "}", ";", "// if the collection has been specified as an object, convert to V2 if necessary and return the result", "if", "(", "_", ".", "isObject", "(", "value", ")", ")", "{", "return", "processCollection", "(", "value", ",", "done", ")", ";", "}", "externalLoader", "(", "'collection'", ",", "value", ",", "options", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "if", "(", "!", "_", ".", "isObject", "(", "data", ")", ")", "{", "return", "done", "(", "new", "Error", "(", "COLLECTION_LOAD_ERROR_MESSAGE", ")", ")", ";", "}", "return", "processCollection", "(", "data", ",", "done", ")", ";", "}", ")", ";", "}" ]
The collection file load helper for the current run. @param {Object|String} value - The collection, specified as a JSON object, or the path to it's file. @param {Object} options - The set of wrapped options. @param {Function} callback - The callback function invoked to mark the end of the collection load routine. @returns {*}
[ "The", "collection", "file", "load", "helper", "for", "the", "current", "run", "." ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/lib/run/options.js#L172-L216
4,808
postmanlabs/newman
lib/run/options.js
function (err, collection) { if (err) { return callback(err); } // ensure that the collection option is present before starting a run if (!_.isObject(collection)) { return callback(new Error(COLLECTION_LOAD_ERROR_MESSAGE)); } // ensure that the collection reference is an SDK instance // @todo - should this be handled by config loaders? collection = new Collection(Collection.isCollection(collection) ? // if the option contain an instance of collection, we simply clone it for future use // create a collection in case it is not one. user can send v2 JSON as a source and that will be // converted to a collection collection.toJSON() : collection); callback(null, collection); }
javascript
function (err, collection) { if (err) { return callback(err); } // ensure that the collection option is present before starting a run if (!_.isObject(collection)) { return callback(new Error(COLLECTION_LOAD_ERROR_MESSAGE)); } // ensure that the collection reference is an SDK instance // @todo - should this be handled by config loaders? collection = new Collection(Collection.isCollection(collection) ? // if the option contain an instance of collection, we simply clone it for future use // create a collection in case it is not one. user can send v2 JSON as a source and that will be // converted to a collection collection.toJSON() : collection); callback(null, collection); }
[ "function", "(", "err", ",", "collection", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "// ensure that the collection option is present before starting a run", "if", "(", "!", "_", ".", "isObject", "(", "collection", ")", ")", "{", "return", "callback", "(", "new", "Error", "(", "COLLECTION_LOAD_ERROR_MESSAGE", ")", ")", ";", "}", "// ensure that the collection reference is an SDK instance", "// @todo - should this be handled by config loaders?", "collection", "=", "new", "Collection", "(", "Collection", ".", "isCollection", "(", "collection", ")", "?", "// if the option contain an instance of collection, we simply clone it for future use", "// create a collection in case it is not one. user can send v2 JSON as a source and that will be", "// converted to a collection", "collection", ".", "toJSON", "(", ")", ":", "collection", ")", ";", "callback", "(", "null", ",", "collection", ")", ";", "}" ]
The post collection load handler. @param {?Error} err - An Error instance / null, passed from the collection loader. @param {Object} collection - The collection / raw JSON object, passed from the collection loader. @returns {*}
[ "The", "post", "collection", "load", "handler", "." ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/lib/run/options.js#L180-L199
4,809
postmanlabs/newman
lib/run/options.js
function (value, options, callback) { if (!value.length) { return callback(); // avoids empty string or array } if (Array.isArray(value) && value.length === 1) { return callback(null, value[0]); // avoids using multipleIdOrName strategy for a single item array } callback(null, value); }
javascript
function (value, options, callback) { if (!value.length) { return callback(); // avoids empty string or array } if (Array.isArray(value) && value.length === 1) { return callback(null, value[0]); // avoids using multipleIdOrName strategy for a single item array } callback(null, value); }
[ "function", "(", "value", ",", "options", ",", "callback", ")", "{", "if", "(", "!", "value", ".", "length", ")", "{", "return", "callback", "(", ")", ";", "// avoids empty string or array", "}", "if", "(", "Array", ".", "isArray", "(", "value", ")", "&&", "value", ".", "length", "===", "1", ")", "{", "return", "callback", "(", "null", ",", "value", "[", "0", "]", ")", ";", "// avoids using multipleIdOrName strategy for a single item array", "}", "callback", "(", "null", ",", "value", ")", ";", "}" ]
Helper function to sanitize folder option. @param {String[]|String} value - The list of folders to execute @param {Object} options - The set of wrapped options. @param {Function} callback - The callback function invoked to mark the end of the folder load routine. @returns {*}
[ "Helper", "function", "to", "sanitize", "folder", "option", "." ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/lib/run/options.js#L240-L250
4,810
postmanlabs/newman
lib/run/options.js
function (location, options, callback) { if (_.isArray(location)) { return callback(null, location); } util.fetch(location, function (err, data) { if (err) { return callback(err); } // Try loading as a JSON, fall-back to CSV. @todo: switch to file extension based loading. async.waterfall([ (cb) => { try { return cb(null, liquidJSON.parse(data.trim())); } catch (e) { return cb(null, undefined); // e masked to avoid displaying JSON parse errors for CSV files } }, (json, cb) => { if (json) { return cb(null, json); } // Wasn't JSON parseCsv(data, { columns: true, escape: '\\', cast: csvAutoParse, trim: true }, cb); } ], (err, parsed) => { if (err) { // todo: Log meaningful stuff here return callback(err); } callback(null, parsed); }); }); }
javascript
function (location, options, callback) { if (_.isArray(location)) { return callback(null, location); } util.fetch(location, function (err, data) { if (err) { return callback(err); } // Try loading as a JSON, fall-back to CSV. @todo: switch to file extension based loading. async.waterfall([ (cb) => { try { return cb(null, liquidJSON.parse(data.trim())); } catch (e) { return cb(null, undefined); // e masked to avoid displaying JSON parse errors for CSV files } }, (json, cb) => { if (json) { return cb(null, json); } // Wasn't JSON parseCsv(data, { columns: true, escape: '\\', cast: csvAutoParse, trim: true }, cb); } ], (err, parsed) => { if (err) { // todo: Log meaningful stuff here return callback(err); } callback(null, parsed); }); }); }
[ "function", "(", "location", ",", "options", ",", "callback", ")", "{", "if", "(", "_", ".", "isArray", "(", "location", ")", ")", "{", "return", "callback", "(", "null", ",", "location", ")", ";", "}", "util", ".", "fetch", "(", "location", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "// Try loading as a JSON, fall-back to CSV. @todo: switch to file extension based loading.", "async", ".", "waterfall", "(", "[", "(", "cb", ")", "=>", "{", "try", "{", "return", "cb", "(", "null", ",", "liquidJSON", ".", "parse", "(", "data", ".", "trim", "(", ")", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "cb", "(", "null", ",", "undefined", ")", ";", "// e masked to avoid displaying JSON parse errors for CSV files", "}", "}", ",", "(", "json", ",", "cb", ")", "=>", "{", "if", "(", "json", ")", "{", "return", "cb", "(", "null", ",", "json", ")", ";", "}", "// Wasn't JSON", "parseCsv", "(", "data", ",", "{", "columns", ":", "true", ",", "escape", ":", "'\\\\'", ",", "cast", ":", "csvAutoParse", ",", "trim", ":", "true", "}", ",", "cb", ")", ";", "}", "]", ",", "(", "err", ",", "parsed", ")", "=>", "{", "if", "(", "err", ")", "{", "// todo: Log meaningful stuff here", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "parsed", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
The iterationData loader module, with support for JSON or CSV data files. @param {String|Object[]} location - The path to the iteration data file for the current collection run, or the array of iteration data objects. @param {Object} options - The set of wrapped options. @param {Function} callback - The function invoked to indicate the end of the iteration data loading routine. @returns {*}
[ "The", "iterationData", "loader", "module", "with", "support", "for", "JSON", "or", "CSV", "data", "files", "." ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/lib/run/options.js#L261-L300
4,811
postmanlabs/newman
npm/publish-docs.js
function (next) { console.info(colors.yellow.bold('Generating and publishing documentation for postman-collection')); try { // go to the out directory and create a *new* Git repo cd('out/docs'); exec('git init'); // inside this git repo we'll pretend to be a new user // @todo - is this change perpetual? exec('git config user.name "Doc Publisher"'); exec('git config user.email "[email protected]"'); // The first and only commit to this new Git repo contains all the // files present with the commit message "Deploy to GitHub Pages". exec('git add .'); exec('git commit -m "Deploy to GitHub Pages"'); } catch (e) { console.error(e.stack || e); return next(e ? 1 : 0); } // Force push from the current repo's master branch to the remote // repo's gh-pages branch. (All previous history on the gh-pages branch // will be lost, since we are overwriting it.) We silence any output to // hide any sensitive credential data that might otherwise be exposed. config.silent = true; // this is apparently reset after exec exec('git push --force "[email protected]:postmanlabs/newman.git" master:gh-pages', next); }
javascript
function (next) { console.info(colors.yellow.bold('Generating and publishing documentation for postman-collection')); try { // go to the out directory and create a *new* Git repo cd('out/docs'); exec('git init'); // inside this git repo we'll pretend to be a new user // @todo - is this change perpetual? exec('git config user.name "Doc Publisher"'); exec('git config user.email "[email protected]"'); // The first and only commit to this new Git repo contains all the // files present with the commit message "Deploy to GitHub Pages". exec('git add .'); exec('git commit -m "Deploy to GitHub Pages"'); } catch (e) { console.error(e.stack || e); return next(e ? 1 : 0); } // Force push from the current repo's master branch to the remote // repo's gh-pages branch. (All previous history on the gh-pages branch // will be lost, since we are overwriting it.) We silence any output to // hide any sensitive credential data that might otherwise be exposed. config.silent = true; // this is apparently reset after exec exec('git push --force "[email protected]:postmanlabs/newman.git" master:gh-pages', next); }
[ "function", "(", "next", ")", "{", "console", ".", "info", "(", "colors", ".", "yellow", ".", "bold", "(", "'Generating and publishing documentation for postman-collection'", ")", ")", ";", "try", "{", "// go to the out directory and create a *new* Git repo", "cd", "(", "'out/docs'", ")", ";", "exec", "(", "'git init'", ")", ";", "// inside this git repo we'll pretend to be a new user", "// @todo - is this change perpetual?", "exec", "(", "'git config user.name \"Doc Publisher\"'", ")", ";", "exec", "(", "'git config user.email \"[email protected]\"'", ")", ";", "// The first and only commit to this new Git repo contains all the", "// files present with the commit message \"Deploy to GitHub Pages\".", "exec", "(", "'git add .'", ")", ";", "exec", "(", "'git commit -m \"Deploy to GitHub Pages\"'", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "e", ".", "stack", "||", "e", ")", ";", "return", "next", "(", "e", "?", "1", ":", "0", ")", ";", "}", "// Force push from the current repo's master branch to the remote", "// repo's gh-pages branch. (All previous history on the gh-pages branch", "// will be lost, since we are overwriting it.) We silence any output to", "// hide any sensitive credential data that might otherwise be exposed.", "config", ".", "silent", "=", "true", ";", "// this is apparently reset after exec", "exec", "(", "'git push --force \"[email protected]:postmanlabs/newman.git\" master:gh-pages'", ",", "next", ")", ";", "}" ]
Publish the documentation built in the previous step of the pipeline. @param {Function} next - The callback function invoked to mark the completion of the publish routine, either way. @returns {*}
[ "Publish", "the", "documentation", "built", "in", "the", "previous", "step", "of", "the", "pipeline", "." ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/npm/publish-docs.js#L20-L51
4,812
postmanlabs/newman
lib/reporters/cli/cli-utils.js
function (color) { return (color === 'off') || (color !== 'on') && (Boolean(process.env.CI) || !process.stdout.isTTY); // eslint-disable-line no-process-env }
javascript
function (color) { return (color === 'off') || (color !== 'on') && (Boolean(process.env.CI) || !process.stdout.isTTY); // eslint-disable-line no-process-env }
[ "function", "(", "color", ")", "{", "return", "(", "color", "===", "'off'", ")", "||", "(", "color", "!==", "'on'", ")", "&&", "(", "Boolean", "(", "process", ".", "env", ".", "CI", ")", "||", "!", "process", ".", "stdout", ".", "isTTY", ")", ";", "// eslint-disable-line no-process-env", "}" ]
A CLI utility helper method that checks for the non TTY compliance of the current run environment. color: | noTTY: 'on' -> false 'off' -> true otherwise -> Based on CI or isTTY. @param {String} color - A flag to indicate usage of the --color option. @returns {Boolean} - A boolean value depicting the result of the noTTY check.
[ "A", "CLI", "utility", "helper", "method", "that", "checks", "for", "the", "non", "TTY", "compliance", "of", "the", "current", "run", "environment", "." ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/lib/reporters/cli/cli-utils.js#L101-L104
4,813
postmanlabs/newman
lib/reporters/cli/cli-utils.js
function (runOptions) { var dimension = cliUtils.dimension(), options = { depth: 25, maxArrayLength: 100, // only supported in Node v6.1.0 and up: https://github.com/nodejs/node/pull/6334 colors: !cliUtils.noTTY(runOptions.color), // note that similar dimension calculation is in utils.wrapper // only supported in Node v6.3.0 and above: https://github.com/nodejs/node/pull/7499 breakLength: ((dimension.exists && (dimension.width > 20)) ? dimension.width : 60) - 16 }; return function (item) { return inspect(item, options); }; }
javascript
function (runOptions) { var dimension = cliUtils.dimension(), options = { depth: 25, maxArrayLength: 100, // only supported in Node v6.1.0 and up: https://github.com/nodejs/node/pull/6334 colors: !cliUtils.noTTY(runOptions.color), // note that similar dimension calculation is in utils.wrapper // only supported in Node v6.3.0 and above: https://github.com/nodejs/node/pull/7499 breakLength: ((dimension.exists && (dimension.width > 20)) ? dimension.width : 60) - 16 }; return function (item) { return inspect(item, options); }; }
[ "function", "(", "runOptions", ")", "{", "var", "dimension", "=", "cliUtils", ".", "dimension", "(", ")", ",", "options", "=", "{", "depth", ":", "25", ",", "maxArrayLength", ":", "100", ",", "// only supported in Node v6.1.0 and up: https://github.com/nodejs/node/pull/6334", "colors", ":", "!", "cliUtils", ".", "noTTY", "(", "runOptions", ".", "color", ")", ",", "// note that similar dimension calculation is in utils.wrapper", "// only supported in Node v6.3.0 and above: https://github.com/nodejs/node/pull/7499", "breakLength", ":", "(", "(", "dimension", ".", "exists", "&&", "(", "dimension", ".", "width", ">", "20", ")", ")", "?", "dimension", ".", "width", ":", "60", ")", "-", "16", "}", ";", "return", "function", "(", "item", ")", "{", "return", "inspect", "(", "item", ",", "options", ")", ";", "}", ";", "}" ]
A CLI utility helper method that generates a color inspector function for CLI reports. @param {Object} runOptions - The set of run options acquired via the runner. @returns {Function} - A function to perform utils.inspect, given a sample item, under pre-existing options.
[ "A", "CLI", "utility", "helper", "method", "that", "generates", "a", "color", "inspector", "function", "for", "CLI", "reports", "." ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/lib/reporters/cli/cli-utils.js#L112-L129
4,814
postmanlabs/newman
lib/reporters/cli/cli-utils.js
function () { var dimension = cliUtils.dimension(), // note that similar dimension calculation is in utils.wrapper width = ((dimension.exists && (dimension.width > 20)) ? dimension.width : 60) - 6; return function (text, indent) { return wrap(text, { indent: indent, width: width, cut: true }); }; }
javascript
function () { var dimension = cliUtils.dimension(), // note that similar dimension calculation is in utils.wrapper width = ((dimension.exists && (dimension.width > 20)) ? dimension.width : 60) - 6; return function (text, indent) { return wrap(text, { indent: indent, width: width, cut: true }); }; }
[ "function", "(", ")", "{", "var", "dimension", "=", "cliUtils", ".", "dimension", "(", ")", ",", "// note that similar dimension calculation is in utils.wrapper", "width", "=", "(", "(", "dimension", ".", "exists", "&&", "(", "dimension", ".", "width", ">", "20", ")", ")", "?", "dimension", ".", "width", ":", "60", ")", "-", "6", ";", "return", "function", "(", "text", ",", "indent", ")", "{", "return", "wrap", "(", "text", ",", "{", "indent", ":", "indent", ",", "width", ":", "width", ",", "cut", ":", "true", "}", ")", ";", "}", ";", "}" ]
A CLI utility helper method to provide content wrapping functionality for CLI reports. @returns {Function} - A sub-method to wrap content, given a piece of text, and indent value.
[ "A", "CLI", "utility", "helper", "method", "to", "provide", "content", "wrapping", "functionality", "for", "CLI", "reports", "." ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/lib/reporters/cli/cli-utils.js#L136-L148
4,815
postmanlabs/newman
lib/reporters/cli/cli-utils.js
function () { var tty, width, height; try { tty = require('tty'); } catch (e) { tty = null; } if (tty && tty.isatty(1) && tty.isatty(2)) { if (process.stdout.getWindowSize) { width = process.stdout.getWindowSize(1)[0]; height = process.stdout.getWindowSize(1)[1]; } else if (tty.getWindowSize) { width = tty.getWindowSize()[1]; height = tty.getWindowSize()[0]; } else if (process.stdout.columns && process.stdout.rows) { height = process.stdout.rows; width = process.stdout.columns; } } return { exists: !(Boolean(process.env.CI) || !process.stdout.isTTY), // eslint-disable-line no-process-env width: width, height: height }; }
javascript
function () { var tty, width, height; try { tty = require('tty'); } catch (e) { tty = null; } if (tty && tty.isatty(1) && tty.isatty(2)) { if (process.stdout.getWindowSize) { width = process.stdout.getWindowSize(1)[0]; height = process.stdout.getWindowSize(1)[1]; } else if (tty.getWindowSize) { width = tty.getWindowSize()[1]; height = tty.getWindowSize()[0]; } else if (process.stdout.columns && process.stdout.rows) { height = process.stdout.rows; width = process.stdout.columns; } } return { exists: !(Boolean(process.env.CI) || !process.stdout.isTTY), // eslint-disable-line no-process-env width: width, height: height }; }
[ "function", "(", ")", "{", "var", "tty", ",", "width", ",", "height", ";", "try", "{", "tty", "=", "require", "(", "'tty'", ")", ";", "}", "catch", "(", "e", ")", "{", "tty", "=", "null", ";", "}", "if", "(", "tty", "&&", "tty", ".", "isatty", "(", "1", ")", "&&", "tty", ".", "isatty", "(", "2", ")", ")", "{", "if", "(", "process", ".", "stdout", ".", "getWindowSize", ")", "{", "width", "=", "process", ".", "stdout", ".", "getWindowSize", "(", "1", ")", "[", "0", "]", ";", "height", "=", "process", ".", "stdout", ".", "getWindowSize", "(", "1", ")", "[", "1", "]", ";", "}", "else", "if", "(", "tty", ".", "getWindowSize", ")", "{", "width", "=", "tty", ".", "getWindowSize", "(", ")", "[", "1", "]", ";", "height", "=", "tty", ".", "getWindowSize", "(", ")", "[", "0", "]", ";", "}", "else", "if", "(", "process", ".", "stdout", ".", "columns", "&&", "process", ".", "stdout", ".", "rows", ")", "{", "height", "=", "process", ".", "stdout", ".", "rows", ";", "width", "=", "process", ".", "stdout", ".", "columns", ";", "}", "}", "return", "{", "exists", ":", "!", "(", "Boolean", "(", "process", ".", "env", ".", "CI", ")", "||", "!", "process", ".", "stdout", ".", "isTTY", ")", ",", "// eslint-disable-line no-process-env", "width", ":", "width", ",", "height", ":", "height", "}", ";", "}" ]
A CLI utility helper method to compute and scae the size of the CLI table to be displayed. @returns {Object} - A set of properties: width, height, and TTY existance.
[ "A", "CLI", "utility", "helper", "method", "to", "compute", "and", "scae", "the", "size", "of", "the", "CLI", "table", "to", "be", "displayed", "." ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/lib/reporters/cli/cli-utils.js#L155-L183
4,816
postmanlabs/newman
npm/server.js
createRawEchoServer
function createRawEchoServer () { var server; server = net.createServer(function (socket) { socket.on('data', function (chunk) { if (this.data === undefined) { this.data = ''; setTimeout(() => { // Status Line socket.write('HTTP/1.1 200 ok\r\n'); // Response Headers socket.write('connection: close\r\n'); socket.write('content-type: text/plain\r\n'); socket.write('raw-request: ' + JSON.stringify(this.data) + '\r\n'); // CRLF socket.write('\r\n'); // Response Body if (!this.data.startsWith('HEAD / HTTP/1.1')) { socket.write(this.data); } socket.end(); }, 1000); } this.data += chunk.toString(); }); }); server.on('listening', function () { server.port = this.address().port; }); enableServerDestroy(server); return server; }
javascript
function createRawEchoServer () { var server; server = net.createServer(function (socket) { socket.on('data', function (chunk) { if (this.data === undefined) { this.data = ''; setTimeout(() => { // Status Line socket.write('HTTP/1.1 200 ok\r\n'); // Response Headers socket.write('connection: close\r\n'); socket.write('content-type: text/plain\r\n'); socket.write('raw-request: ' + JSON.stringify(this.data) + '\r\n'); // CRLF socket.write('\r\n'); // Response Body if (!this.data.startsWith('HEAD / HTTP/1.1')) { socket.write(this.data); } socket.end(); }, 1000); } this.data += chunk.toString(); }); }); server.on('listening', function () { server.port = this.address().port; }); enableServerDestroy(server); return server; }
[ "function", "createRawEchoServer", "(", ")", "{", "var", "server", ";", "server", "=", "net", ".", "createServer", "(", "function", "(", "socket", ")", "{", "socket", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "if", "(", "this", ".", "data", "===", "undefined", ")", "{", "this", ".", "data", "=", "''", ";", "setTimeout", "(", "(", ")", "=>", "{", "// Status Line", "socket", ".", "write", "(", "'HTTP/1.1 200 ok\\r\\n'", ")", ";", "// Response Headers", "socket", ".", "write", "(", "'connection: close\\r\\n'", ")", ";", "socket", ".", "write", "(", "'content-type: text/plain\\r\\n'", ")", ";", "socket", ".", "write", "(", "'raw-request: '", "+", "JSON", ".", "stringify", "(", "this", ".", "data", ")", "+", "'\\r\\n'", ")", ";", "// CRLF", "socket", ".", "write", "(", "'\\r\\n'", ")", ";", "// Response Body", "if", "(", "!", "this", ".", "data", ".", "startsWith", "(", "'HEAD / HTTP/1.1'", ")", ")", "{", "socket", ".", "write", "(", "this", ".", "data", ")", ";", "}", "socket", ".", "end", "(", ")", ";", "}", ",", "1000", ")", ";", "}", "this", ".", "data", "+=", "chunk", ".", "toString", "(", ")", ";", "}", ")", ";", "}", ")", ";", "server", ".", "on", "(", "'listening'", ",", "function", "(", ")", "{", "server", ".", "port", "=", "this", ".", "address", "(", ")", ".", "port", ";", "}", ")", ";", "enableServerDestroy", "(", "server", ")", ";", "return", "server", ";", "}" ]
Echo raw request message to test - Body for HTTP methods like GET, HEAD - Custom HTTP methods @example var s = createRawEchoServer(); s.listen(3000, function() { console.log(s.port); s.close(); }); @note For HEAD request, read body from `raw-request` response header
[ "Echo", "raw", "request", "message", "to", "test", "-", "Body", "for", "HTTP", "methods", "like", "GET", "HEAD", "-", "Custom", "HTTP", "methods" ]
c05a5a1e82aa3c2021e94ba09e627ba4718af69e
https://github.com/postmanlabs/newman/blob/c05a5a1e82aa3c2021e94ba09e627ba4718af69e/npm/server.js#L20-L60
4,817
graphql/graphiql
src/utility/fillLeafs.js
defaultGetDefaultFieldNames
function defaultGetDefaultFieldNames(type) { // If this type cannot access fields, then return an empty set. if (!type.getFields) { return []; } const fields = type.getFields(); // Is there an `id` field? if (fields['id']) { return ['id']; } // Is there an `edges` field? if (fields['edges']) { return ['edges']; } // Is there an `node` field? if (fields['node']) { return ['node']; } // Include all leaf-type fields. const leafFieldNames = []; Object.keys(fields).forEach(fieldName => { if (isLeafType(fields[fieldName].type)) { leafFieldNames.push(fieldName); } }); return leafFieldNames; }
javascript
function defaultGetDefaultFieldNames(type) { // If this type cannot access fields, then return an empty set. if (!type.getFields) { return []; } const fields = type.getFields(); // Is there an `id` field? if (fields['id']) { return ['id']; } // Is there an `edges` field? if (fields['edges']) { return ['edges']; } // Is there an `node` field? if (fields['node']) { return ['node']; } // Include all leaf-type fields. const leafFieldNames = []; Object.keys(fields).forEach(fieldName => { if (isLeafType(fields[fieldName].type)) { leafFieldNames.push(fieldName); } }); return leafFieldNames; }
[ "function", "defaultGetDefaultFieldNames", "(", "type", ")", "{", "// If this type cannot access fields, then return an empty set.", "if", "(", "!", "type", ".", "getFields", ")", "{", "return", "[", "]", ";", "}", "const", "fields", "=", "type", ".", "getFields", "(", ")", ";", "// Is there an `id` field?", "if", "(", "fields", "[", "'id'", "]", ")", "{", "return", "[", "'id'", "]", ";", "}", "// Is there an `edges` field?", "if", "(", "fields", "[", "'edges'", "]", ")", "{", "return", "[", "'edges'", "]", ";", "}", "// Is there an `node` field?", "if", "(", "fields", "[", "'node'", "]", ")", "{", "return", "[", "'node'", "]", ";", "}", "// Include all leaf-type fields.", "const", "leafFieldNames", "=", "[", "]", ";", "Object", ".", "keys", "(", "fields", ")", ".", "forEach", "(", "fieldName", "=>", "{", "if", "(", "isLeafType", "(", "fields", "[", "fieldName", "]", ".", "type", ")", ")", "{", "leafFieldNames", ".", "push", "(", "fieldName", ")", ";", "}", "}", ")", ";", "return", "leafFieldNames", ";", "}" ]
The default function to use for producing the default fields from a type. This function first looks for some common patterns, and falls back to including all leaf-type fields.
[ "The", "default", "function", "to", "use", "for", "producing", "the", "default", "fields", "from", "a", "type", ".", "This", "function", "first", "looks", "for", "some", "common", "patterns", "and", "falls", "back", "to", "including", "all", "leaf", "-", "type", "fields", "." ]
5d0f31d6059edc5f816edba3962c3b57fdabd478
https://github.com/graphql/graphiql/blob/5d0f31d6059edc5f816edba3962c3b57fdabd478/src/utility/fillLeafs.js#L73-L104
4,818
graphql/graphiql
src/utility/fillLeafs.js
buildSelectionSet
function buildSelectionSet(type, getDefaultFieldNames) { // Unwrap any non-null or list types. const namedType = getNamedType(type); // Unknown types and leaf types do not have selection sets. if (!type || isLeafType(type)) { return; } // Get an array of field names to use. const fieldNames = getDefaultFieldNames(namedType); // If there are no field names to use, return no selection set. if (!Array.isArray(fieldNames) || fieldNames.length === 0) { return; } // Build a selection set of each field, calling buildSelectionSet recursively. return { kind: 'SelectionSet', selections: fieldNames.map(fieldName => { const fieldDef = namedType.getFields()[fieldName]; const fieldType = fieldDef ? fieldDef.type : null; return { kind: 'Field', name: { kind: 'Name', value: fieldName, }, selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames), }; }), }; }
javascript
function buildSelectionSet(type, getDefaultFieldNames) { // Unwrap any non-null or list types. const namedType = getNamedType(type); // Unknown types and leaf types do not have selection sets. if (!type || isLeafType(type)) { return; } // Get an array of field names to use. const fieldNames = getDefaultFieldNames(namedType); // If there are no field names to use, return no selection set. if (!Array.isArray(fieldNames) || fieldNames.length === 0) { return; } // Build a selection set of each field, calling buildSelectionSet recursively. return { kind: 'SelectionSet', selections: fieldNames.map(fieldName => { const fieldDef = namedType.getFields()[fieldName]; const fieldType = fieldDef ? fieldDef.type : null; return { kind: 'Field', name: { kind: 'Name', value: fieldName, }, selectionSet: buildSelectionSet(fieldType, getDefaultFieldNames), }; }), }; }
[ "function", "buildSelectionSet", "(", "type", ",", "getDefaultFieldNames", ")", "{", "// Unwrap any non-null or list types.", "const", "namedType", "=", "getNamedType", "(", "type", ")", ";", "// Unknown types and leaf types do not have selection sets.", "if", "(", "!", "type", "||", "isLeafType", "(", "type", ")", ")", "{", "return", ";", "}", "// Get an array of field names to use.", "const", "fieldNames", "=", "getDefaultFieldNames", "(", "namedType", ")", ";", "// If there are no field names to use, return no selection set.", "if", "(", "!", "Array", ".", "isArray", "(", "fieldNames", ")", "||", "fieldNames", ".", "length", "===", "0", ")", "{", "return", ";", "}", "// Build a selection set of each field, calling buildSelectionSet recursively.", "return", "{", "kind", ":", "'SelectionSet'", ",", "selections", ":", "fieldNames", ".", "map", "(", "fieldName", "=>", "{", "const", "fieldDef", "=", "namedType", ".", "getFields", "(", ")", "[", "fieldName", "]", ";", "const", "fieldType", "=", "fieldDef", "?", "fieldDef", ".", "type", ":", "null", ";", "return", "{", "kind", ":", "'Field'", ",", "name", ":", "{", "kind", ":", "'Name'", ",", "value", ":", "fieldName", ",", "}", ",", "selectionSet", ":", "buildSelectionSet", "(", "fieldType", ",", "getDefaultFieldNames", ")", ",", "}", ";", "}", ")", ",", "}", ";", "}" ]
Given a GraphQL type, and a function which produces field names, recursively generate a SelectionSet which includes default fields.
[ "Given", "a", "GraphQL", "type", "and", "a", "function", "which", "produces", "field", "names", "recursively", "generate", "a", "SelectionSet", "which", "includes", "default", "fields", "." ]
5d0f31d6059edc5f816edba3962c3b57fdabd478
https://github.com/graphql/graphiql/blob/5d0f31d6059edc5f816edba3962c3b57fdabd478/src/utility/fillLeafs.js#L108-L141
4,819
graphql/graphiql
src/utility/fillLeafs.js
getIndentation
function getIndentation(str, index) { let indentStart = index; let indentEnd = index; while (indentStart) { const c = str.charCodeAt(indentStart - 1); // line break if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) { break; } indentStart--; // not white space if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) { indentEnd = indentStart; } } return str.substring(indentStart, indentEnd); }
javascript
function getIndentation(str, index) { let indentStart = index; let indentEnd = index; while (indentStart) { const c = str.charCodeAt(indentStart - 1); // line break if (c === 10 || c === 13 || c === 0x2028 || c === 0x2029) { break; } indentStart--; // not white space if (c !== 9 && c !== 11 && c !== 12 && c !== 32 && c !== 160) { indentEnd = indentStart; } } return str.substring(indentStart, indentEnd); }
[ "function", "getIndentation", "(", "str", ",", "index", ")", "{", "let", "indentStart", "=", "index", ";", "let", "indentEnd", "=", "index", ";", "while", "(", "indentStart", ")", "{", "const", "c", "=", "str", ".", "charCodeAt", "(", "indentStart", "-", "1", ")", ";", "// line break", "if", "(", "c", "===", "10", "||", "c", "===", "13", "||", "c", "===", "0x2028", "||", "c", "===", "0x2029", ")", "{", "break", ";", "}", "indentStart", "--", ";", "// not white space", "if", "(", "c", "!==", "9", "&&", "c", "!==", "11", "&&", "c", "!==", "12", "&&", "c", "!==", "32", "&&", "c", "!==", "160", ")", "{", "indentEnd", "=", "indentStart", ";", "}", "}", "return", "str", ".", "substring", "(", "indentStart", ",", "indentEnd", ")", ";", "}" ]
Given a string and an index, look backwards to find the string of whitespace following the next previous line break.
[ "Given", "a", "string", "and", "an", "index", "look", "backwards", "to", "find", "the", "string", "of", "whitespace", "following", "the", "next", "previous", "line", "break", "." ]
5d0f31d6059edc5f816edba3962c3b57fdabd478
https://github.com/graphql/graphiql/blob/5d0f31d6059edc5f816edba3962c3b57fdabd478/src/utility/fillLeafs.js#L161-L177
4,820
PrismJS/prism
gulpfile.js
guessTitle
function guessTitle(id) { if (!id) { return id; } return (id.substring(0, 1).toUpperCase() + id.substring(1)).replace(/s(?=cript)/, 'S'); }
javascript
function guessTitle(id) { if (!id) { return id; } return (id.substring(0, 1).toUpperCase() + id.substring(1)).replace(/s(?=cript)/, 'S'); }
[ "function", "guessTitle", "(", "id", ")", "{", "if", "(", "!", "id", ")", "{", "return", "id", ";", "}", "return", "(", "id", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "id", ".", "substring", "(", "1", ")", ")", ".", "replace", "(", "/", "s(?=cript)", "/", ",", "'S'", ")", ";", "}" ]
Tries to guess the name of a language given its id. From `prism-show-language.js`. @param {string} id The language id. @returns {string}
[ "Tries", "to", "guess", "the", "name", "of", "a", "language", "given", "its", "id", "." ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/gulpfile.js#L109-L114
4,821
PrismJS/prism
plugins/line-highlight/prism-line-highlight.js
highlightLines
function highlightLines(pre, lines, classes) { lines = typeof lines === 'string' ? lines : pre.getAttribute('data-line'); var ranges = lines.replace(/\s+/g, '').split(','); var offset = +pre.getAttribute('data-line-offset') || 0; var parseMethod = isLineHeightRounded() ? parseInt : parseFloat; var lineHeight = parseMethod(getComputedStyle(pre).lineHeight); var hasLineNumbers = hasClass(pre, 'line-numbers'); var parentElement = hasLineNumbers ? pre : pre.querySelector('code') || pre; var mutateActions = /** @type {(() => void)[]} */ ([]); ranges.forEach(function (currentRange) { var range = currentRange.split('-'); var start = +range[0]; var end = +range[1] || start; var line = pre.querySelector('.line-highlight[data-range="' + currentRange + '"]') || document.createElement('div'); mutateActions.push(function () { line.setAttribute('aria-hidden', 'true'); line.setAttribute('data-range', currentRange); line.className = (classes || '') + ' line-highlight'; }); // if the line-numbers plugin is enabled, then there is no reason for this plugin to display the line numbers if (hasLineNumbers && Prism.plugins.lineNumbers) { var startNode = Prism.plugins.lineNumbers.getLine(pre, start); var endNode = Prism.plugins.lineNumbers.getLine(pre, end); if (startNode) { var top = startNode.offsetTop + 'px'; mutateActions.push(function () { line.style.top = top; }); } if (endNode) { var height = (endNode.offsetTop - startNode.offsetTop) + endNode.offsetHeight + 'px'; mutateActions.push(function () { line.style.height = height; }); } } else { mutateActions.push(function () { line.setAttribute('data-start', start); if (end > start) { line.setAttribute('data-end', end); } line.style.top = (start - offset - 1) * lineHeight + 'px'; line.textContent = new Array(end - start + 2).join(' \n'); }); } mutateActions.push(function () { // allow this to play nicely with the line-numbers plugin // need to attack to pre as when line-numbers is enabled, the code tag is relatively which screws up the positioning parentElement.appendChild(line); }); }); return function () { mutateActions.forEach(callFunction); }; }
javascript
function highlightLines(pre, lines, classes) { lines = typeof lines === 'string' ? lines : pre.getAttribute('data-line'); var ranges = lines.replace(/\s+/g, '').split(','); var offset = +pre.getAttribute('data-line-offset') || 0; var parseMethod = isLineHeightRounded() ? parseInt : parseFloat; var lineHeight = parseMethod(getComputedStyle(pre).lineHeight); var hasLineNumbers = hasClass(pre, 'line-numbers'); var parentElement = hasLineNumbers ? pre : pre.querySelector('code') || pre; var mutateActions = /** @type {(() => void)[]} */ ([]); ranges.forEach(function (currentRange) { var range = currentRange.split('-'); var start = +range[0]; var end = +range[1] || start; var line = pre.querySelector('.line-highlight[data-range="' + currentRange + '"]') || document.createElement('div'); mutateActions.push(function () { line.setAttribute('aria-hidden', 'true'); line.setAttribute('data-range', currentRange); line.className = (classes || '') + ' line-highlight'; }); // if the line-numbers plugin is enabled, then there is no reason for this plugin to display the line numbers if (hasLineNumbers && Prism.plugins.lineNumbers) { var startNode = Prism.plugins.lineNumbers.getLine(pre, start); var endNode = Prism.plugins.lineNumbers.getLine(pre, end); if (startNode) { var top = startNode.offsetTop + 'px'; mutateActions.push(function () { line.style.top = top; }); } if (endNode) { var height = (endNode.offsetTop - startNode.offsetTop) + endNode.offsetHeight + 'px'; mutateActions.push(function () { line.style.height = height; }); } } else { mutateActions.push(function () { line.setAttribute('data-start', start); if (end > start) { line.setAttribute('data-end', end); } line.style.top = (start - offset - 1) * lineHeight + 'px'; line.textContent = new Array(end - start + 2).join(' \n'); }); } mutateActions.push(function () { // allow this to play nicely with the line-numbers plugin // need to attack to pre as when line-numbers is enabled, the code tag is relatively which screws up the positioning parentElement.appendChild(line); }); }); return function () { mutateActions.forEach(callFunction); }; }
[ "function", "highlightLines", "(", "pre", ",", "lines", ",", "classes", ")", "{", "lines", "=", "typeof", "lines", "===", "'string'", "?", "lines", ":", "pre", ".", "getAttribute", "(", "'data-line'", ")", ";", "var", "ranges", "=", "lines", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "''", ")", ".", "split", "(", "','", ")", ";", "var", "offset", "=", "+", "pre", ".", "getAttribute", "(", "'data-line-offset'", ")", "||", "0", ";", "var", "parseMethod", "=", "isLineHeightRounded", "(", ")", "?", "parseInt", ":", "parseFloat", ";", "var", "lineHeight", "=", "parseMethod", "(", "getComputedStyle", "(", "pre", ")", ".", "lineHeight", ")", ";", "var", "hasLineNumbers", "=", "hasClass", "(", "pre", ",", "'line-numbers'", ")", ";", "var", "parentElement", "=", "hasLineNumbers", "?", "pre", ":", "pre", ".", "querySelector", "(", "'code'", ")", "||", "pre", ";", "var", "mutateActions", "=", "/** @type {(() => void)[]} */", "(", "[", "]", ")", ";", "ranges", ".", "forEach", "(", "function", "(", "currentRange", ")", "{", "var", "range", "=", "currentRange", ".", "split", "(", "'-'", ")", ";", "var", "start", "=", "+", "range", "[", "0", "]", ";", "var", "end", "=", "+", "range", "[", "1", "]", "||", "start", ";", "var", "line", "=", "pre", ".", "querySelector", "(", "'.line-highlight[data-range=\"'", "+", "currentRange", "+", "'\"]'", ")", "||", "document", ".", "createElement", "(", "'div'", ")", ";", "mutateActions", ".", "push", "(", "function", "(", ")", "{", "line", ".", "setAttribute", "(", "'aria-hidden'", ",", "'true'", ")", ";", "line", ".", "setAttribute", "(", "'data-range'", ",", "currentRange", ")", ";", "line", ".", "className", "=", "(", "classes", "||", "''", ")", "+", "' line-highlight'", ";", "}", ")", ";", "// if the line-numbers plugin is enabled, then there is no reason for this plugin to display the line numbers", "if", "(", "hasLineNumbers", "&&", "Prism", ".", "plugins", ".", "lineNumbers", ")", "{", "var", "startNode", "=", "Prism", ".", "plugins", ".", "lineNumbers", ".", "getLine", "(", "pre", ",", "start", ")", ";", "var", "endNode", "=", "Prism", ".", "plugins", ".", "lineNumbers", ".", "getLine", "(", "pre", ",", "end", ")", ";", "if", "(", "startNode", ")", "{", "var", "top", "=", "startNode", ".", "offsetTop", "+", "'px'", ";", "mutateActions", ".", "push", "(", "function", "(", ")", "{", "line", ".", "style", ".", "top", "=", "top", ";", "}", ")", ";", "}", "if", "(", "endNode", ")", "{", "var", "height", "=", "(", "endNode", ".", "offsetTop", "-", "startNode", ".", "offsetTop", ")", "+", "endNode", ".", "offsetHeight", "+", "'px'", ";", "mutateActions", ".", "push", "(", "function", "(", ")", "{", "line", ".", "style", ".", "height", "=", "height", ";", "}", ")", ";", "}", "}", "else", "{", "mutateActions", ".", "push", "(", "function", "(", ")", "{", "line", ".", "setAttribute", "(", "'data-start'", ",", "start", ")", ";", "if", "(", "end", ">", "start", ")", "{", "line", ".", "setAttribute", "(", "'data-end'", ",", "end", ")", ";", "}", "line", ".", "style", ".", "top", "=", "(", "start", "-", "offset", "-", "1", ")", "*", "lineHeight", "+", "'px'", ";", "line", ".", "textContent", "=", "new", "Array", "(", "end", "-", "start", "+", "2", ")", ".", "join", "(", "' \\n'", ")", ";", "}", ")", ";", "}", "mutateActions", ".", "push", "(", "function", "(", ")", "{", "// allow this to play nicely with the line-numbers plugin", "// need to attack to pre as when line-numbers is enabled, the code tag is relatively which screws up the positioning", "parentElement", ".", "appendChild", "(", "line", ")", ";", "}", ")", ";", "}", ")", ";", "return", "function", "(", ")", "{", "mutateActions", ".", "forEach", "(", "callFunction", ")", ";", "}", ";", "}" ]
Highlights the lines of the given pre. This function is split into a DOM measuring and mutate phase to improve performance. The returned function mutates the DOM when called. @param {HTMLElement} pre @param {string} [lines] @param {string} [classes=''] @returns {() => void}
[ "Highlights", "the", "lines", "of", "the", "given", "pre", "." ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/plugins/line-highlight/prism-line-highlight.js#L53-L121
4,822
PrismJS/prism
components/prism-asciidoc.js
copyFromAsciiDoc
function copyFromAsciiDoc(keys) { keys = keys.split(' '); var o = {}; for (var i = 0, l = keys.length; i < l; i++) { o[keys[i]] = asciidoc[keys[i]]; } return o; }
javascript
function copyFromAsciiDoc(keys) { keys = keys.split(' '); var o = {}; for (var i = 0, l = keys.length; i < l; i++) { o[keys[i]] = asciidoc[keys[i]]; } return o; }
[ "function", "copyFromAsciiDoc", "(", "keys", ")", "{", "keys", "=", "keys", ".", "split", "(", "' '", ")", ";", "var", "o", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "keys", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "o", "[", "keys", "[", "i", "]", "]", "=", "asciidoc", "[", "keys", "[", "i", "]", "]", ";", "}", "return", "o", ";", "}" ]
Allow some nesting. There is no recursion though, so cloning should not be needed.
[ "Allow", "some", "nesting", ".", "There", "is", "no", "recursion", "though", "so", "cloning", "should", "not", "be", "needed", "." ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/components/prism-asciidoc.js#L203-L211
4,823
PrismJS/prism
plugins/custom-class/prism-custom-class.js
map
function map(classMap) { if (typeof classMap === 'function') { options.classMap = classMap; } else { options.classMap = function (className) { return classMap[className] || className; }; } }
javascript
function map(classMap) { if (typeof classMap === 'function') { options.classMap = classMap; } else { options.classMap = function (className) { return classMap[className] || className; }; } }
[ "function", "map", "(", "classMap", ")", "{", "if", "(", "typeof", "classMap", "===", "'function'", ")", "{", "options", ".", "classMap", "=", "classMap", ";", "}", "else", "{", "options", ".", "classMap", "=", "function", "(", "className", ")", "{", "return", "classMap", "[", "className", "]", "||", "className", ";", "}", ";", "}", "}" ]
Maps all class names using the given object or map function. This does not affect the prefix. @param {Object<string, string> | ClassMapper} classMap
[ "Maps", "all", "class", "names", "using", "the", "given", "object", "or", "map", "function", "." ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/plugins/custom-class/prism-custom-class.js#L39-L47
4,824
PrismJS/prism
components/prism-jsx.js
function (token) { if (!token) { return ''; } if (typeof token === 'string') { return token; } if (typeof token.content === 'string') { return token.content; } return token.content.map(stringifyToken).join(''); }
javascript
function (token) { if (!token) { return ''; } if (typeof token === 'string') { return token; } if (typeof token.content === 'string') { return token.content; } return token.content.map(stringifyToken).join(''); }
[ "function", "(", "token", ")", "{", "if", "(", "!", "token", ")", "{", "return", "''", ";", "}", "if", "(", "typeof", "token", "===", "'string'", ")", "{", "return", "token", ";", "}", "if", "(", "typeof", "token", ".", "content", "===", "'string'", ")", "{", "return", "token", ".", "content", ";", "}", "return", "token", ".", "content", ".", "map", "(", "stringifyToken", ")", ".", "join", "(", "''", ")", ";", "}" ]
The following will handle plain text inside tags
[ "The", "following", "will", "handle", "plain", "text", "inside", "tags" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/components/prism-jsx.js#L38-L49
4,825
PrismJS/prism
scripts/utopia.js
function(obj, func, context) { if(!_.type(func) == 'function') { throw Error('The second argument in Utopia.each() must be a function'); }; context = context || obj; for (var i in obj) { if(obj.hasOwnProperty && obj.hasOwnProperty(i)) { var ret = func.call(context, obj[i], i); if(!!ret || ret === 0 || ret === '') { return ret; } } } return null; }
javascript
function(obj, func, context) { if(!_.type(func) == 'function') { throw Error('The second argument in Utopia.each() must be a function'); }; context = context || obj; for (var i in obj) { if(obj.hasOwnProperty && obj.hasOwnProperty(i)) { var ret = func.call(context, obj[i], i); if(!!ret || ret === 0 || ret === '') { return ret; } } } return null; }
[ "function", "(", "obj", ",", "func", ",", "context", ")", "{", "if", "(", "!", "_", ".", "type", "(", "func", ")", "==", "'function'", ")", "{", "throw", "Error", "(", "'The second argument in Utopia.each() must be a function'", ")", ";", "}", ";", "context", "=", "context", "||", "obj", ";", "for", "(", "var", "i", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "&&", "obj", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "var", "ret", "=", "func", ".", "call", "(", "context", ",", "obj", "[", "i", "]", ",", "i", ")", ";", "if", "(", "!", "!", "ret", "||", "ret", "===", "0", "||", "ret", "===", "''", ")", "{", "return", "ret", ";", "}", "}", "}", "return", "null", ";", "}" ]
Iterate over the properties of an object. Checks whether the properties actually belong to it. Can be stopped if the function explicitly returns a value that isn't null, undefined or NaN. @param obj {Object} The object to iterate over @param func {Function} The function used in the iteration. Can accept 2 parameters: one of the value of the object and one for its name. @param context {Object} Context for the above function. Default is the object being iterated. @return {Object} Null or the return value of func, if it broke the loop at some point.
[ "Iterate", "over", "the", "properties", "of", "an", "object", ".", "Checks", "whether", "the", "properties", "actually", "belong", "to", "it", ".", "Can", "be", "stopped", "if", "the", "function", "explicitly", "returns", "a", "value", "that", "isn", "t", "null", "undefined", "or", "NaN", "." ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/scripts/utopia.js#L86-L104
4,826
PrismJS/prism
scripts/utopia.js
function(objects) { var ret = {}; for(var i=0; i<arguments.length; i++) { var o = arguments[i]; for(var j in o) { ret[j] = o[j]; } } return ret; }
javascript
function(objects) { var ret = {}; for(var i=0; i<arguments.length; i++) { var o = arguments[i]; for(var j in o) { ret[j] = o[j]; } } return ret; }
[ "function", "(", "objects", ")", "{", "var", "ret", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "var", "o", "=", "arguments", "[", "i", "]", ";", "for", "(", "var", "j", "in", "o", ")", "{", "ret", "[", "j", "]", "=", "o", "[", "j", "]", ";", "}", "}", "return", "ret", ";", "}" ]
Copies the properties of one object onto another. When there is a collision, the later one wins @return {Object} destination object
[ "Copies", "the", "properties", "of", "one", "object", "onto", "another", ".", "When", "there", "is", "a", "collision", "the", "later", "one", "wins" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/scripts/utopia.js#L112-L124
4,827
PrismJS/prism
scripts/utopia.js
function(object, objects) { for(var i=0; i<arguments.length; i++) { var o = arguments[i]; for(var j in o) { if(!(j in object)) { object[j] = o[j]; } } } return object; }
javascript
function(object, objects) { for(var i=0; i<arguments.length; i++) { var o = arguments[i]; for(var j in o) { if(!(j in object)) { object[j] = o[j]; } } } return object; }
[ "function", "(", "object", ",", "objects", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "var", "o", "=", "arguments", "[", "i", "]", ";", "for", "(", "var", "j", "in", "o", ")", "{", "if", "(", "!", "(", "j", "in", "object", ")", ")", "{", "object", "[", "j", "]", "=", "o", "[", "j", "]", ";", "}", "}", "}", "return", "object", ";", "}" ]
Copies the properties of one or more objects onto the first one When there is a collision, the first object wins
[ "Copies", "the", "properties", "of", "one", "or", "more", "objects", "onto", "the", "first", "one", "When", "there", "is", "a", "collision", "the", "first", "object", "wins" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/scripts/utopia.js#L130-L142
4,828
PrismJS/prism
scripts/utopia.js
function() { var options; if(_.type(arguments[0]) === 'string') { if(_.type(arguments[1]) === 'object') { // Utopia.element.create('div', { ... }); options = arguments[1]; options.tag = arguments[0]; } else { // Utopia.element.create('div', ...); options = { tag: arguments[0] }; // Utopia.element.create('div', [contents]); if(_.type(arguments[1]) === 'array') { options.contents = arguments[1]; } // Utopia.element.create('div', 'Text contents'); else if(_.type(arguments[1]) === 'string' || _.type(arguments[1]) === 'number') { options.contents = ['' + arguments[1]]; } } } else { options = arguments[0]; } var namespace = options.namespace || '', element; if(namespace) { element = document.createElementNS(namespace, options.tag); } else { element = document.createElement(options.tag); } if (options.className || options.id) { options.properties = options.properties || {}; options.properties.className = options.className; options.properties.id = options.id; } // Set properties, attributes and contents _.element.set(element, options); // Place the element in the DOM (inside, before or after an existing element) // This could be a selector if(options.before) { var before = $(options.before); if (before && before.parentNode) { before.parentNode.insertBefore(element, before); } } if (options.after && element.parentNode === null) { var after = $(options.after); if (after && after.parentNode) { after.parentNode.insertBefore(element, after.nextSibling) } } if (options.inside && element.parentNode === null) { $(options.inside).appendChild(element); } return element; }
javascript
function() { var options; if(_.type(arguments[0]) === 'string') { if(_.type(arguments[1]) === 'object') { // Utopia.element.create('div', { ... }); options = arguments[1]; options.tag = arguments[0]; } else { // Utopia.element.create('div', ...); options = { tag: arguments[0] }; // Utopia.element.create('div', [contents]); if(_.type(arguments[1]) === 'array') { options.contents = arguments[1]; } // Utopia.element.create('div', 'Text contents'); else if(_.type(arguments[1]) === 'string' || _.type(arguments[1]) === 'number') { options.contents = ['' + arguments[1]]; } } } else { options = arguments[0]; } var namespace = options.namespace || '', element; if(namespace) { element = document.createElementNS(namespace, options.tag); } else { element = document.createElement(options.tag); } if (options.className || options.id) { options.properties = options.properties || {}; options.properties.className = options.className; options.properties.id = options.id; } // Set properties, attributes and contents _.element.set(element, options); // Place the element in the DOM (inside, before or after an existing element) // This could be a selector if(options.before) { var before = $(options.before); if (before && before.parentNode) { before.parentNode.insertBefore(element, before); } } if (options.after && element.parentNode === null) { var after = $(options.after); if (after && after.parentNode) { after.parentNode.insertBefore(element, after.nextSibling) } } if (options.inside && element.parentNode === null) { $(options.inside).appendChild(element); } return element; }
[ "function", "(", ")", "{", "var", "options", ";", "if", "(", "_", ".", "type", "(", "arguments", "[", "0", "]", ")", "===", "'string'", ")", "{", "if", "(", "_", ".", "type", "(", "arguments", "[", "1", "]", ")", "===", "'object'", ")", "{", "// Utopia.element.create('div', { ... });", "options", "=", "arguments", "[", "1", "]", ";", "options", ".", "tag", "=", "arguments", "[", "0", "]", ";", "}", "else", "{", "// Utopia.element.create('div', ...);", "options", "=", "{", "tag", ":", "arguments", "[", "0", "]", "}", ";", "// Utopia.element.create('div', [contents]);", "if", "(", "_", ".", "type", "(", "arguments", "[", "1", "]", ")", "===", "'array'", ")", "{", "options", ".", "contents", "=", "arguments", "[", "1", "]", ";", "}", "// Utopia.element.create('div', 'Text contents');", "else", "if", "(", "_", ".", "type", "(", "arguments", "[", "1", "]", ")", "===", "'string'", "||", "_", ".", "type", "(", "arguments", "[", "1", "]", ")", "===", "'number'", ")", "{", "options", ".", "contents", "=", "[", "''", "+", "arguments", "[", "1", "]", "]", ";", "}", "}", "}", "else", "{", "options", "=", "arguments", "[", "0", "]", ";", "}", "var", "namespace", "=", "options", ".", "namespace", "||", "''", ",", "element", ";", "if", "(", "namespace", ")", "{", "element", "=", "document", ".", "createElementNS", "(", "namespace", ",", "options", ".", "tag", ")", ";", "}", "else", "{", "element", "=", "document", ".", "createElement", "(", "options", ".", "tag", ")", ";", "}", "if", "(", "options", ".", "className", "||", "options", ".", "id", ")", "{", "options", ".", "properties", "=", "options", ".", "properties", "||", "{", "}", ";", "options", ".", "properties", ".", "className", "=", "options", ".", "className", ";", "options", ".", "properties", ".", "id", "=", "options", ".", "id", ";", "}", "// Set properties, attributes and contents", "_", ".", "element", ".", "set", "(", "element", ",", "options", ")", ";", "// Place the element in the DOM (inside, before or after an existing element)", "// This could be a selector", "if", "(", "options", ".", "before", ")", "{", "var", "before", "=", "$", "(", "options", ".", "before", ")", ";", "if", "(", "before", "&&", "before", ".", "parentNode", ")", "{", "before", ".", "parentNode", ".", "insertBefore", "(", "element", ",", "before", ")", ";", "}", "}", "if", "(", "options", ".", "after", "&&", "element", ".", "parentNode", "===", "null", ")", "{", "var", "after", "=", "$", "(", "options", ".", "after", ")", ";", "if", "(", "after", "&&", "after", ".", "parentNode", ")", "{", "after", ".", "parentNode", ".", "insertBefore", "(", "element", ",", "after", ".", "nextSibling", ")", "}", "}", "if", "(", "options", ".", "inside", "&&", "element", ".", "parentNode", "===", "null", ")", "{", "$", "(", "options", ".", "inside", ")", ".", "appendChild", "(", "element", ")", ";", "}", "return", "element", ";", "}" ]
Creates a new DOM element @param options {Object} A set of key/value pairs for attributes, properties, contents, placement in the DOM etc @return The new DOM element
[ "Creates", "a", "new", "DOM", "element" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/scripts/utopia.js#L150-L220
4,829
PrismJS/prism
scripts/utopia.js
function(target, event, callback, traditional) { if(_.type(target) === 'string' || _.type(target) === 'array') { var elements = _.type(target) === 'string'? $$(target) : target; elements.forEach(function(element) { _.event.bind(element, event, callback, traditional); }); } else if(_.type(event) === 'string') { if(traditional) { target['on' + event] = callback; } else { target.addEventListener(event, callback, false); } } else if(_.type(event) === 'array') { for (var i=0; i<event.length; i++) { _.event.bind(target, event[i], callback, arguments[2]); } } else { for (var name in event) { _.event.bind(target, name, event[name], arguments[2]); } } }
javascript
function(target, event, callback, traditional) { if(_.type(target) === 'string' || _.type(target) === 'array') { var elements = _.type(target) === 'string'? $$(target) : target; elements.forEach(function(element) { _.event.bind(element, event, callback, traditional); }); } else if(_.type(event) === 'string') { if(traditional) { target['on' + event] = callback; } else { target.addEventListener(event, callback, false); } } else if(_.type(event) === 'array') { for (var i=0; i<event.length; i++) { _.event.bind(target, event[i], callback, arguments[2]); } } else { for (var name in event) { _.event.bind(target, name, event[name], arguments[2]); } } }
[ "function", "(", "target", ",", "event", ",", "callback", ",", "traditional", ")", "{", "if", "(", "_", ".", "type", "(", "target", ")", "===", "'string'", "||", "_", ".", "type", "(", "target", ")", "===", "'array'", ")", "{", "var", "elements", "=", "_", ".", "type", "(", "target", ")", "===", "'string'", "?", "$$", "(", "target", ")", ":", "target", ";", "elements", ".", "forEach", "(", "function", "(", "element", ")", "{", "_", ".", "event", ".", "bind", "(", "element", ",", "event", ",", "callback", ",", "traditional", ")", ";", "}", ")", ";", "}", "else", "if", "(", "_", ".", "type", "(", "event", ")", "===", "'string'", ")", "{", "if", "(", "traditional", ")", "{", "target", "[", "'on'", "+", "event", "]", "=", "callback", ";", "}", "else", "{", "target", ".", "addEventListener", "(", "event", ",", "callback", ",", "false", ")", ";", "}", "}", "else", "if", "(", "_", ".", "type", "(", "event", ")", "===", "'array'", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "event", ".", "length", ";", "i", "++", ")", "{", "_", ".", "event", ".", "bind", "(", "target", ",", "event", "[", "i", "]", ",", "callback", ",", "arguments", "[", "2", "]", ")", ";", "}", "}", "else", "{", "for", "(", "var", "name", "in", "event", ")", "{", "_", ".", "event", ".", "bind", "(", "target", ",", "name", ",", "event", "[", "name", "]", ",", "arguments", "[", "2", "]", ")", ";", "}", "}", "}" ]
Binds one or more events to one or more elements
[ "Binds", "one", "or", "more", "events", "to", "one", "or", "more", "elements" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/scripts/utopia.js#L310-L336
4,830
PrismJS/prism
scripts/utopia.js
function(target, type, properties) { if(_.type(target) === 'string' || _.type(target) === 'array') { var elements = _.type(target) === 'string'? $$(target) : target; elements.forEach(function(element) { _.event.fire(element, type, properties); }); } else if (document.createEvent) { var evt = document.createEvent("HTMLEvents"); evt.initEvent(type, true, true ); evt.custom = true; if(properties) { _.attach(evt, properties); } target.dispatchEvent(evt); } }
javascript
function(target, type, properties) { if(_.type(target) === 'string' || _.type(target) === 'array') { var elements = _.type(target) === 'string'? $$(target) : target; elements.forEach(function(element) { _.event.fire(element, type, properties); }); } else if (document.createEvent) { var evt = document.createEvent("HTMLEvents"); evt.initEvent(type, true, true ); evt.custom = true; if(properties) { _.attach(evt, properties); } target.dispatchEvent(evt); } }
[ "function", "(", "target", ",", "type", ",", "properties", ")", "{", "if", "(", "_", ".", "type", "(", "target", ")", "===", "'string'", "||", "_", ".", "type", "(", "target", ")", "===", "'array'", ")", "{", "var", "elements", "=", "_", ".", "type", "(", "target", ")", "===", "'string'", "?", "$$", "(", "target", ")", ":", "target", ";", "elements", ".", "forEach", "(", "function", "(", "element", ")", "{", "_", ".", "event", ".", "fire", "(", "element", ",", "type", ",", "properties", ")", ";", "}", ")", ";", "}", "else", "if", "(", "document", ".", "createEvent", ")", "{", "var", "evt", "=", "document", ".", "createEvent", "(", "\"HTMLEvents\"", ")", ";", "evt", ".", "initEvent", "(", "type", ",", "true", ",", "true", ")", ";", "evt", ".", "custom", "=", "true", ";", "if", "(", "properties", ")", "{", "_", ".", "attach", "(", "evt", ",", "properties", ")", ";", "}", "target", ".", "dispatchEvent", "(", "evt", ")", ";", "}", "}" ]
Fire a custom event
[ "Fire", "a", "custom", "event" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/scripts/utopia.js#L341-L361
4,831
PrismJS/prism
scripts/utopia.js
function(o) { document.body.setAttribute('data-loading', ''); var xhr = new XMLHttpRequest(), method = o.method || 'GET', data = o.data || ''; xhr.open(method, o.url + (method === 'GET' && data? '?' + data : ''), true); o.headers = o.headers || {}; if(method !== 'GET' && !o.headers['Content-type'] && !o.headers['Content-Type']) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); } for (var header in o.headers) { xhr.setRequestHeader(header, o.headers[header]); } xhr.onreadystatechange = function(){ if(xhr.readyState === 4) { document.body.removeAttribute('data-loading'); o.callback(xhr); } }; xhr.send(method === 'GET'? null : data); return xhr; }
javascript
function(o) { document.body.setAttribute('data-loading', ''); var xhr = new XMLHttpRequest(), method = o.method || 'GET', data = o.data || ''; xhr.open(method, o.url + (method === 'GET' && data? '?' + data : ''), true); o.headers = o.headers || {}; if(method !== 'GET' && !o.headers['Content-type'] && !o.headers['Content-Type']) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); } for (var header in o.headers) { xhr.setRequestHeader(header, o.headers[header]); } xhr.onreadystatechange = function(){ if(xhr.readyState === 4) { document.body.removeAttribute('data-loading'); o.callback(xhr); } }; xhr.send(method === 'GET'? null : data); return xhr; }
[ "function", "(", "o", ")", "{", "document", ".", "body", ".", "setAttribute", "(", "'data-loading'", ",", "''", ")", ";", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ",", "method", "=", "o", ".", "method", "||", "'GET'", ",", "data", "=", "o", ".", "data", "||", "''", ";", "xhr", ".", "open", "(", "method", ",", "o", ".", "url", "+", "(", "method", "===", "'GET'", "&&", "data", "?", "'?'", "+", "data", ":", "''", ")", ",", "true", ")", ";", "o", ".", "headers", "=", "o", ".", "headers", "||", "{", "}", ";", "if", "(", "method", "!==", "'GET'", "&&", "!", "o", ".", "headers", "[", "'Content-type'", "]", "&&", "!", "o", ".", "headers", "[", "'Content-Type'", "]", ")", "{", "xhr", ".", "setRequestHeader", "(", "\"Content-type\"", ",", "\"application/x-www-form-urlencoded\"", ")", ";", "}", "for", "(", "var", "header", "in", "o", ".", "headers", ")", "{", "xhr", ".", "setRequestHeader", "(", "header", ",", "o", ".", "headers", "[", "header", "]", ")", ";", "}", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "===", "4", ")", "{", "document", ".", "body", ".", "removeAttribute", "(", "'data-loading'", ")", ";", "o", ".", "callback", "(", "xhr", ")", ";", "}", "}", ";", "xhr", ".", "send", "(", "method", "===", "'GET'", "?", "null", ":", "data", ")", ";", "return", "xhr", ";", "}" ]
Helper for XHR requests
[ "Helper", "for", "XHR", "requests" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/scripts/utopia.js#L367-L398
4,832
PrismJS/prism
plugins/show-invisibles/prism-show-invisibles.js
handleToken
function handleToken(tokens, name) { var value = tokens[name]; var type = Prism.util.type(value); switch (type) { case 'RegExp': var inside = {}; tokens[name] = { pattern: value, inside: inside }; addInvisibles(inside); break; case 'Array': for (var i = 0, l = value.length; i < l; i++) { handleToken(value, i); } break; default: // 'Object' var inside = value.inside || (value.inside = {}); addInvisibles(inside); break; } }
javascript
function handleToken(tokens, name) { var value = tokens[name]; var type = Prism.util.type(value); switch (type) { case 'RegExp': var inside = {}; tokens[name] = { pattern: value, inside: inside }; addInvisibles(inside); break; case 'Array': for (var i = 0, l = value.length; i < l; i++) { handleToken(value, i); } break; default: // 'Object' var inside = value.inside || (value.inside = {}); addInvisibles(inside); break; } }
[ "function", "handleToken", "(", "tokens", ",", "name", ")", "{", "var", "value", "=", "tokens", "[", "name", "]", ";", "var", "type", "=", "Prism", ".", "util", ".", "type", "(", "value", ")", ";", "switch", "(", "type", ")", "{", "case", "'RegExp'", ":", "var", "inside", "=", "{", "}", ";", "tokens", "[", "name", "]", "=", "{", "pattern", ":", "value", ",", "inside", ":", "inside", "}", ";", "addInvisibles", "(", "inside", ")", ";", "break", ";", "case", "'Array'", ":", "for", "(", "var", "i", "=", "0", ",", "l", "=", "value", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "handleToken", "(", "value", ",", "i", ")", ";", "}", "break", ";", "default", ":", "// 'Object'", "var", "inside", "=", "value", ".", "inside", "||", "(", "value", ".", "inside", "=", "{", "}", ")", ";", "addInvisibles", "(", "inside", ")", ";", "break", ";", "}", "}" ]
Handles the recursive calling of `addInvisibles` for one token. @param {Object|Array} tokens The grammar or array which contains the token. @param {string|number} name The name or index of the token in `tokens`.
[ "Handles", "the", "recursive", "calling", "of", "addInvisibles", "for", "one", "token", "." ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/plugins/show-invisibles/prism-show-invisibles.js#L26-L51
4,833
PrismJS/prism
plugins/previewers/prism-previewers.js
function(prefix, func, values) { // Default value for angle var angle = '180deg'; if (/^(?:-?\d*\.?\d+(?:deg|rad)|to\b|top|right|bottom|left)/.test(values[0])) { angle = values.shift(); if (angle.indexOf('to ') < 0) { // Angle uses old keywords // W3C syntax uses "to" + opposite keywords if (angle.indexOf('top') >= 0) { if (angle.indexOf('left') >= 0) { angle = 'to bottom right'; } else if (angle.indexOf('right') >= 0) { angle = 'to bottom left'; } else { angle = 'to bottom'; } } else if (angle.indexOf('bottom') >= 0) { if (angle.indexOf('left') >= 0) { angle = 'to top right'; } else if (angle.indexOf('right') >= 0) { angle = 'to top left'; } else { angle = 'to top'; } } else if (angle.indexOf('left') >= 0) { angle = 'to right'; } else if (angle.indexOf('right') >= 0) { angle = 'to left'; } else if (prefix) { // Angle is shifted by 90deg in prefixed gradients if (angle.indexOf('deg') >= 0) { angle = (90 - parseFloat(angle)) + 'deg'; } else if (angle.indexOf('rad') >= 0) { angle = (Math.PI / 2 - parseFloat(angle)) + 'rad'; } } } } return func + '(' + angle + ',' + values.join(',') + ')'; }
javascript
function(prefix, func, values) { // Default value for angle var angle = '180deg'; if (/^(?:-?\d*\.?\d+(?:deg|rad)|to\b|top|right|bottom|left)/.test(values[0])) { angle = values.shift(); if (angle.indexOf('to ') < 0) { // Angle uses old keywords // W3C syntax uses "to" + opposite keywords if (angle.indexOf('top') >= 0) { if (angle.indexOf('left') >= 0) { angle = 'to bottom right'; } else if (angle.indexOf('right') >= 0) { angle = 'to bottom left'; } else { angle = 'to bottom'; } } else if (angle.indexOf('bottom') >= 0) { if (angle.indexOf('left') >= 0) { angle = 'to top right'; } else if (angle.indexOf('right') >= 0) { angle = 'to top left'; } else { angle = 'to top'; } } else if (angle.indexOf('left') >= 0) { angle = 'to right'; } else if (angle.indexOf('right') >= 0) { angle = 'to left'; } else if (prefix) { // Angle is shifted by 90deg in prefixed gradients if (angle.indexOf('deg') >= 0) { angle = (90 - parseFloat(angle)) + 'deg'; } else if (angle.indexOf('rad') >= 0) { angle = (Math.PI / 2 - parseFloat(angle)) + 'rad'; } } } } return func + '(' + angle + ',' + values.join(',') + ')'; }
[ "function", "(", "prefix", ",", "func", ",", "values", ")", "{", "// Default value for angle", "var", "angle", "=", "'180deg'", ";", "if", "(", "/", "^(?:-?\\d*\\.?\\d+(?:deg|rad)|to\\b|top|right|bottom|left)", "/", ".", "test", "(", "values", "[", "0", "]", ")", ")", "{", "angle", "=", "values", ".", "shift", "(", ")", ";", "if", "(", "angle", ".", "indexOf", "(", "'to '", ")", "<", "0", ")", "{", "// Angle uses old keywords", "// W3C syntax uses \"to\" + opposite keywords", "if", "(", "angle", ".", "indexOf", "(", "'top'", ")", ">=", "0", ")", "{", "if", "(", "angle", ".", "indexOf", "(", "'left'", ")", ">=", "0", ")", "{", "angle", "=", "'to bottom right'", ";", "}", "else", "if", "(", "angle", ".", "indexOf", "(", "'right'", ")", ">=", "0", ")", "{", "angle", "=", "'to bottom left'", ";", "}", "else", "{", "angle", "=", "'to bottom'", ";", "}", "}", "else", "if", "(", "angle", ".", "indexOf", "(", "'bottom'", ")", ">=", "0", ")", "{", "if", "(", "angle", ".", "indexOf", "(", "'left'", ")", ">=", "0", ")", "{", "angle", "=", "'to top right'", ";", "}", "else", "if", "(", "angle", ".", "indexOf", "(", "'right'", ")", ">=", "0", ")", "{", "angle", "=", "'to top left'", ";", "}", "else", "{", "angle", "=", "'to top'", ";", "}", "}", "else", "if", "(", "angle", ".", "indexOf", "(", "'left'", ")", ">=", "0", ")", "{", "angle", "=", "'to right'", ";", "}", "else", "if", "(", "angle", ".", "indexOf", "(", "'right'", ")", ">=", "0", ")", "{", "angle", "=", "'to left'", ";", "}", "else", "if", "(", "prefix", ")", "{", "// Angle is shifted by 90deg in prefixed gradients", "if", "(", "angle", ".", "indexOf", "(", "'deg'", ")", ">=", "0", ")", "{", "angle", "=", "(", "90", "-", "parseFloat", "(", "angle", ")", ")", "+", "'deg'", ";", "}", "else", "if", "(", "angle", ".", "indexOf", "(", "'rad'", ")", ">=", "0", ")", "{", "angle", "=", "(", "Math", ".", "PI", "/", "2", "-", "parseFloat", "(", "angle", ")", ")", "+", "'rad'", ";", "}", "}", "}", "}", "return", "func", "+", "'('", "+", "angle", "+", "','", "+", "values", ".", "join", "(", "','", ")", "+", "')'", ";", "}" ]
Returns a W3C-valid linear gradient @param {string} prefix Vendor prefix if any ("-moz-", "-webkit-", etc.) @param {string} func Gradient function name ("linear-gradient") @param {string[]} values Array of the gradient function parameters (["0deg", "red 0%", "blue 100%"])
[ "Returns", "a", "W3C", "-", "valid", "linear", "gradient" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/plugins/previewers/prism-previewers.js#L25-L66
4,834
PrismJS/prism
plugins/previewers/prism-previewers.js
function(prefix, func, values) { if (values[0].indexOf('at') < 0) { // Looks like old syntax // Default values var position = 'center'; var shape = 'ellipse'; var size = 'farthest-corner'; if (/\bcenter|top|right|bottom|left\b|^\d+/.test(values[0])) { // Found a position // Remove angle value, if any position = values.shift().replace(/\s*-?\d+(?:rad|deg)\s*/, ''); } if (/\bcircle|ellipse|closest|farthest|contain|cover\b/.test(values[0])) { // Found a shape and/or size var shapeSizeParts = values.shift().split(/\s+/); if (shapeSizeParts[0] && (shapeSizeParts[0] === 'circle' || shapeSizeParts[0] === 'ellipse')) { shape = shapeSizeParts.shift(); } if (shapeSizeParts[0]) { size = shapeSizeParts.shift(); } // Old keywords are converted to their synonyms if (size === 'cover') { size = 'farthest-corner'; } else if (size === 'contain') { size = 'clothest-side'; } } return func + '(' + shape + ' ' + size + ' at ' + position + ',' + values.join(',') + ')'; } return func + '(' + values.join(',') + ')'; }
javascript
function(prefix, func, values) { if (values[0].indexOf('at') < 0) { // Looks like old syntax // Default values var position = 'center'; var shape = 'ellipse'; var size = 'farthest-corner'; if (/\bcenter|top|right|bottom|left\b|^\d+/.test(values[0])) { // Found a position // Remove angle value, if any position = values.shift().replace(/\s*-?\d+(?:rad|deg)\s*/, ''); } if (/\bcircle|ellipse|closest|farthest|contain|cover\b/.test(values[0])) { // Found a shape and/or size var shapeSizeParts = values.shift().split(/\s+/); if (shapeSizeParts[0] && (shapeSizeParts[0] === 'circle' || shapeSizeParts[0] === 'ellipse')) { shape = shapeSizeParts.shift(); } if (shapeSizeParts[0]) { size = shapeSizeParts.shift(); } // Old keywords are converted to their synonyms if (size === 'cover') { size = 'farthest-corner'; } else if (size === 'contain') { size = 'clothest-side'; } } return func + '(' + shape + ' ' + size + ' at ' + position + ',' + values.join(',') + ')'; } return func + '(' + values.join(',') + ')'; }
[ "function", "(", "prefix", ",", "func", ",", "values", ")", "{", "if", "(", "values", "[", "0", "]", ".", "indexOf", "(", "'at'", ")", "<", "0", ")", "{", "// Looks like old syntax", "// Default values", "var", "position", "=", "'center'", ";", "var", "shape", "=", "'ellipse'", ";", "var", "size", "=", "'farthest-corner'", ";", "if", "(", "/", "\\bcenter|top|right|bottom|left\\b|^\\d+", "/", ".", "test", "(", "values", "[", "0", "]", ")", ")", "{", "// Found a position", "// Remove angle value, if any", "position", "=", "values", ".", "shift", "(", ")", ".", "replace", "(", "/", "\\s*-?\\d+(?:rad|deg)\\s*", "/", ",", "''", ")", ";", "}", "if", "(", "/", "\\bcircle|ellipse|closest|farthest|contain|cover\\b", "/", ".", "test", "(", "values", "[", "0", "]", ")", ")", "{", "// Found a shape and/or size", "var", "shapeSizeParts", "=", "values", ".", "shift", "(", ")", ".", "split", "(", "/", "\\s+", "/", ")", ";", "if", "(", "shapeSizeParts", "[", "0", "]", "&&", "(", "shapeSizeParts", "[", "0", "]", "===", "'circle'", "||", "shapeSizeParts", "[", "0", "]", "===", "'ellipse'", ")", ")", "{", "shape", "=", "shapeSizeParts", ".", "shift", "(", ")", ";", "}", "if", "(", "shapeSizeParts", "[", "0", "]", ")", "{", "size", "=", "shapeSizeParts", ".", "shift", "(", ")", ";", "}", "// Old keywords are converted to their synonyms", "if", "(", "size", "===", "'cover'", ")", "{", "size", "=", "'farthest-corner'", ";", "}", "else", "if", "(", "size", "===", "'contain'", ")", "{", "size", "=", "'clothest-side'", ";", "}", "}", "return", "func", "+", "'('", "+", "shape", "+", "' '", "+", "size", "+", "' at '", "+", "position", "+", "','", "+", "values", ".", "join", "(", "','", ")", "+", "')'", ";", "}", "return", "func", "+", "'('", "+", "values", ".", "join", "(", "','", ")", "+", "')'", ";", "}" ]
Returns a W3C-valid radial gradient @param {string} prefix Vendor prefix if any ("-moz-", "-webkit-", etc.) @param {string} func Gradient function name ("linear-gradient") @param {string[]} values Array of the gradient function parameters (["0deg", "red 0%", "blue 100%"])
[ "Returns", "a", "W3C", "-", "valid", "radial", "gradient" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/plugins/previewers/prism-previewers.js#L74-L109
4,835
PrismJS/prism
components/prism-javadoclike.js
docCommentSupport
function docCommentSupport(lang, callback) { var tokenName = 'doc-comment'; var grammar = Prism.languages[lang]; if (!grammar) { return; } var token = grammar[tokenName]; if (!token) { // add doc comment: /** */ var definition = {}; definition[tokenName] = { pattern: /(^|[^\\])\/\*\*[^/][\s\S]*?(?:\*\/|$)/, alias: 'comment' }; grammar = Prism.languages.insertBefore(lang, 'comment', definition); token = grammar[tokenName]; } if (token instanceof RegExp) { // convert regex to object token = grammar[tokenName] = { pattern: token }; } if (Array.isArray(token)) { for (var i = 0, l = token.length; i < l; i++) { if (token[i] instanceof RegExp) { token[i] = { pattern: token[i] }; } callback(token[i]); } } else { callback(token); } }
javascript
function docCommentSupport(lang, callback) { var tokenName = 'doc-comment'; var grammar = Prism.languages[lang]; if (!grammar) { return; } var token = grammar[tokenName]; if (!token) { // add doc comment: /** */ var definition = {}; definition[tokenName] = { pattern: /(^|[^\\])\/\*\*[^/][\s\S]*?(?:\*\/|$)/, alias: 'comment' }; grammar = Prism.languages.insertBefore(lang, 'comment', definition); token = grammar[tokenName]; } if (token instanceof RegExp) { // convert regex to object token = grammar[tokenName] = { pattern: token }; } if (Array.isArray(token)) { for (var i = 0, l = token.length; i < l; i++) { if (token[i] instanceof RegExp) { token[i] = { pattern: token[i] }; } callback(token[i]); } } else { callback(token); } }
[ "function", "docCommentSupport", "(", "lang", ",", "callback", ")", "{", "var", "tokenName", "=", "'doc-comment'", ";", "var", "grammar", "=", "Prism", ".", "languages", "[", "lang", "]", ";", "if", "(", "!", "grammar", ")", "{", "return", ";", "}", "var", "token", "=", "grammar", "[", "tokenName", "]", ";", "if", "(", "!", "token", ")", "{", "// add doc comment: /** */", "var", "definition", "=", "{", "}", ";", "definition", "[", "tokenName", "]", "=", "{", "pattern", ":", "/", "(^|[^\\\\])\\/\\*\\*[^/][\\s\\S]*?(?:\\*\\/|$)", "/", ",", "alias", ":", "'comment'", "}", ";", "grammar", "=", "Prism", ".", "languages", ".", "insertBefore", "(", "lang", ",", "'comment'", ",", "definition", ")", ";", "token", "=", "grammar", "[", "tokenName", "]", ";", "}", "if", "(", "token", "instanceof", "RegExp", ")", "{", "// convert regex to object", "token", "=", "grammar", "[", "tokenName", "]", "=", "{", "pattern", ":", "token", "}", ";", "}", "if", "(", "Array", ".", "isArray", "(", "token", ")", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "token", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "token", "[", "i", "]", "instanceof", "RegExp", ")", "{", "token", "[", "i", "]", "=", "{", "pattern", ":", "token", "[", "i", "]", "}", ";", "}", "callback", "(", "token", "[", "i", "]", ")", ";", "}", "}", "else", "{", "callback", "(", "token", ")", ";", "}", "}" ]
Adds doc comment support to the given language and calls a given callback on each doc comment pattern. @param {string} lang the language add doc comment support to. @param {(pattern: {inside: {rest: undefined}}) => void} callback the function called with each doc comment pattern as argument.
[ "Adds", "doc", "comment", "support", "to", "the", "given", "language", "and", "calls", "a", "given", "callback", "on", "each", "doc", "comment", "pattern", "." ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/components/prism-javadoclike.js#L24-L59
4,836
PrismJS/prism
components/prism-javadoclike.js
addSupport
function addSupport(languages, docLanguage) { if (typeof languages === 'string') { languages = [languages]; } languages.forEach(function (lang) { docCommentSupport(lang, function (pattern) { if (!pattern.inside) { pattern.inside = {}; } pattern.inside.rest = docLanguage; }); }); }
javascript
function addSupport(languages, docLanguage) { if (typeof languages === 'string') { languages = [languages]; } languages.forEach(function (lang) { docCommentSupport(lang, function (pattern) { if (!pattern.inside) { pattern.inside = {}; } pattern.inside.rest = docLanguage; }); }); }
[ "function", "addSupport", "(", "languages", ",", "docLanguage", ")", "{", "if", "(", "typeof", "languages", "===", "'string'", ")", "{", "languages", "=", "[", "languages", "]", ";", "}", "languages", ".", "forEach", "(", "function", "(", "lang", ")", "{", "docCommentSupport", "(", "lang", ",", "function", "(", "pattern", ")", "{", "if", "(", "!", "pattern", ".", "inside", ")", "{", "pattern", ".", "inside", "=", "{", "}", ";", "}", "pattern", ".", "inside", ".", "rest", "=", "docLanguage", ";", "}", ")", ";", "}", ")", ";", "}" ]
Adds doc-comment support to the given languages for the given documentation language. @param {string[]|string} languages @param {Object} docLanguage
[ "Adds", "doc", "-", "comment", "support", "to", "the", "given", "languages", "for", "the", "given", "documentation", "language", "." ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/components/prism-javadoclike.js#L67-L80
4,837
PrismJS/prism
plugins/line-numbers/prism-line-numbers.js
function (element) { if (!element) { return null; } return window.getComputedStyle ? getComputedStyle(element) : (element.currentStyle || null); }
javascript
function (element) { if (!element) { return null; } return window.getComputedStyle ? getComputedStyle(element) : (element.currentStyle || null); }
[ "function", "(", "element", ")", "{", "if", "(", "!", "element", ")", "{", "return", "null", ";", "}", "return", "window", ".", "getComputedStyle", "?", "getComputedStyle", "(", "element", ")", ":", "(", "element", ".", "currentStyle", "||", "null", ")", ";", "}" ]
Returns style declarations for the element @param {Element} element
[ "Returns", "style", "declarations", "for", "the", "element" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/plugins/line-numbers/prism-line-numbers.js#L57-L63
4,838
PrismJS/prism
plugins/line-numbers/prism-line-numbers.js
function (element, number) { if (element.tagName !== 'PRE' || !element.classList.contains(PLUGIN_NAME)) { return; } var lineNumberRows = element.querySelector('.line-numbers-rows'); var lineNumberStart = parseInt(element.getAttribute('data-start'), 10) || 1; var lineNumberEnd = lineNumberStart + (lineNumberRows.children.length - 1); if (number < lineNumberStart) { number = lineNumberStart; } if (number > lineNumberEnd) { number = lineNumberEnd; } var lineIndex = number - lineNumberStart; return lineNumberRows.children[lineIndex]; }
javascript
function (element, number) { if (element.tagName !== 'PRE' || !element.classList.contains(PLUGIN_NAME)) { return; } var lineNumberRows = element.querySelector('.line-numbers-rows'); var lineNumberStart = parseInt(element.getAttribute('data-start'), 10) || 1; var lineNumberEnd = lineNumberStart + (lineNumberRows.children.length - 1); if (number < lineNumberStart) { number = lineNumberStart; } if (number > lineNumberEnd) { number = lineNumberEnd; } var lineIndex = number - lineNumberStart; return lineNumberRows.children[lineIndex]; }
[ "function", "(", "element", ",", "number", ")", "{", "if", "(", "element", ".", "tagName", "!==", "'PRE'", "||", "!", "element", ".", "classList", ".", "contains", "(", "PLUGIN_NAME", ")", ")", "{", "return", ";", "}", "var", "lineNumberRows", "=", "element", ".", "querySelector", "(", "'.line-numbers-rows'", ")", ";", "var", "lineNumberStart", "=", "parseInt", "(", "element", ".", "getAttribute", "(", "'data-start'", ")", ",", "10", ")", "||", "1", ";", "var", "lineNumberEnd", "=", "lineNumberStart", "+", "(", "lineNumberRows", ".", "children", ".", "length", "-", "1", ")", ";", "if", "(", "number", "<", "lineNumberStart", ")", "{", "number", "=", "lineNumberStart", ";", "}", "if", "(", "number", ">", "lineNumberEnd", ")", "{", "number", "=", "lineNumberEnd", ";", "}", "var", "lineIndex", "=", "number", "-", "lineNumberStart", ";", "return", "lineNumberRows", ".", "children", "[", "lineIndex", "]", ";", "}" ]
Get node for provided line number @param {Element} element pre element @param {Number} number line number @return {Element|undefined}
[ "Get", "node", "for", "provided", "line", "number" ]
acceb3b56f0e8362a7ef274dbd85b17611df2ec4
https://github.com/PrismJS/prism/blob/acceb3b56f0e8362a7ef274dbd85b17611df2ec4/plugins/line-numbers/prism-line-numbers.js#L146-L165
4,839
fengyuanchen/cropper
dist/cropper.common.js
forEach
function forEach(data, callback) { if (data && isFunction(callback)) { if (Array.isArray(data) || isNumber(data.length) /* array-like */) { var length = data.length; var i = void 0; for (i = 0; i < length; i += 1) { if (callback.call(data, data[i], i, data) === false) { break; } } } else if (isObject(data)) { Object.keys(data).forEach(function (key) { callback.call(data, data[key], key, data); }); } } return data; }
javascript
function forEach(data, callback) { if (data && isFunction(callback)) { if (Array.isArray(data) || isNumber(data.length) /* array-like */) { var length = data.length; var i = void 0; for (i = 0; i < length; i += 1) { if (callback.call(data, data[i], i, data) === false) { break; } } } else if (isObject(data)) { Object.keys(data).forEach(function (key) { callback.call(data, data[key], key, data); }); } } return data; }
[ "function", "forEach", "(", "data", ",", "callback", ")", "{", "if", "(", "data", "&&", "isFunction", "(", "callback", ")", ")", "{", "if", "(", "Array", ".", "isArray", "(", "data", ")", "||", "isNumber", "(", "data", ".", "length", ")", "/* array-like */", ")", "{", "var", "length", "=", "data", ".", "length", ";", "var", "i", "=", "void", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "+=", "1", ")", "{", "if", "(", "callback", ".", "call", "(", "data", ",", "data", "[", "i", "]", ",", "i", ",", "data", ")", "===", "false", ")", "{", "break", ";", "}", "}", "}", "else", "if", "(", "isObject", "(", "data", ")", ")", "{", "Object", ".", "keys", "(", "data", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "callback", ".", "call", "(", "data", ",", "data", "[", "key", "]", ",", "key", ",", "data", ")", ";", "}", ")", ";", "}", "}", "return", "data", ";", "}" ]
Iterate the given data. @param {*} data - The data to iterate. @param {Function} callback - The process function for each element. @returns {*} The original data.
[ "Iterate", "the", "given", "data", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L283-L303
4,840
fengyuanchen/cropper
dist/cropper.common.js
setStyle
function setStyle(element, styles) { var style = element.style; forEach(styles, function (value, property) { if (REGEXP_SUFFIX.test(property) && isNumber(value)) { value += 'px'; } style[property] = value; }); }
javascript
function setStyle(element, styles) { var style = element.style; forEach(styles, function (value, property) { if (REGEXP_SUFFIX.test(property) && isNumber(value)) { value += 'px'; } style[property] = value; }); }
[ "function", "setStyle", "(", "element", ",", "styles", ")", "{", "var", "style", "=", "element", ".", "style", ";", "forEach", "(", "styles", ",", "function", "(", "value", ",", "property", ")", "{", "if", "(", "REGEXP_SUFFIX", ".", "test", "(", "property", ")", "&&", "isNumber", "(", "value", ")", ")", "{", "value", "+=", "'px'", ";", "}", "style", "[", "property", "]", "=", "value", ";", "}", ")", ";", "}" ]
Apply styles to the given element. @param {Element} element - The target element. @param {Object} styles - The styles for applying.
[ "Apply", "styles", "to", "the", "given", "element", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L351-L362
4,841
fengyuanchen/cropper
dist/cropper.common.js
getData
function getData(element, name) { if (isObject(element[name])) { return element[name]; } else if (element.dataset) { return element.dataset[name]; } return element.getAttribute('data-' + hyphenate(name)); }
javascript
function getData(element, name) { if (isObject(element[name])) { return element[name]; } else if (element.dataset) { return element.dataset[name]; } return element.getAttribute('data-' + hyphenate(name)); }
[ "function", "getData", "(", "element", ",", "name", ")", "{", "if", "(", "isObject", "(", "element", "[", "name", "]", ")", ")", "{", "return", "element", "[", "name", "]", ";", "}", "else", "if", "(", "element", ".", "dataset", ")", "{", "return", "element", ".", "dataset", "[", "name", "]", ";", "}", "return", "element", ".", "getAttribute", "(", "'data-'", "+", "hyphenate", "(", "name", ")", ")", ";", "}" ]
Get data from the given element. @param {Element} element - The target element. @param {string} name - The data key to get. @returns {string} The data value.
[ "Get", "data", "from", "the", "given", "element", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L475-L483
4,842
fengyuanchen/cropper
dist/cropper.common.js
setData
function setData(element, name, data) { if (isObject(data)) { element[name] = data; } else if (element.dataset) { element.dataset[name] = data; } else { element.setAttribute('data-' + hyphenate(name), data); } }
javascript
function setData(element, name, data) { if (isObject(data)) { element[name] = data; } else if (element.dataset) { element.dataset[name] = data; } else { element.setAttribute('data-' + hyphenate(name), data); } }
[ "function", "setData", "(", "element", ",", "name", ",", "data", ")", "{", "if", "(", "isObject", "(", "data", ")", ")", "{", "element", "[", "name", "]", "=", "data", ";", "}", "else", "if", "(", "element", ".", "dataset", ")", "{", "element", ".", "dataset", "[", "name", "]", "=", "data", ";", "}", "else", "{", "element", ".", "setAttribute", "(", "'data-'", "+", "hyphenate", "(", "name", ")", ",", "data", ")", ";", "}", "}" ]
Set data to the given element. @param {Element} element - The target element. @param {string} name - The data key to set. @param {string} data - The data value.
[ "Set", "data", "to", "the", "given", "element", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L491-L499
4,843
fengyuanchen/cropper
dist/cropper.common.js
removeData
function removeData(element, name) { if (isObject(element[name])) { try { delete element[name]; } catch (e) { element[name] = undefined; } } else if (element.dataset) { // #128 Safari not allows to delete dataset property try { delete element.dataset[name]; } catch (e) { element.dataset[name] = undefined; } } else { element.removeAttribute('data-' + hyphenate(name)); } }
javascript
function removeData(element, name) { if (isObject(element[name])) { try { delete element[name]; } catch (e) { element[name] = undefined; } } else if (element.dataset) { // #128 Safari not allows to delete dataset property try { delete element.dataset[name]; } catch (e) { element.dataset[name] = undefined; } } else { element.removeAttribute('data-' + hyphenate(name)); } }
[ "function", "removeData", "(", "element", ",", "name", ")", "{", "if", "(", "isObject", "(", "element", "[", "name", "]", ")", ")", "{", "try", "{", "delete", "element", "[", "name", "]", ";", "}", "catch", "(", "e", ")", "{", "element", "[", "name", "]", "=", "undefined", ";", "}", "}", "else", "if", "(", "element", ".", "dataset", ")", "{", "// #128 Safari not allows to delete dataset property", "try", "{", "delete", "element", ".", "dataset", "[", "name", "]", ";", "}", "catch", "(", "e", ")", "{", "element", ".", "dataset", "[", "name", "]", "=", "undefined", ";", "}", "}", "else", "{", "element", ".", "removeAttribute", "(", "'data-'", "+", "hyphenate", "(", "name", ")", ")", ";", "}", "}" ]
Remove data from the given element. @param {Element} element - The target element. @param {string} name - The data key to remove.
[ "Remove", "data", "from", "the", "given", "element", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L506-L523
4,844
fengyuanchen/cropper
dist/cropper.common.js
isCrossOriginURL
function isCrossOriginURL(url) { var parts = url.match(REGEXP_ORIGINS); return parts && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port); }
javascript
function isCrossOriginURL(url) { var parts = url.match(REGEXP_ORIGINS); return parts && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port); }
[ "function", "isCrossOriginURL", "(", "url", ")", "{", "var", "parts", "=", "url", ".", "match", "(", "REGEXP_ORIGINS", ")", ";", "return", "parts", "&&", "(", "parts", "[", "1", "]", "!==", "location", ".", "protocol", "||", "parts", "[", "2", "]", "!==", "location", ".", "hostname", "||", "parts", "[", "3", "]", "!==", "location", ".", "port", ")", ";", "}" ]
Check if the given URL is a cross origin URL. @param {string} url - The target URL. @returns {boolean} Returns `true` if the given URL is a cross origin URL, else `false`.
[ "Check", "if", "the", "given", "URL", "is", "a", "cross", "origin", "URL", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L683-L687
4,845
fengyuanchen/cropper
dist/cropper.common.js
getAdjustedSizes
function getAdjustedSizes(_ref4) // or 'cover' { var aspectRatio = _ref4.aspectRatio, height = _ref4.height, width = _ref4.width; var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain'; var isValidNumber = function isValidNumber(value) { return isFinite(value) && value > 0; }; if (isValidNumber(width) && isValidNumber(height)) { var adjustedWidth = height * aspectRatio; if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) { height = width / aspectRatio; } else { width = height * aspectRatio; } } else if (isValidNumber(width)) { height = width / aspectRatio; } else if (isValidNumber(height)) { width = height * aspectRatio; } return { width: width, height: height }; }
javascript
function getAdjustedSizes(_ref4) // or 'cover' { var aspectRatio = _ref4.aspectRatio, height = _ref4.height, width = _ref4.width; var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain'; var isValidNumber = function isValidNumber(value) { return isFinite(value) && value > 0; }; if (isValidNumber(width) && isValidNumber(height)) { var adjustedWidth = height * aspectRatio; if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) { height = width / aspectRatio; } else { width = height * aspectRatio; } } else if (isValidNumber(width)) { height = width / aspectRatio; } else if (isValidNumber(height)) { width = height * aspectRatio; } return { width: width, height: height }; }
[ "function", "getAdjustedSizes", "(", "_ref4", ")", "// or 'cover'", "{", "var", "aspectRatio", "=", "_ref4", ".", "aspectRatio", ",", "height", "=", "_ref4", ".", "height", ",", "width", "=", "_ref4", ".", "width", ";", "var", "type", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "'contain'", ";", "var", "isValidNumber", "=", "function", "isValidNumber", "(", "value", ")", "{", "return", "isFinite", "(", "value", ")", "&&", "value", ">", "0", ";", "}", ";", "if", "(", "isValidNumber", "(", "width", ")", "&&", "isValidNumber", "(", "height", ")", ")", "{", "var", "adjustedWidth", "=", "height", "*", "aspectRatio", ";", "if", "(", "type", "===", "'contain'", "&&", "adjustedWidth", ">", "width", "||", "type", "===", "'cover'", "&&", "adjustedWidth", "<", "width", ")", "{", "height", "=", "width", "/", "aspectRatio", ";", "}", "else", "{", "width", "=", "height", "*", "aspectRatio", ";", "}", "}", "else", "if", "(", "isValidNumber", "(", "width", ")", ")", "{", "height", "=", "width", "/", "aspectRatio", ";", "}", "else", "if", "(", "isValidNumber", "(", "height", ")", ")", "{", "width", "=", "height", "*", "aspectRatio", ";", "}", "return", "{", "width", ":", "width", ",", "height", ":", "height", "}", ";", "}" ]
Get the max sizes in a rectangle under the given aspect ratio. @param {Object} data - The original sizes. @param {string} [type='contain'] - The adjust type. @returns {Object} The result sizes.
[ "Get", "the", "max", "sizes", "in", "a", "rectangle", "under", "the", "given", "aspect", "ratio", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L836-L865
4,846
fengyuanchen/cropper
dist/cropper.common.js
arrayBufferToDataURL
function arrayBufferToDataURL(arrayBuffer, mimeType) { var uint8 = new Uint8Array(arrayBuffer); var data = ''; // TypedArray.prototype.forEach is not supported in some browsers. forEach(uint8, function (value) { data += fromCharCode(value); }); return 'data:' + mimeType + ';base64,' + btoa(data); }
javascript
function arrayBufferToDataURL(arrayBuffer, mimeType) { var uint8 = new Uint8Array(arrayBuffer); var data = ''; // TypedArray.prototype.forEach is not supported in some browsers. forEach(uint8, function (value) { data += fromCharCode(value); }); return 'data:' + mimeType + ';base64,' + btoa(data); }
[ "function", "arrayBufferToDataURL", "(", "arrayBuffer", ",", "mimeType", ")", "{", "var", "uint8", "=", "new", "Uint8Array", "(", "arrayBuffer", ")", ";", "var", "data", "=", "''", ";", "// TypedArray.prototype.forEach is not supported in some browsers.", "forEach", "(", "uint8", ",", "function", "(", "value", ")", "{", "data", "+=", "fromCharCode", "(", "value", ")", ";", "}", ")", ";", "return", "'data:'", "+", "mimeType", "+", "';base64,'", "+", "btoa", "(", "data", ")", ";", "}" ]
Transform array buffer to Data URL. @param {ArrayBuffer} arrayBuffer - The array buffer to transform. @param {string} mimeType - The mime type of the Data URL. @returns {string} The result Data URL.
[ "Transform", "array", "buffer", "to", "Data", "URL", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L1034-L1044
4,847
fengyuanchen/cropper
dist/cropper.common.js
destroy
function destroy() { var element = this.element; if (!getData(element, NAMESPACE)) { return this; } if (this.isImg && this.replaced) { element.src = this.originalUrl; } this.uncreate(); removeData(element, NAMESPACE); return this; }
javascript
function destroy() { var element = this.element; if (!getData(element, NAMESPACE)) { return this; } if (this.isImg && this.replaced) { element.src = this.originalUrl; } this.uncreate(); removeData(element, NAMESPACE); return this; }
[ "function", "destroy", "(", ")", "{", "var", "element", "=", "this", ".", "element", ";", "if", "(", "!", "getData", "(", "element", ",", "NAMESPACE", ")", ")", "{", "return", "this", ";", "}", "if", "(", "this", ".", "isImg", "&&", "this", ".", "replaced", ")", "{", "element", ".", "src", "=", "this", ".", "originalUrl", ";", "}", "this", ".", "uncreate", "(", ")", ";", "removeData", "(", "element", ",", "NAMESPACE", ")", ";", "return", "this", ";", "}" ]
Destroy the cropper and remove the instance from the image @returns {Cropper} this
[ "Destroy", "the", "cropper", "and", "remove", "the", "instance", "from", "the", "image" ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L2559-L2575
4,848
fengyuanchen/cropper
dist/cropper.common.js
zoomTo
function zoomTo(ratio, pivot, _originalEvent) { var options = this.options, canvasData = this.canvasData; var width = canvasData.width, height = canvasData.height, naturalWidth = canvasData.naturalWidth, naturalHeight = canvasData.naturalHeight; ratio = Number(ratio); if (ratio >= 0 && this.ready && !this.disabled && options.zoomable) { var newWidth = naturalWidth * ratio; var newHeight = naturalHeight * ratio; if (dispatchEvent(this.element, EVENT_ZOOM, { originalEvent: _originalEvent, oldRatio: width / naturalWidth, ratio: newWidth / naturalWidth }) === false) { return this; } if (_originalEvent) { var pointers = this.pointers; var offset = getOffset(this.cropper); var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : { pageX: _originalEvent.pageX, pageY: _originalEvent.pageY }; // Zoom from the triggering point of the event canvasData.left -= (newWidth - width) * ((center.pageX - offset.left - canvasData.left) / width); canvasData.top -= (newHeight - height) * ((center.pageY - offset.top - canvasData.top) / height); } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) { canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width); canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height); } else { // Zoom from the center of the canvas canvasData.left -= (newWidth - width) / 2; canvasData.top -= (newHeight - height) / 2; } canvasData.width = newWidth; canvasData.height = newHeight; this.renderCanvas(true); } return this; }
javascript
function zoomTo(ratio, pivot, _originalEvent) { var options = this.options, canvasData = this.canvasData; var width = canvasData.width, height = canvasData.height, naturalWidth = canvasData.naturalWidth, naturalHeight = canvasData.naturalHeight; ratio = Number(ratio); if (ratio >= 0 && this.ready && !this.disabled && options.zoomable) { var newWidth = naturalWidth * ratio; var newHeight = naturalHeight * ratio; if (dispatchEvent(this.element, EVENT_ZOOM, { originalEvent: _originalEvent, oldRatio: width / naturalWidth, ratio: newWidth / naturalWidth }) === false) { return this; } if (_originalEvent) { var pointers = this.pointers; var offset = getOffset(this.cropper); var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : { pageX: _originalEvent.pageX, pageY: _originalEvent.pageY }; // Zoom from the triggering point of the event canvasData.left -= (newWidth - width) * ((center.pageX - offset.left - canvasData.left) / width); canvasData.top -= (newHeight - height) * ((center.pageY - offset.top - canvasData.top) / height); } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) { canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width); canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height); } else { // Zoom from the center of the canvas canvasData.left -= (newWidth - width) / 2; canvasData.top -= (newHeight - height) / 2; } canvasData.width = newWidth; canvasData.height = newHeight; this.renderCanvas(true); } return this; }
[ "function", "zoomTo", "(", "ratio", ",", "pivot", ",", "_originalEvent", ")", "{", "var", "options", "=", "this", ".", "options", ",", "canvasData", "=", "this", ".", "canvasData", ";", "var", "width", "=", "canvasData", ".", "width", ",", "height", "=", "canvasData", ".", "height", ",", "naturalWidth", "=", "canvasData", ".", "naturalWidth", ",", "naturalHeight", "=", "canvasData", ".", "naturalHeight", ";", "ratio", "=", "Number", "(", "ratio", ")", ";", "if", "(", "ratio", ">=", "0", "&&", "this", ".", "ready", "&&", "!", "this", ".", "disabled", "&&", "options", ".", "zoomable", ")", "{", "var", "newWidth", "=", "naturalWidth", "*", "ratio", ";", "var", "newHeight", "=", "naturalHeight", "*", "ratio", ";", "if", "(", "dispatchEvent", "(", "this", ".", "element", ",", "EVENT_ZOOM", ",", "{", "originalEvent", ":", "_originalEvent", ",", "oldRatio", ":", "width", "/", "naturalWidth", ",", "ratio", ":", "newWidth", "/", "naturalWidth", "}", ")", "===", "false", ")", "{", "return", "this", ";", "}", "if", "(", "_originalEvent", ")", "{", "var", "pointers", "=", "this", ".", "pointers", ";", "var", "offset", "=", "getOffset", "(", "this", ".", "cropper", ")", ";", "var", "center", "=", "pointers", "&&", "Object", ".", "keys", "(", "pointers", ")", ".", "length", "?", "getPointersCenter", "(", "pointers", ")", ":", "{", "pageX", ":", "_originalEvent", ".", "pageX", ",", "pageY", ":", "_originalEvent", ".", "pageY", "}", ";", "// Zoom from the triggering point of the event", "canvasData", ".", "left", "-=", "(", "newWidth", "-", "width", ")", "*", "(", "(", "center", ".", "pageX", "-", "offset", ".", "left", "-", "canvasData", ".", "left", ")", "/", "width", ")", ";", "canvasData", ".", "top", "-=", "(", "newHeight", "-", "height", ")", "*", "(", "(", "center", ".", "pageY", "-", "offset", ".", "top", "-", "canvasData", ".", "top", ")", "/", "height", ")", ";", "}", "else", "if", "(", "isPlainObject", "(", "pivot", ")", "&&", "isNumber", "(", "pivot", ".", "x", ")", "&&", "isNumber", "(", "pivot", ".", "y", ")", ")", "{", "canvasData", ".", "left", "-=", "(", "newWidth", "-", "width", ")", "*", "(", "(", "pivot", ".", "x", "-", "canvasData", ".", "left", ")", "/", "width", ")", ";", "canvasData", ".", "top", "-=", "(", "newHeight", "-", "height", ")", "*", "(", "(", "pivot", ".", "y", "-", "canvasData", ".", "top", ")", "/", "height", ")", ";", "}", "else", "{", "// Zoom from the center of the canvas", "canvasData", ".", "left", "-=", "(", "newWidth", "-", "width", ")", "/", "2", ";", "canvasData", ".", "top", "-=", "(", "newHeight", "-", "height", ")", "/", "2", ";", "}", "canvasData", ".", "width", "=", "newWidth", ";", "canvasData", ".", "height", "=", "newHeight", ";", "this", ".", "renderCanvas", "(", "true", ")", ";", "}", "return", "this", ";", "}" ]
Zoom the canvas to an absolute ratio @param {number} ratio - The target ratio. @param {Object} pivot - The zoom pivot point coordinate. @param {Event} _originalEvent - The original event if any. @returns {Cropper} this
[ "Zoom", "the", "canvas", "to", "an", "absolute", "ratio" ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L2659-L2709
4,849
fengyuanchen/cropper
dist/cropper.common.js
setData$$1
function setData$$1(data) { var options = this.options, imageData = this.imageData, canvasData = this.canvasData; var cropBoxData = {}; if (this.ready && !this.disabled && isPlainObject(data)) { var transformed = false; if (options.rotatable) { if (isNumber(data.rotate) && data.rotate !== imageData.rotate) { imageData.rotate = data.rotate; transformed = true; } } if (options.scalable) { if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) { imageData.scaleX = data.scaleX; transformed = true; } if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) { imageData.scaleY = data.scaleY; transformed = true; } } if (transformed) { this.renderCanvas(true, true); } var ratio = imageData.width / imageData.naturalWidth; if (isNumber(data.x)) { cropBoxData.left = data.x * ratio + canvasData.left; } if (isNumber(data.y)) { cropBoxData.top = data.y * ratio + canvasData.top; } if (isNumber(data.width)) { cropBoxData.width = data.width * ratio; } if (isNumber(data.height)) { cropBoxData.height = data.height * ratio; } this.setCropBoxData(cropBoxData); } return this; }
javascript
function setData$$1(data) { var options = this.options, imageData = this.imageData, canvasData = this.canvasData; var cropBoxData = {}; if (this.ready && !this.disabled && isPlainObject(data)) { var transformed = false; if (options.rotatable) { if (isNumber(data.rotate) && data.rotate !== imageData.rotate) { imageData.rotate = data.rotate; transformed = true; } } if (options.scalable) { if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) { imageData.scaleX = data.scaleX; transformed = true; } if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) { imageData.scaleY = data.scaleY; transformed = true; } } if (transformed) { this.renderCanvas(true, true); } var ratio = imageData.width / imageData.naturalWidth; if (isNumber(data.x)) { cropBoxData.left = data.x * ratio + canvasData.left; } if (isNumber(data.y)) { cropBoxData.top = data.y * ratio + canvasData.top; } if (isNumber(data.width)) { cropBoxData.width = data.width * ratio; } if (isNumber(data.height)) { cropBoxData.height = data.height * ratio; } this.setCropBoxData(cropBoxData); } return this; }
[ "function", "setData$$1", "(", "data", ")", "{", "var", "options", "=", "this", ".", "options", ",", "imageData", "=", "this", ".", "imageData", ",", "canvasData", "=", "this", ".", "canvasData", ";", "var", "cropBoxData", "=", "{", "}", ";", "if", "(", "this", ".", "ready", "&&", "!", "this", ".", "disabled", "&&", "isPlainObject", "(", "data", ")", ")", "{", "var", "transformed", "=", "false", ";", "if", "(", "options", ".", "rotatable", ")", "{", "if", "(", "isNumber", "(", "data", ".", "rotate", ")", "&&", "data", ".", "rotate", "!==", "imageData", ".", "rotate", ")", "{", "imageData", ".", "rotate", "=", "data", ".", "rotate", ";", "transformed", "=", "true", ";", "}", "}", "if", "(", "options", ".", "scalable", ")", "{", "if", "(", "isNumber", "(", "data", ".", "scaleX", ")", "&&", "data", ".", "scaleX", "!==", "imageData", ".", "scaleX", ")", "{", "imageData", ".", "scaleX", "=", "data", ".", "scaleX", ";", "transformed", "=", "true", ";", "}", "if", "(", "isNumber", "(", "data", ".", "scaleY", ")", "&&", "data", ".", "scaleY", "!==", "imageData", ".", "scaleY", ")", "{", "imageData", ".", "scaleY", "=", "data", ".", "scaleY", ";", "transformed", "=", "true", ";", "}", "}", "if", "(", "transformed", ")", "{", "this", ".", "renderCanvas", "(", "true", ",", "true", ")", ";", "}", "var", "ratio", "=", "imageData", ".", "width", "/", "imageData", ".", "naturalWidth", ";", "if", "(", "isNumber", "(", "data", ".", "x", ")", ")", "{", "cropBoxData", ".", "left", "=", "data", ".", "x", "*", "ratio", "+", "canvasData", ".", "left", ";", "}", "if", "(", "isNumber", "(", "data", ".", "y", ")", ")", "{", "cropBoxData", ".", "top", "=", "data", ".", "y", "*", "ratio", "+", "canvasData", ".", "top", ";", "}", "if", "(", "isNumber", "(", "data", ".", "width", ")", ")", "{", "cropBoxData", ".", "width", "=", "data", ".", "width", "*", "ratio", ";", "}", "if", "(", "isNumber", "(", "data", ".", "height", ")", ")", "{", "cropBoxData", ".", "height", "=", "data", ".", "height", "*", "ratio", ";", "}", "this", ".", "setCropBoxData", "(", "cropBoxData", ")", ";", "}", "return", "this", ";", "}" ]
Set the cropped area position and size with new data @param {Object} data - The new data. @returns {Cropper} this
[ "Set", "the", "cropped", "area", "position", "and", "size", "with", "new", "data" ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L2855-L2910
4,850
fengyuanchen/cropper
dist/cropper.common.js
getCropBoxData
function getCropBoxData() { var cropBoxData = this.cropBoxData; var data = void 0; if (this.ready && this.cropped) { data = { left: cropBoxData.left, top: cropBoxData.top, width: cropBoxData.width, height: cropBoxData.height }; } return data || {}; }
javascript
function getCropBoxData() { var cropBoxData = this.cropBoxData; var data = void 0; if (this.ready && this.cropped) { data = { left: cropBoxData.left, top: cropBoxData.top, width: cropBoxData.width, height: cropBoxData.height }; } return data || {}; }
[ "function", "getCropBoxData", "(", ")", "{", "var", "cropBoxData", "=", "this", ".", "cropBoxData", ";", "var", "data", "=", "void", "0", ";", "if", "(", "this", ".", "ready", "&&", "this", ".", "cropped", ")", "{", "data", "=", "{", "left", ":", "cropBoxData", ".", "left", ",", "top", ":", "cropBoxData", ".", "top", ",", "width", ":", "cropBoxData", ".", "width", ",", "height", ":", "cropBoxData", ".", "height", "}", ";", "}", "return", "data", "||", "{", "}", ";", "}" ]
Get the crop box position and size data. @returns {Object} The result crop box data.
[ "Get", "the", "crop", "box", "position", "and", "size", "data", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L2988-L3003
4,851
fengyuanchen/cropper
dist/cropper.common.js
setCropBoxData
function setCropBoxData(data) { var cropBoxData = this.cropBoxData; var aspectRatio = this.options.aspectRatio; var widthChanged = void 0; var heightChanged = void 0; if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) { if (isNumber(data.left)) { cropBoxData.left = data.left; } if (isNumber(data.top)) { cropBoxData.top = data.top; } if (isNumber(data.width) && data.width !== cropBoxData.width) { widthChanged = true; cropBoxData.width = data.width; } if (isNumber(data.height) && data.height !== cropBoxData.height) { heightChanged = true; cropBoxData.height = data.height; } if (aspectRatio) { if (widthChanged) { cropBoxData.height = cropBoxData.width / aspectRatio; } else if (heightChanged) { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.renderCropBox(); } return this; }
javascript
function setCropBoxData(data) { var cropBoxData = this.cropBoxData; var aspectRatio = this.options.aspectRatio; var widthChanged = void 0; var heightChanged = void 0; if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) { if (isNumber(data.left)) { cropBoxData.left = data.left; } if (isNumber(data.top)) { cropBoxData.top = data.top; } if (isNumber(data.width) && data.width !== cropBoxData.width) { widthChanged = true; cropBoxData.width = data.width; } if (isNumber(data.height) && data.height !== cropBoxData.height) { heightChanged = true; cropBoxData.height = data.height; } if (aspectRatio) { if (widthChanged) { cropBoxData.height = cropBoxData.width / aspectRatio; } else if (heightChanged) { cropBoxData.width = cropBoxData.height * aspectRatio; } } this.renderCropBox(); } return this; }
[ "function", "setCropBoxData", "(", "data", ")", "{", "var", "cropBoxData", "=", "this", ".", "cropBoxData", ";", "var", "aspectRatio", "=", "this", ".", "options", ".", "aspectRatio", ";", "var", "widthChanged", "=", "void", "0", ";", "var", "heightChanged", "=", "void", "0", ";", "if", "(", "this", ".", "ready", "&&", "this", ".", "cropped", "&&", "!", "this", ".", "disabled", "&&", "isPlainObject", "(", "data", ")", ")", "{", "if", "(", "isNumber", "(", "data", ".", "left", ")", ")", "{", "cropBoxData", ".", "left", "=", "data", ".", "left", ";", "}", "if", "(", "isNumber", "(", "data", ".", "top", ")", ")", "{", "cropBoxData", ".", "top", "=", "data", ".", "top", ";", "}", "if", "(", "isNumber", "(", "data", ".", "width", ")", "&&", "data", ".", "width", "!==", "cropBoxData", ".", "width", ")", "{", "widthChanged", "=", "true", ";", "cropBoxData", ".", "width", "=", "data", ".", "width", ";", "}", "if", "(", "isNumber", "(", "data", ".", "height", ")", "&&", "data", ".", "height", "!==", "cropBoxData", ".", "height", ")", "{", "heightChanged", "=", "true", ";", "cropBoxData", ".", "height", "=", "data", ".", "height", ";", "}", "if", "(", "aspectRatio", ")", "{", "if", "(", "widthChanged", ")", "{", "cropBoxData", ".", "height", "=", "cropBoxData", ".", "width", "/", "aspectRatio", ";", "}", "else", "if", "(", "heightChanged", ")", "{", "cropBoxData", ".", "width", "=", "cropBoxData", ".", "height", "*", "aspectRatio", ";", "}", "}", "this", ".", "renderCropBox", "(", ")", ";", "}", "return", "this", ";", "}" ]
Set the crop box position and size with new data. @param {Object} data - The new crop box data. @returns {Cropper} this
[ "Set", "the", "crop", "box", "position", "and", "size", "with", "new", "data", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L3011-L3049
4,852
fengyuanchen/cropper
dist/cropper.common.js
Cropper
function Cropper(element) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; classCallCheck(this, Cropper); if (!element || !REGEXP_TAG_NAME.test(element.tagName)) { throw new Error('The first argument is required and must be an <img> or <canvas> element.'); } this.element = element; this.options = assign({}, DEFAULTS, isPlainObject(options) && options); this.cropped = false; this.disabled = false; this.pointers = {}; this.ready = false; this.reloading = false; this.replaced = false; this.sized = false; this.sizing = false; this.init(); }
javascript
function Cropper(element) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; classCallCheck(this, Cropper); if (!element || !REGEXP_TAG_NAME.test(element.tagName)) { throw new Error('The first argument is required and must be an <img> or <canvas> element.'); } this.element = element; this.options = assign({}, DEFAULTS, isPlainObject(options) && options); this.cropped = false; this.disabled = false; this.pointers = {}; this.ready = false; this.reloading = false; this.replaced = false; this.sized = false; this.sizing = false; this.init(); }
[ "function", "Cropper", "(", "element", ")", "{", "var", "options", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "{", "}", ";", "classCallCheck", "(", "this", ",", "Cropper", ")", ";", "if", "(", "!", "element", "||", "!", "REGEXP_TAG_NAME", ".", "test", "(", "element", ".", "tagName", ")", ")", "{", "throw", "new", "Error", "(", "'The first argument is required and must be an <img> or <canvas> element.'", ")", ";", "}", "this", ".", "element", "=", "element", ";", "this", ".", "options", "=", "assign", "(", "{", "}", ",", "DEFAULTS", ",", "isPlainObject", "(", "options", ")", "&&", "options", ")", ";", "this", ".", "cropped", "=", "false", ";", "this", ".", "disabled", "=", "false", ";", "this", ".", "pointers", "=", "{", "}", ";", "this", ".", "ready", "=", "false", ";", "this", ".", "reloading", "=", "false", ";", "this", ".", "replaced", "=", "false", ";", "this", ".", "sized", "=", "false", ";", "this", ".", "sizing", "=", "false", ";", "this", ".", "init", "(", ")", ";", "}" ]
Create a new Cropper. @param {Element} element - The target element for cropping. @param {Object} [options={}] - The configuration options.
[ "Create", "a", "new", "Cropper", "." ]
6677332a6a375b647f58808dfc24ea09f5804041
https://github.com/fengyuanchen/cropper/blob/6677332a6a375b647f58808dfc24ea09f5804041/dist/cropper.common.js#L3266-L3285
4,853
grpc/grpc-node
packages/grpc-native-core/src/client.js
ClientWritableStream
function ClientWritableStream(call) { Writable.call(this, {objectMode: true}); this.call = call; var self = this; this.on('finish', function() { self.call.halfClose(); }); }
javascript
function ClientWritableStream(call) { Writable.call(this, {objectMode: true}); this.call = call; var self = this; this.on('finish', function() { self.call.halfClose(); }); }
[ "function", "ClientWritableStream", "(", "call", ")", "{", "Writable", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "call", "=", "call", ";", "var", "self", "=", "this", ";", "this", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "self", ".", "call", ".", "halfClose", "(", ")", ";", "}", ")", ";", "}" ]
A stream that the client can write to. Used for calls that are streaming from the client side. @constructor grpc~ClientWritableStream @extends external:Writable @borrows grpc~ClientUnaryCall#cancel as grpc~ClientWritableStream#cancel @borrows grpc~ClientUnaryCall#getPeer as grpc~ClientWritableStream#getPeer @borrows grpc~ClientUnaryCall#event:metadata as grpc~ClientWritableStream#metadata @borrows grpc~ClientUnaryCall#event:status as grpc~ClientWritableStream#status @param {InterceptingCall} call Exposes gRPC request operations, processed by an interceptor stack.
[ "A", "stream", "that", "the", "client", "can", "write", "to", ".", "Used", "for", "calls", "that", "are", "streaming", "from", "the", "client", "side", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client.js#L97-L104
4,854
grpc/grpc-node
packages/grpc-native-core/src/client.js
_write
function _write(chunk, encoding, callback) { /* jshint validthis: true */ var self = this; if (this.writeFailed) { /* Once a write fails, just call the callback immediately to let the caller flush any pending writes. */ setImmediate(callback); return; } var outerCallback = function(err, event) { if (err) { /* Assume that the call is complete and that writing failed because a status was received. In that case, set a flag to discard all future writes */ self.writeFailed = true; } callback(); }; var context = { encoding: encoding, callback: outerCallback }; this.call.sendMessageWithContext(context, chunk); }
javascript
function _write(chunk, encoding, callback) { /* jshint validthis: true */ var self = this; if (this.writeFailed) { /* Once a write fails, just call the callback immediately to let the caller flush any pending writes. */ setImmediate(callback); return; } var outerCallback = function(err, event) { if (err) { /* Assume that the call is complete and that writing failed because a status was received. In that case, set a flag to discard all future writes */ self.writeFailed = true; } callback(); }; var context = { encoding: encoding, callback: outerCallback }; this.call.sendMessageWithContext(context, chunk); }
[ "function", "_write", "(", "chunk", ",", "encoding", ",", "callback", ")", "{", "/* jshint validthis: true */", "var", "self", "=", "this", ";", "if", "(", "this", ".", "writeFailed", ")", "{", "/* Once a write fails, just call the callback immediately to let the caller\n flush any pending writes. */", "setImmediate", "(", "callback", ")", ";", "return", ";", "}", "var", "outerCallback", "=", "function", "(", "err", ",", "event", ")", "{", "if", "(", "err", ")", "{", "/* Assume that the call is complete and that writing failed because a\n status was received. In that case, set a flag to discard all future\n writes */", "self", ".", "writeFailed", "=", "true", ";", "}", "callback", "(", ")", ";", "}", ";", "var", "context", "=", "{", "encoding", ":", "encoding", ",", "callback", ":", "outerCallback", "}", ";", "this", ".", "call", ".", "sendMessageWithContext", "(", "context", ",", "chunk", ")", ";", "}" ]
Write a message to the request stream. If serializing the argument fails, the call will be cancelled and the stream will end with an error. @name grpc~ClientWritableStream#write @kind function @override @param {*} message The message to write. Must be a valid argument to the serialize function of the corresponding method @param {grpc.writeFlags} flags Flags to modify how the message is written @param {Function} callback Callback for when this chunk of data is flushed @return {boolean} As defined for [Writable]{@link external:Writable} Attempt to write the given chunk. Calls the callback when done. This is an implementation of a method needed for implementing stream.Writable. @private @param {*} chunk The chunk to write @param {grpc.writeFlags} encoding Used to pass write flags @param {function(Error=)} callback Called when the write is complete
[ "Write", "a", "message", "to", "the", "request", "stream", ".", "If", "serializing", "the", "argument", "fails", "the", "call", "will", "be", "cancelled", "and", "the", "stream", "will", "end", "with", "an", "error", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client.js#L127-L150
4,855
grpc/grpc-node
packages/grpc-native-core/src/client.js
ClientReadableStream
function ClientReadableStream(call) { Readable.call(this, {objectMode: true}); this.call = call; this.finished = false; this.reading = false; /* Status generated from reading messages from the server. Overrides the * status from the server if not OK */ this.read_status = null; /* Status received from the server. */ this.received_status = null; }
javascript
function ClientReadableStream(call) { Readable.call(this, {objectMode: true}); this.call = call; this.finished = false; this.reading = false; /* Status generated from reading messages from the server. Overrides the * status from the server if not OK */ this.read_status = null; /* Status received from the server. */ this.received_status = null; }
[ "function", "ClientReadableStream", "(", "call", ")", "{", "Readable", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "call", "=", "call", ";", "this", ".", "finished", "=", "false", ";", "this", ".", "reading", "=", "false", ";", "/* Status generated from reading messages from the server. Overrides the\n * status from the server if not OK */", "this", ".", "read_status", "=", "null", ";", "/* Status received from the server. */", "this", ".", "received_status", "=", "null", ";", "}" ]
A stream that the client can read from. Used for calls that are streaming from the server side. @constructor grpc~ClientReadableStream @extends external:Readable @borrows grpc~ClientUnaryCall#cancel as grpc~ClientReadableStream#cancel @borrows grpc~ClientUnaryCall#getPeer as grpc~ClientReadableStream#getPeer @borrows grpc~ClientUnaryCall#event:metadata as grpc~ClientReadableStream#metadata @borrows grpc~ClientUnaryCall#event:status as grpc~ClientReadableStream#status @param {InterceptingCall} call Exposes gRPC request operations, processed by an interceptor stack.
[ "A", "stream", "that", "the", "client", "can", "read", "from", ".", "Used", "for", "calls", "that", "are", "streaming", "from", "the", "server", "side", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client.js#L170-L180
4,856
grpc/grpc-node
packages/grpc-native-core/src/client.js
_readsDone
function _readsDone(status) { /* jshint validthis: true */ if (!status) { status = {code: constants.status.OK, details: 'OK'}; } if (status.code !== constants.status.OK) { this.call.cancelWithStatus(status.code, status.details); } this.finished = true; this.read_status = status; this._emitStatusIfDone(); }
javascript
function _readsDone(status) { /* jshint validthis: true */ if (!status) { status = {code: constants.status.OK, details: 'OK'}; } if (status.code !== constants.status.OK) { this.call.cancelWithStatus(status.code, status.details); } this.finished = true; this.read_status = status; this._emitStatusIfDone(); }
[ "function", "_readsDone", "(", "status", ")", "{", "/* jshint validthis: true */", "if", "(", "!", "status", ")", "{", "status", "=", "{", "code", ":", "constants", ".", "status", ".", "OK", ",", "details", ":", "'OK'", "}", ";", "}", "if", "(", "status", ".", "code", "!==", "constants", ".", "status", ".", "OK", ")", "{", "this", ".", "call", ".", "cancelWithStatus", "(", "status", ".", "code", ",", "status", ".", "details", ")", ";", "}", "this", ".", "finished", "=", "true", ";", "this", ".", "read_status", "=", "status", ";", "this", ".", "_emitStatusIfDone", "(", ")", ";", "}" ]
Called when all messages from the server have been processed. The status parameter indicates that the call should end with that status. status defaults to OK if not provided. @param {Object!} status The status that the call should end with @private
[ "Called", "when", "all", "messages", "from", "the", "server", "have", "been", "processed", ".", "The", "status", "parameter", "indicates", "that", "the", "call", "should", "end", "with", "that", "status", ".", "status", "defaults", "to", "OK", "if", "not", "provided", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client.js#L189-L200
4,857
grpc/grpc-node
packages/grpc-native-core/src/client.js
_emitStatusIfDone
function _emitStatusIfDone() { /* jshint validthis: true */ var status; if (this.read_status && this.received_status) { if (this.read_status.code !== constants.status.OK) { status = this.read_status; } else { status = this.received_status; } if (status.code === constants.status.OK) { this.push(null); } else { var error = common.createStatusError(status); this.emit('error', error); } this.emit('status', status); } }
javascript
function _emitStatusIfDone() { /* jshint validthis: true */ var status; if (this.read_status && this.received_status) { if (this.read_status.code !== constants.status.OK) { status = this.read_status; } else { status = this.received_status; } if (status.code === constants.status.OK) { this.push(null); } else { var error = common.createStatusError(status); this.emit('error', error); } this.emit('status', status); } }
[ "function", "_emitStatusIfDone", "(", ")", "{", "/* jshint validthis: true */", "var", "status", ";", "if", "(", "this", ".", "read_status", "&&", "this", ".", "received_status", ")", "{", "if", "(", "this", ".", "read_status", ".", "code", "!==", "constants", ".", "status", ".", "OK", ")", "{", "status", "=", "this", ".", "read_status", ";", "}", "else", "{", "status", "=", "this", ".", "received_status", ";", "}", "if", "(", "status", ".", "code", "===", "constants", ".", "status", ".", "OK", ")", "{", "this", ".", "push", "(", "null", ")", ";", "}", "else", "{", "var", "error", "=", "common", ".", "createStatusError", "(", "status", ")", ";", "this", ".", "emit", "(", "'error'", ",", "error", ")", ";", "}", "this", ".", "emit", "(", "'status'", ",", "status", ")", ";", "}", "}" ]
If we have both processed all incoming messages and received the status from the server, emit the status. Otherwise, do nothing. @private
[ "If", "we", "have", "both", "processed", "all", "incoming", "messages", "and", "received", "the", "status", "from", "the", "server", "emit", "the", "status", ".", "Otherwise", "do", "nothing", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client.js#L221-L238
4,858
grpc/grpc-node
packages/grpc-native-core/src/client.js
_read
function _read(size) { /* jshint validthis: true */ if (this.finished) { this.push(null); } else { if (!this.reading) { this.reading = true; var context = { stream: this }; this.call.recvMessageWithContext(context); } } }
javascript
function _read(size) { /* jshint validthis: true */ if (this.finished) { this.push(null); } else { if (!this.reading) { this.reading = true; var context = { stream: this }; this.call.recvMessageWithContext(context); } } }
[ "function", "_read", "(", "size", ")", "{", "/* jshint validthis: true */", "if", "(", "this", ".", "finished", ")", "{", "this", ".", "push", "(", "null", ")", ";", "}", "else", "{", "if", "(", "!", "this", ".", "reading", ")", "{", "this", ".", "reading", "=", "true", ";", "var", "context", "=", "{", "stream", ":", "this", "}", ";", "this", ".", "call", ".", "recvMessageWithContext", "(", "context", ")", ";", "}", "}", "}" ]
Read the next object from the stream. @private @param {*} size Ignored because we use objectMode=true
[ "Read", "the", "next", "object", "from", "the", "stream", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client.js#L247-L260
4,859
grpc/grpc-node
packages/grpc-native-core/src/client.js
ClientDuplexStream
function ClientDuplexStream(call) { Duplex.call(this, {objectMode: true}); this.call = call; /* Status generated from reading messages from the server. Overrides the * status from the server if not OK */ this.read_status = null; /* Status received from the server. */ this.received_status = null; var self = this; this.on('finish', function() { self.call.halfClose(); }); }
javascript
function ClientDuplexStream(call) { Duplex.call(this, {objectMode: true}); this.call = call; /* Status generated from reading messages from the server. Overrides the * status from the server if not OK */ this.read_status = null; /* Status received from the server. */ this.received_status = null; var self = this; this.on('finish', function() { self.call.halfClose(); }); }
[ "function", "ClientDuplexStream", "(", "call", ")", "{", "Duplex", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "call", "=", "call", ";", "/* Status generated from reading messages from the server. Overrides the\n * status from the server if not OK */", "this", ".", "read_status", "=", "null", ";", "/* Status received from the server. */", "this", ".", "received_status", "=", "null", ";", "var", "self", "=", "this", ";", "this", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "self", ".", "call", ".", "halfClose", "(", ")", ";", "}", ")", ";", "}" ]
A stream that the client can read from or write to. Used for calls with duplex streaming. @constructor grpc~ClientDuplexStream @extends external:Duplex @borrows grpc~ClientUnaryCall#cancel as grpc~ClientDuplexStream#cancel @borrows grpc~ClientUnaryCall#getPeer as grpc~ClientDuplexStream#getPeer @borrows grpc~ClientWritableStream#write as grpc~ClientDuplexStream#write @borrows grpc~ClientUnaryCall#event:metadata as grpc~ClientDuplexStream#metadata @borrows grpc~ClientUnaryCall#event:status as grpc~ClientDuplexStream#status @param {InterceptingCall} call Exposes gRPC request operations, processed by an interceptor stack.
[ "A", "stream", "that", "the", "client", "can", "read", "from", "or", "write", "to", ".", "Used", "for", "calls", "with", "duplex", "streaming", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client.js#L281-L293
4,860
grpc/grpc-node
packages/grpc-native-core/src/client.js
Client
function Client(address, credentials, options) { var self = this; if (!options) { options = {}; } // Resolve interceptor options and assign interceptors to each method if (Array.isArray(options.interceptor_providers) && Array.isArray(options.interceptors)) { throw new client_interceptors.InterceptorConfigurationError( 'Both interceptors and interceptor_providers were passed as options ' + 'to the client constructor. Only one of these is allowed.'); } self.$interceptors = options.interceptors || []; self.$interceptor_providers = options.interceptor_providers || []; if (self.$method_definitions) { Object.keys(self.$method_definitions).forEach(method_name => { const method_definition = self.$method_definitions[method_name]; self[method_name].interceptors = client_interceptors .resolveInterceptorProviders(self.$interceptor_providers, method_definition) .concat(self.$interceptors); }); } this.$callInvocationTransformer = options.callInvocationTransformer; let channelOverride = options.channelOverride; let channelFactoryOverride = options.channelFactoryOverride; // Exclude channel options which have already been consumed const ignoredKeys = [ 'interceptors', 'interceptor_providers', 'channelOverride', 'channelFactoryOverride', 'callInvocationTransformer' ]; var channel_options = Object.getOwnPropertyNames(options) .reduce((acc, key) => { if (ignoredKeys.indexOf(key) === -1) { acc[key] = options[key]; } return acc; }, {}); /* Private fields use $ as a prefix instead of _ because it is an invalid * prefix of a method name */ if (channelOverride) { this.$channel = options.channelOverride; } else { if (channelFactoryOverride) { this.$channel = channelFactoryOverride(address, credentials, channel_options); } else { this.$channel = new grpc.Channel(address, credentials, channel_options); } } }
javascript
function Client(address, credentials, options) { var self = this; if (!options) { options = {}; } // Resolve interceptor options and assign interceptors to each method if (Array.isArray(options.interceptor_providers) && Array.isArray(options.interceptors)) { throw new client_interceptors.InterceptorConfigurationError( 'Both interceptors and interceptor_providers were passed as options ' + 'to the client constructor. Only one of these is allowed.'); } self.$interceptors = options.interceptors || []; self.$interceptor_providers = options.interceptor_providers || []; if (self.$method_definitions) { Object.keys(self.$method_definitions).forEach(method_name => { const method_definition = self.$method_definitions[method_name]; self[method_name].interceptors = client_interceptors .resolveInterceptorProviders(self.$interceptor_providers, method_definition) .concat(self.$interceptors); }); } this.$callInvocationTransformer = options.callInvocationTransformer; let channelOverride = options.channelOverride; let channelFactoryOverride = options.channelFactoryOverride; // Exclude channel options which have already been consumed const ignoredKeys = [ 'interceptors', 'interceptor_providers', 'channelOverride', 'channelFactoryOverride', 'callInvocationTransformer' ]; var channel_options = Object.getOwnPropertyNames(options) .reduce((acc, key) => { if (ignoredKeys.indexOf(key) === -1) { acc[key] = options[key]; } return acc; }, {}); /* Private fields use $ as a prefix instead of _ because it is an invalid * prefix of a method name */ if (channelOverride) { this.$channel = options.channelOverride; } else { if (channelFactoryOverride) { this.$channel = channelFactoryOverride(address, credentials, channel_options); } else { this.$channel = new grpc.Channel(address, credentials, channel_options); } } }
[ "function", "Client", "(", "address", ",", "credentials", ",", "options", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "options", ")", "{", "options", "=", "{", "}", ";", "}", "// Resolve interceptor options and assign interceptors to each method", "if", "(", "Array", ".", "isArray", "(", "options", ".", "interceptor_providers", ")", "&&", "Array", ".", "isArray", "(", "options", ".", "interceptors", ")", ")", "{", "throw", "new", "client_interceptors", ".", "InterceptorConfigurationError", "(", "'Both interceptors and interceptor_providers were passed as options '", "+", "'to the client constructor. Only one of these is allowed.'", ")", ";", "}", "self", ".", "$interceptors", "=", "options", ".", "interceptors", "||", "[", "]", ";", "self", ".", "$interceptor_providers", "=", "options", ".", "interceptor_providers", "||", "[", "]", ";", "if", "(", "self", ".", "$method_definitions", ")", "{", "Object", ".", "keys", "(", "self", ".", "$method_definitions", ")", ".", "forEach", "(", "method_name", "=>", "{", "const", "method_definition", "=", "self", ".", "$method_definitions", "[", "method_name", "]", ";", "self", "[", "method_name", "]", ".", "interceptors", "=", "client_interceptors", ".", "resolveInterceptorProviders", "(", "self", ".", "$interceptor_providers", ",", "method_definition", ")", ".", "concat", "(", "self", ".", "$interceptors", ")", ";", "}", ")", ";", "}", "this", ".", "$callInvocationTransformer", "=", "options", ".", "callInvocationTransformer", ";", "let", "channelOverride", "=", "options", ".", "channelOverride", ";", "let", "channelFactoryOverride", "=", "options", ".", "channelFactoryOverride", ";", "// Exclude channel options which have already been consumed", "const", "ignoredKeys", "=", "[", "'interceptors'", ",", "'interceptor_providers'", ",", "'channelOverride'", ",", "'channelFactoryOverride'", ",", "'callInvocationTransformer'", "]", ";", "var", "channel_options", "=", "Object", ".", "getOwnPropertyNames", "(", "options", ")", ".", "reduce", "(", "(", "acc", ",", "key", ")", "=>", "{", "if", "(", "ignoredKeys", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "acc", "[", "key", "]", "=", "options", "[", "key", "]", ";", "}", "return", "acc", ";", "}", ",", "{", "}", ")", ";", "/* Private fields use $ as a prefix instead of _ because it is an invalid\n * prefix of a method name */", "if", "(", "channelOverride", ")", "{", "this", ".", "$channel", "=", "options", ".", "channelOverride", ";", "}", "else", "{", "if", "(", "channelFactoryOverride", ")", "{", "this", ".", "$channel", "=", "channelFactoryOverride", "(", "address", ",", "credentials", ",", "channel_options", ")", ";", "}", "else", "{", "this", ".", "$channel", "=", "new", "grpc", ".", "Channel", "(", "address", ",", "credentials", ",", "channel_options", ")", ";", "}", "}", "}" ]
Options that can be set on a call. @typedef {Object} grpc.Client~CallOptions @property {grpc~Deadline} deadline The deadline for the entire call to complete. @property {string} host Server hostname to set on the call. Only meaningful if different from the server address used to construct the client. @property {grpc.Client~Call} parent Parent call. Used in servers when making a call as part of the process of handling a call. Used to propagate some information automatically, as specified by propagate_flags. @property {number} propagate_flags Indicates which properties of a parent call should propagate to this call. Bitwise combination of flags in {@link grpc.propagate}. @property {grpc.credentials~CallCredentials} credentials The credentials that should be used to make this particular call. A generic gRPC client. Primarily useful as a base class for generated clients @memberof grpc @constructor @param {string} address Server address to connect to @param {grpc.credentials~ChannelCredentials} credentials Credentials to use to connect to the server @param {Object} options Options to apply to channel creation
[ "Options", "that", "can", "be", "set", "on", "a", "call", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client.js#L365-L415
4,861
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
function(providers, method_definition) { if (!Array.isArray(providers)) { return null; } var interceptors = []; for (var i = 0; i < providers.length; i++) { var provider = providers[i]; var interceptor = provider(method_definition); if (interceptor) { interceptors.push(interceptor); } } return interceptors; }
javascript
function(providers, method_definition) { if (!Array.isArray(providers)) { return null; } var interceptors = []; for (var i = 0; i < providers.length; i++) { var provider = providers[i]; var interceptor = provider(method_definition); if (interceptor) { interceptors.push(interceptor); } } return interceptors; }
[ "function", "(", "providers", ",", "method_definition", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "providers", ")", ")", "{", "return", "null", ";", "}", "var", "interceptors", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "providers", ".", "length", ";", "i", "++", ")", "{", "var", "provider", "=", "providers", "[", "i", "]", ";", "var", "interceptor", "=", "provider", "(", "method_definition", ")", ";", "if", "(", "interceptor", ")", "{", "interceptors", ".", "push", "(", "interceptor", ")", ";", "}", "}", "return", "interceptors", ";", "}" ]
Transforms a list of interceptor providers into interceptors. @param {InterceptorProvider[]} providers @param {grpc~MethodDefinition} method_definition @return {null|Interceptor[]}
[ "Transforms", "a", "list", "of", "interceptor", "providers", "into", "interceptors", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L354-L367
4,862
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
function(metadata, current_listener) { // If there is a next call in the chain, run it. Otherwise do nothing. if (self.next_call) { // Wire together any listener provided with the next listener var listener = _getInterceptingListener(current_listener, next_listener); self.next_call.start(metadata, listener); } }
javascript
function(metadata, current_listener) { // If there is a next call in the chain, run it. Otherwise do nothing. if (self.next_call) { // Wire together any listener provided with the next listener var listener = _getInterceptingListener(current_listener, next_listener); self.next_call.start(metadata, listener); } }
[ "function", "(", "metadata", ",", "current_listener", ")", "{", "// If there is a next call in the chain, run it. Otherwise do nothing.", "if", "(", "self", ".", "next_call", ")", "{", "// Wire together any listener provided with the next listener", "var", "listener", "=", "_getInterceptingListener", "(", "current_listener", ",", "next_listener", ")", ";", "self", ".", "next_call", ".", "start", "(", "metadata", ",", "listener", ")", ";", "}", "}" ]
Build the next method in the interceptor chain
[ "Build", "the", "next", "method", "in", "the", "interceptor", "chain" ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L448-L455
4,863
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
getCall
function getCall(channel, path, options) { var deadline; var host; var parent; var propagate_flags; var credentials; if (options) { deadline = options.deadline; host = options.host; parent = options.parent ? options.parent.call : undefined; propagate_flags = options.propagate_flags; credentials = options.credentials; } if (deadline === undefined) { deadline = Infinity; } var call = channel.createCall(path, deadline, host, parent, propagate_flags); if (credentials) { call.setCredentials(credentials); } return call; }
javascript
function getCall(channel, path, options) { var deadline; var host; var parent; var propagate_flags; var credentials; if (options) { deadline = options.deadline; host = options.host; parent = options.parent ? options.parent.call : undefined; propagate_flags = options.propagate_flags; credentials = options.credentials; } if (deadline === undefined) { deadline = Infinity; } var call = channel.createCall(path, deadline, host, parent, propagate_flags); if (credentials) { call.setCredentials(credentials); } return call; }
[ "function", "getCall", "(", "channel", ",", "path", ",", "options", ")", "{", "var", "deadline", ";", "var", "host", ";", "var", "parent", ";", "var", "propagate_flags", ";", "var", "credentials", ";", "if", "(", "options", ")", "{", "deadline", "=", "options", ".", "deadline", ";", "host", "=", "options", ".", "host", ";", "parent", "=", "options", ".", "parent", "?", "options", ".", "parent", ".", "call", ":", "undefined", ";", "propagate_flags", "=", "options", ".", "propagate_flags", ";", "credentials", "=", "options", ".", "credentials", ";", "}", "if", "(", "deadline", "===", "undefined", ")", "{", "deadline", "=", "Infinity", ";", "}", "var", "call", "=", "channel", ".", "createCall", "(", "path", ",", "deadline", ",", "host", ",", "parent", ",", "propagate_flags", ")", ";", "if", "(", "credentials", ")", "{", "call", ".", "setCredentials", "(", "credentials", ")", ";", "}", "return", "call", ";", "}" ]
Get a call object built with the provided options. @param {grpc.Channel} channel @param {string} path @param {grpc.Client~CallOptions=} options Options object.
[ "Get", "a", "call", "object", "built", "with", "the", "provided", "options", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L639-L661
4,864
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
_getStreamReadCallback
function _getStreamReadCallback(emitter, call, get_listener, deserialize) { return function (err, response) { if (err) { // Something has gone wrong. Stop reading and wait for status emitter.finished = true; emitter._readsDone(); return; } var data = response.read; var deserialized; try { deserialized = deserialize(data); } catch (e) { emitter._readsDone({ code: constants.status.INTERNAL, details: 'Failed to parse server response' }); return; } if (data === null) { emitter._readsDone(); return; } var listener = get_listener(); var context = { call: call, listener: listener }; listener.recvMessageWithContext(context, deserialized); }; }
javascript
function _getStreamReadCallback(emitter, call, get_listener, deserialize) { return function (err, response) { if (err) { // Something has gone wrong. Stop reading and wait for status emitter.finished = true; emitter._readsDone(); return; } var data = response.read; var deserialized; try { deserialized = deserialize(data); } catch (e) { emitter._readsDone({ code: constants.status.INTERNAL, details: 'Failed to parse server response' }); return; } if (data === null) { emitter._readsDone(); return; } var listener = get_listener(); var context = { call: call, listener: listener }; listener.recvMessageWithContext(context, deserialized); }; }
[ "function", "_getStreamReadCallback", "(", "emitter", ",", "call", ",", "get_listener", ",", "deserialize", ")", "{", "return", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", ")", "{", "// Something has gone wrong. Stop reading and wait for status", "emitter", ".", "finished", "=", "true", ";", "emitter", ".", "_readsDone", "(", ")", ";", "return", ";", "}", "var", "data", "=", "response", ".", "read", ";", "var", "deserialized", ";", "try", "{", "deserialized", "=", "deserialize", "(", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "emitter", ".", "_readsDone", "(", "{", "code", ":", "constants", ".", "status", ".", "INTERNAL", ",", "details", ":", "'Failed to parse server response'", "}", ")", ";", "return", ";", "}", "if", "(", "data", "===", "null", ")", "{", "emitter", ".", "_readsDone", "(", ")", ";", "return", ";", "}", "var", "listener", "=", "get_listener", "(", ")", ";", "var", "context", "=", "{", "call", ":", "call", ",", "listener", ":", "listener", "}", ";", "listener", ".", "recvMessageWithContext", "(", "context", ",", "deserialized", ")", ";", "}", ";", "}" ]
Produces a callback triggered by streaming response messages. @private @param {EventEmitter} emitter @param {grpc.internal~Call} call @param {function} get_listener Returns a grpc~Listener. @param {grpc~deserialize} deserialize @return {Function}
[ "Produces", "a", "callback", "triggered", "by", "streaming", "response", "messages", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L678-L708
4,865
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
_areBatchRequirementsMet
function _areBatchRequirementsMet(batch_ops, completed_ops) { var dependencies = common.flatMap(batch_ops, function(op) { return OP_DEPENDENCIES[op] || []; }); for (var i = 0; i < dependencies.length; i++) { var required_dep = dependencies[i]; if (batch_ops.indexOf(required_dep) === -1 && completed_ops.indexOf(required_dep) === -1) { return false; } } return true; }
javascript
function _areBatchRequirementsMet(batch_ops, completed_ops) { var dependencies = common.flatMap(batch_ops, function(op) { return OP_DEPENDENCIES[op] || []; }); for (var i = 0; i < dependencies.length; i++) { var required_dep = dependencies[i]; if (batch_ops.indexOf(required_dep) === -1 && completed_ops.indexOf(required_dep) === -1) { return false; } } return true; }
[ "function", "_areBatchRequirementsMet", "(", "batch_ops", ",", "completed_ops", ")", "{", "var", "dependencies", "=", "common", ".", "flatMap", "(", "batch_ops", ",", "function", "(", "op", ")", "{", "return", "OP_DEPENDENCIES", "[", "op", "]", "||", "[", "]", ";", "}", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "dependencies", ".", "length", ";", "i", "++", ")", "{", "var", "required_dep", "=", "dependencies", "[", "i", "]", ";", "if", "(", "batch_ops", ".", "indexOf", "(", "required_dep", ")", "===", "-", "1", "&&", "completed_ops", ".", "indexOf", "(", "required_dep", ")", "===", "-", "1", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Tests whether a batch can be started. @private @param {number[]} batch_ops The operations in the batch we are checking. @param {number[]} completed_ops Previously completed operations. @return {boolean}
[ "Tests", "whether", "a", "batch", "can", "be", "started", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L717-L729
4,866
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
_startBatchIfReady
function _startBatchIfReady(call, batch, batch_state, callback) { var completed_ops = batch_state.completed_ops; var deferred_batches = batch_state.deferred_batches; var batch_ops = Object.keys(batch).map(Number); if (_areBatchRequirementsMet(batch_ops, completed_ops)) { // Dependencies are met, start the batch and any deferred batches whose // dependencies are met as a result. call.startBatch(batch, callback); completed_ops = Array.from(new Set(completed_ops.concat(batch_ops))); deferred_batches = common.flatMap(deferred_batches, function(deferred_batch) { var deferred_batch_ops = Object.keys(deferred_batch).map(Number); if (_areBatchRequirementsMet(deferred_batch_ops, completed_ops)) { call.startBatch(deferred_batch.batch, deferred_batch.callback); return []; } return [deferred_batch]; }); } else { // Dependencies are not met, defer the batch deferred_batches = deferred_batches.concat({ batch: batch, callback: callback }); } return { completed_ops: completed_ops, deferred_batches: deferred_batches }; }
javascript
function _startBatchIfReady(call, batch, batch_state, callback) { var completed_ops = batch_state.completed_ops; var deferred_batches = batch_state.deferred_batches; var batch_ops = Object.keys(batch).map(Number); if (_areBatchRequirementsMet(batch_ops, completed_ops)) { // Dependencies are met, start the batch and any deferred batches whose // dependencies are met as a result. call.startBatch(batch, callback); completed_ops = Array.from(new Set(completed_ops.concat(batch_ops))); deferred_batches = common.flatMap(deferred_batches, function(deferred_batch) { var deferred_batch_ops = Object.keys(deferred_batch).map(Number); if (_areBatchRequirementsMet(deferred_batch_ops, completed_ops)) { call.startBatch(deferred_batch.batch, deferred_batch.callback); return []; } return [deferred_batch]; }); } else { // Dependencies are not met, defer the batch deferred_batches = deferred_batches.concat({ batch: batch, callback: callback }); } return { completed_ops: completed_ops, deferred_batches: deferred_batches }; }
[ "function", "_startBatchIfReady", "(", "call", ",", "batch", ",", "batch_state", ",", "callback", ")", "{", "var", "completed_ops", "=", "batch_state", ".", "completed_ops", ";", "var", "deferred_batches", "=", "batch_state", ".", "deferred_batches", ";", "var", "batch_ops", "=", "Object", ".", "keys", "(", "batch", ")", ".", "map", "(", "Number", ")", ";", "if", "(", "_areBatchRequirementsMet", "(", "batch_ops", ",", "completed_ops", ")", ")", "{", "// Dependencies are met, start the batch and any deferred batches whose", "// dependencies are met as a result.", "call", ".", "startBatch", "(", "batch", ",", "callback", ")", ";", "completed_ops", "=", "Array", ".", "from", "(", "new", "Set", "(", "completed_ops", ".", "concat", "(", "batch_ops", ")", ")", ")", ";", "deferred_batches", "=", "common", ".", "flatMap", "(", "deferred_batches", ",", "function", "(", "deferred_batch", ")", "{", "var", "deferred_batch_ops", "=", "Object", ".", "keys", "(", "deferred_batch", ")", ".", "map", "(", "Number", ")", ";", "if", "(", "_areBatchRequirementsMet", "(", "deferred_batch_ops", ",", "completed_ops", ")", ")", "{", "call", ".", "startBatch", "(", "deferred_batch", ".", "batch", ",", "deferred_batch", ".", "callback", ")", ";", "return", "[", "]", ";", "}", "return", "[", "deferred_batch", "]", ";", "}", ")", ";", "}", "else", "{", "// Dependencies are not met, defer the batch", "deferred_batches", "=", "deferred_batches", ".", "concat", "(", "{", "batch", ":", "batch", ",", "callback", ":", "callback", "}", ")", ";", "}", "return", "{", "completed_ops", ":", "completed_ops", ",", "deferred_batches", ":", "deferred_batches", "}", ";", "}" ]
Enforces the order of operations for synchronous requests. If a batch's operations cannot be started because required operations have not started yet, the batch is deferred until requirements are met. @private @param {grpc.Client~Call} call @param {object} batch @param {object} batch_state @param {number[]} [batch_state.completed_ops] The ops already sent. @param {object} [batch_state.deferred_batches] Batches to be sent after their dependencies are fulfilled. @param {function} callback @return {object}
[ "Enforces", "the", "order", "of", "operations", "for", "synchronous", "requests", ".", "If", "a", "batch", "s", "operations", "cannot", "be", "started", "because", "required", "operations", "have", "not", "started", "yet", "the", "batch", "is", "deferred", "until", "requirements", "are", "met", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L745-L773
4,867
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
_getUnaryInterceptor
function _getUnaryInterceptor(method_definition, channel, emitter, callback) { var serialize = method_definition.requestSerialize; var deserialize = method_definition.responseDeserialize; return function (options) { var call = getCall(channel, method_definition.path, options); var first_listener; var final_requester = {}; var batch_state = { completed_ops: [], deferred_batches: [] }; final_requester.start = function (metadata, listener) { var batch = { [grpc.opType.SEND_INITIAL_METADATA]: metadata._getCoreRepresentation(), }; first_listener = listener; batch_state = _startBatchIfReady(call, batch, batch_state, function() {}); }; final_requester.sendMessage = function (message) { var batch = { [grpc.opType.SEND_MESSAGE]: serialize(message), }; batch_state = _startBatchIfReady(call, batch, batch_state, function() {}); }; final_requester.halfClose = function () { var batch = { [grpc.opType.SEND_CLOSE_FROM_CLIENT]: true, [grpc.opType.RECV_INITIAL_METADATA]: true, [grpc.opType.RECV_MESSAGE]: true, [grpc.opType.RECV_STATUS_ON_CLIENT]: true }; var callback = function (err, response) { response.status.metadata = Metadata._fromCoreRepresentation( response.status.metadata); var status = response.status; var deserialized; if (status.code === constants.status.OK) { if (err) { // Got a batch error, but OK status. Something went wrong callback(err); return; } else { try { deserialized = deserialize(response.read); } catch (e) { /* Change status to indicate bad server response. This * will result in passing an error to the callback */ status = { code: constants.status.INTERNAL, details: 'Failed to parse server response' }; } } } response.metadata = Metadata._fromCoreRepresentation(response.metadata); first_listener.onReceiveMetadata(response.metadata); first_listener.onReceiveMessage(deserialized); first_listener.onReceiveStatus(status); }; batch_state = _startBatchIfReady(call, batch, batch_state, callback); }; final_requester.cancel = function () { call.cancel(); }; final_requester.cancelWithStatus = function(code, details) { call.cancelWithStatus(code, details) }; final_requester.getPeer = function () { return call.getPeer(); }; return new InterceptingCall(null, final_requester); }; }
javascript
function _getUnaryInterceptor(method_definition, channel, emitter, callback) { var serialize = method_definition.requestSerialize; var deserialize = method_definition.responseDeserialize; return function (options) { var call = getCall(channel, method_definition.path, options); var first_listener; var final_requester = {}; var batch_state = { completed_ops: [], deferred_batches: [] }; final_requester.start = function (metadata, listener) { var batch = { [grpc.opType.SEND_INITIAL_METADATA]: metadata._getCoreRepresentation(), }; first_listener = listener; batch_state = _startBatchIfReady(call, batch, batch_state, function() {}); }; final_requester.sendMessage = function (message) { var batch = { [grpc.opType.SEND_MESSAGE]: serialize(message), }; batch_state = _startBatchIfReady(call, batch, batch_state, function() {}); }; final_requester.halfClose = function () { var batch = { [grpc.opType.SEND_CLOSE_FROM_CLIENT]: true, [grpc.opType.RECV_INITIAL_METADATA]: true, [grpc.opType.RECV_MESSAGE]: true, [grpc.opType.RECV_STATUS_ON_CLIENT]: true }; var callback = function (err, response) { response.status.metadata = Metadata._fromCoreRepresentation( response.status.metadata); var status = response.status; var deserialized; if (status.code === constants.status.OK) { if (err) { // Got a batch error, but OK status. Something went wrong callback(err); return; } else { try { deserialized = deserialize(response.read); } catch (e) { /* Change status to indicate bad server response. This * will result in passing an error to the callback */ status = { code: constants.status.INTERNAL, details: 'Failed to parse server response' }; } } } response.metadata = Metadata._fromCoreRepresentation(response.metadata); first_listener.onReceiveMetadata(response.metadata); first_listener.onReceiveMessage(deserialized); first_listener.onReceiveStatus(status); }; batch_state = _startBatchIfReady(call, batch, batch_state, callback); }; final_requester.cancel = function () { call.cancel(); }; final_requester.cancelWithStatus = function(code, details) { call.cancelWithStatus(code, details) }; final_requester.getPeer = function () { return call.getPeer(); }; return new InterceptingCall(null, final_requester); }; }
[ "function", "_getUnaryInterceptor", "(", "method_definition", ",", "channel", ",", "emitter", ",", "callback", ")", "{", "var", "serialize", "=", "method_definition", ".", "requestSerialize", ";", "var", "deserialize", "=", "method_definition", ".", "responseDeserialize", ";", "return", "function", "(", "options", ")", "{", "var", "call", "=", "getCall", "(", "channel", ",", "method_definition", ".", "path", ",", "options", ")", ";", "var", "first_listener", ";", "var", "final_requester", "=", "{", "}", ";", "var", "batch_state", "=", "{", "completed_ops", ":", "[", "]", ",", "deferred_batches", ":", "[", "]", "}", ";", "final_requester", ".", "start", "=", "function", "(", "metadata", ",", "listener", ")", "{", "var", "batch", "=", "{", "[", "grpc", ".", "opType", ".", "SEND_INITIAL_METADATA", "]", ":", "metadata", ".", "_getCoreRepresentation", "(", ")", ",", "}", ";", "first_listener", "=", "listener", ";", "batch_state", "=", "_startBatchIfReady", "(", "call", ",", "batch", ",", "batch_state", ",", "function", "(", ")", "{", "}", ")", ";", "}", ";", "final_requester", ".", "sendMessage", "=", "function", "(", "message", ")", "{", "var", "batch", "=", "{", "[", "grpc", ".", "opType", ".", "SEND_MESSAGE", "]", ":", "serialize", "(", "message", ")", ",", "}", ";", "batch_state", "=", "_startBatchIfReady", "(", "call", ",", "batch", ",", "batch_state", ",", "function", "(", ")", "{", "}", ")", ";", "}", ";", "final_requester", ".", "halfClose", "=", "function", "(", ")", "{", "var", "batch", "=", "{", "[", "grpc", ".", "opType", ".", "SEND_CLOSE_FROM_CLIENT", "]", ":", "true", ",", "[", "grpc", ".", "opType", ".", "RECV_INITIAL_METADATA", "]", ":", "true", ",", "[", "grpc", ".", "opType", ".", "RECV_MESSAGE", "]", ":", "true", ",", "[", "grpc", ".", "opType", ".", "RECV_STATUS_ON_CLIENT", "]", ":", "true", "}", ";", "var", "callback", "=", "function", "(", "err", ",", "response", ")", "{", "response", ".", "status", ".", "metadata", "=", "Metadata", ".", "_fromCoreRepresentation", "(", "response", ".", "status", ".", "metadata", ")", ";", "var", "status", "=", "response", ".", "status", ";", "var", "deserialized", ";", "if", "(", "status", ".", "code", "===", "constants", ".", "status", ".", "OK", ")", "{", "if", "(", "err", ")", "{", "// Got a batch error, but OK status. Something went wrong", "callback", "(", "err", ")", ";", "return", ";", "}", "else", "{", "try", "{", "deserialized", "=", "deserialize", "(", "response", ".", "read", ")", ";", "}", "catch", "(", "e", ")", "{", "/* Change status to indicate bad server response. This\n * will result in passing an error to the callback */", "status", "=", "{", "code", ":", "constants", ".", "status", ".", "INTERNAL", ",", "details", ":", "'Failed to parse server response'", "}", ";", "}", "}", "}", "response", ".", "metadata", "=", "Metadata", ".", "_fromCoreRepresentation", "(", "response", ".", "metadata", ")", ";", "first_listener", ".", "onReceiveMetadata", "(", "response", ".", "metadata", ")", ";", "first_listener", ".", "onReceiveMessage", "(", "deserialized", ")", ";", "first_listener", ".", "onReceiveStatus", "(", "status", ")", ";", "}", ";", "batch_state", "=", "_startBatchIfReady", "(", "call", ",", "batch", ",", "batch_state", ",", "callback", ")", ";", "}", ";", "final_requester", ".", "cancel", "=", "function", "(", ")", "{", "call", ".", "cancel", "(", ")", ";", "}", ";", "final_requester", ".", "cancelWithStatus", "=", "function", "(", "code", ",", "details", ")", "{", "call", ".", "cancelWithStatus", "(", "code", ",", "details", ")", "}", ";", "final_requester", ".", "getPeer", "=", "function", "(", ")", "{", "return", "call", ".", "getPeer", "(", ")", ";", "}", ";", "return", "new", "InterceptingCall", "(", "null", ",", "final_requester", ")", ";", "}", ";", "}" ]
Produces an interceptor which will start gRPC batches for unary calls. @private @param {grpc~MethodDefinition} method_definition @param {grpc.Channel} channel @param {EventEmitter} emitter @param {function} callback @return {Interceptor}
[ "Produces", "an", "interceptor", "which", "will", "start", "gRPC", "batches", "for", "unary", "calls", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L784-L860
4,868
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
_getServerStreamingInterceptor
function _getServerStreamingInterceptor(method_definition, channel, emitter) { var deserialize = common.wrapIgnoreNull( method_definition.responseDeserialize); var serialize = method_definition.requestSerialize; return function (options) { var batch_state = { completed_ops: [], deferred_batches: [] }; var call = getCall(channel, method_definition.path, options); var final_requester = {}; var first_listener; var get_listener = function() { return first_listener; }; final_requester.start = function(metadata, listener) { first_listener = listener; metadata = metadata.clone(); var metadata_batch = { [grpc.opType.SEND_INITIAL_METADATA]: metadata._getCoreRepresentation(), [grpc.opType.RECV_INITIAL_METADATA]: true }; var callback = function(err, response) { if (err) { // The call has stopped for some reason. A non-OK status will arrive // in the other batch. return; } first_listener.onReceiveMetadata( Metadata._fromCoreRepresentation(response.metadata)); }; batch_state = _startBatchIfReady(call, metadata_batch, batch_state, callback); var status_batch = { [grpc.opType.RECV_STATUS_ON_CLIENT]: true }; call.startBatch(status_batch, function(err, response) { if (err) { emitter.emit('error', err); return; } response.status.metadata = Metadata._fromCoreRepresentation( response.status.metadata); first_listener.onReceiveStatus(response.status); }); }; final_requester.sendMessage = function(argument) { var message = serialize(argument); if (options) { message.grpcWriteFlags = options.flags; } var send_batch = { [grpc.opType.SEND_MESSAGE]: message }; var callback = function(err, response) { if (err) { // The call has stopped for some reason. A non-OK status will arrive // in the other batch. return; } }; batch_state = _startBatchIfReady(call, send_batch, batch_state, callback); }; final_requester.halfClose = function() { var batch = { [grpc.opType.SEND_CLOSE_FROM_CLIENT]: true }; batch_state = _startBatchIfReady(call, batch, batch_state, function() {}); }; final_requester.recvMessageWithContext = function(context) { var recv_batch = { [grpc.opType.RECV_MESSAGE]: true }; var callback = _getStreamReadCallback(emitter, call, get_listener, deserialize); batch_state = _startBatchIfReady(call, recv_batch, batch_state, callback); }; final_requester.cancel = function() { call.cancel(); }; final_requester.cancelWithStatus = function(code, details) { call.cancelWithStatus(code, details) }; final_requester.getPeer = function() { return call.getPeer(); }; return new InterceptingCall(null, final_requester); }; }
javascript
function _getServerStreamingInterceptor(method_definition, channel, emitter) { var deserialize = common.wrapIgnoreNull( method_definition.responseDeserialize); var serialize = method_definition.requestSerialize; return function (options) { var batch_state = { completed_ops: [], deferred_batches: [] }; var call = getCall(channel, method_definition.path, options); var final_requester = {}; var first_listener; var get_listener = function() { return first_listener; }; final_requester.start = function(metadata, listener) { first_listener = listener; metadata = metadata.clone(); var metadata_batch = { [grpc.opType.SEND_INITIAL_METADATA]: metadata._getCoreRepresentation(), [grpc.opType.RECV_INITIAL_METADATA]: true }; var callback = function(err, response) { if (err) { // The call has stopped for some reason. A non-OK status will arrive // in the other batch. return; } first_listener.onReceiveMetadata( Metadata._fromCoreRepresentation(response.metadata)); }; batch_state = _startBatchIfReady(call, metadata_batch, batch_state, callback); var status_batch = { [grpc.opType.RECV_STATUS_ON_CLIENT]: true }; call.startBatch(status_batch, function(err, response) { if (err) { emitter.emit('error', err); return; } response.status.metadata = Metadata._fromCoreRepresentation( response.status.metadata); first_listener.onReceiveStatus(response.status); }); }; final_requester.sendMessage = function(argument) { var message = serialize(argument); if (options) { message.grpcWriteFlags = options.flags; } var send_batch = { [grpc.opType.SEND_MESSAGE]: message }; var callback = function(err, response) { if (err) { // The call has stopped for some reason. A non-OK status will arrive // in the other batch. return; } }; batch_state = _startBatchIfReady(call, send_batch, batch_state, callback); }; final_requester.halfClose = function() { var batch = { [grpc.opType.SEND_CLOSE_FROM_CLIENT]: true }; batch_state = _startBatchIfReady(call, batch, batch_state, function() {}); }; final_requester.recvMessageWithContext = function(context) { var recv_batch = { [grpc.opType.RECV_MESSAGE]: true }; var callback = _getStreamReadCallback(emitter, call, get_listener, deserialize); batch_state = _startBatchIfReady(call, recv_batch, batch_state, callback); }; final_requester.cancel = function() { call.cancel(); }; final_requester.cancelWithStatus = function(code, details) { call.cancelWithStatus(code, details) }; final_requester.getPeer = function() { return call.getPeer(); }; return new InterceptingCall(null, final_requester); }; }
[ "function", "_getServerStreamingInterceptor", "(", "method_definition", ",", "channel", ",", "emitter", ")", "{", "var", "deserialize", "=", "common", ".", "wrapIgnoreNull", "(", "method_definition", ".", "responseDeserialize", ")", ";", "var", "serialize", "=", "method_definition", ".", "requestSerialize", ";", "return", "function", "(", "options", ")", "{", "var", "batch_state", "=", "{", "completed_ops", ":", "[", "]", ",", "deferred_batches", ":", "[", "]", "}", ";", "var", "call", "=", "getCall", "(", "channel", ",", "method_definition", ".", "path", ",", "options", ")", ";", "var", "final_requester", "=", "{", "}", ";", "var", "first_listener", ";", "var", "get_listener", "=", "function", "(", ")", "{", "return", "first_listener", ";", "}", ";", "final_requester", ".", "start", "=", "function", "(", "metadata", ",", "listener", ")", "{", "first_listener", "=", "listener", ";", "metadata", "=", "metadata", ".", "clone", "(", ")", ";", "var", "metadata_batch", "=", "{", "[", "grpc", ".", "opType", ".", "SEND_INITIAL_METADATA", "]", ":", "metadata", ".", "_getCoreRepresentation", "(", ")", ",", "[", "grpc", ".", "opType", ".", "RECV_INITIAL_METADATA", "]", ":", "true", "}", ";", "var", "callback", "=", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", ")", "{", "// The call has stopped for some reason. A non-OK status will arrive", "// in the other batch.", "return", ";", "}", "first_listener", ".", "onReceiveMetadata", "(", "Metadata", ".", "_fromCoreRepresentation", "(", "response", ".", "metadata", ")", ")", ";", "}", ";", "batch_state", "=", "_startBatchIfReady", "(", "call", ",", "metadata_batch", ",", "batch_state", ",", "callback", ")", ";", "var", "status_batch", "=", "{", "[", "grpc", ".", "opType", ".", "RECV_STATUS_ON_CLIENT", "]", ":", "true", "}", ";", "call", ".", "startBatch", "(", "status_batch", ",", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", ")", "{", "emitter", ".", "emit", "(", "'error'", ",", "err", ")", ";", "return", ";", "}", "response", ".", "status", ".", "metadata", "=", "Metadata", ".", "_fromCoreRepresentation", "(", "response", ".", "status", ".", "metadata", ")", ";", "first_listener", ".", "onReceiveStatus", "(", "response", ".", "status", ")", ";", "}", ")", ";", "}", ";", "final_requester", ".", "sendMessage", "=", "function", "(", "argument", ")", "{", "var", "message", "=", "serialize", "(", "argument", ")", ";", "if", "(", "options", ")", "{", "message", ".", "grpcWriteFlags", "=", "options", ".", "flags", ";", "}", "var", "send_batch", "=", "{", "[", "grpc", ".", "opType", ".", "SEND_MESSAGE", "]", ":", "message", "}", ";", "var", "callback", "=", "function", "(", "err", ",", "response", ")", "{", "if", "(", "err", ")", "{", "// The call has stopped for some reason. A non-OK status will arrive", "// in the other batch.", "return", ";", "}", "}", ";", "batch_state", "=", "_startBatchIfReady", "(", "call", ",", "send_batch", ",", "batch_state", ",", "callback", ")", ";", "}", ";", "final_requester", ".", "halfClose", "=", "function", "(", ")", "{", "var", "batch", "=", "{", "[", "grpc", ".", "opType", ".", "SEND_CLOSE_FROM_CLIENT", "]", ":", "true", "}", ";", "batch_state", "=", "_startBatchIfReady", "(", "call", ",", "batch", ",", "batch_state", ",", "function", "(", ")", "{", "}", ")", ";", "}", ";", "final_requester", ".", "recvMessageWithContext", "=", "function", "(", "context", ")", "{", "var", "recv_batch", "=", "{", "[", "grpc", ".", "opType", ".", "RECV_MESSAGE", "]", ":", "true", "}", ";", "var", "callback", "=", "_getStreamReadCallback", "(", "emitter", ",", "call", ",", "get_listener", ",", "deserialize", ")", ";", "batch_state", "=", "_startBatchIfReady", "(", "call", ",", "recv_batch", ",", "batch_state", ",", "callback", ")", ";", "}", ";", "final_requester", ".", "cancel", "=", "function", "(", ")", "{", "call", ".", "cancel", "(", ")", ";", "}", ";", "final_requester", ".", "cancelWithStatus", "=", "function", "(", "code", ",", "details", ")", "{", "call", ".", "cancelWithStatus", "(", "code", ",", "details", ")", "}", ";", "final_requester", ".", "getPeer", "=", "function", "(", ")", "{", "return", "call", ".", "getPeer", "(", ")", ";", "}", ";", "return", "new", "InterceptingCall", "(", "null", ",", "final_requester", ")", ";", "}", ";", "}" ]
Produces an interceptor which will start gRPC batches for server streaming calls. @private @param {grpc~MethodDefinition} method_definition @param {grpc.Channel} channel @param {EventEmitter} emitter @return {Interceptor}
[ "Produces", "an", "interceptor", "which", "will", "start", "gRPC", "batches", "for", "server", "streaming", "calls", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L986-L1074
4,869
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
_getUnaryListener
function _getUnaryListener(method_definition, emitter, callback) { var resultMessage; return { onReceiveMetadata: function (metadata) { emitter.emit('metadata', metadata); }, onReceiveMessage: function (message) { resultMessage = message; }, onReceiveStatus: function (status) { if (status.code !== constants.status.OK) { var error = common.createStatusError(status); callback(error); } else { callback(null, resultMessage); } emitter.emit('status', status); } }; }
javascript
function _getUnaryListener(method_definition, emitter, callback) { var resultMessage; return { onReceiveMetadata: function (metadata) { emitter.emit('metadata', metadata); }, onReceiveMessage: function (message) { resultMessage = message; }, onReceiveStatus: function (status) { if (status.code !== constants.status.OK) { var error = common.createStatusError(status); callback(error); } else { callback(null, resultMessage); } emitter.emit('status', status); } }; }
[ "function", "_getUnaryListener", "(", "method_definition", ",", "emitter", ",", "callback", ")", "{", "var", "resultMessage", ";", "return", "{", "onReceiveMetadata", ":", "function", "(", "metadata", ")", "{", "emitter", ".", "emit", "(", "'metadata'", ",", "metadata", ")", ";", "}", ",", "onReceiveMessage", ":", "function", "(", "message", ")", "{", "resultMessage", "=", "message", ";", "}", ",", "onReceiveStatus", ":", "function", "(", "status", ")", "{", "if", "(", "status", ".", "code", "!==", "constants", ".", "status", ".", "OK", ")", "{", "var", "error", "=", "common", ".", "createStatusError", "(", "status", ")", ";", "callback", "(", "error", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "resultMessage", ")", ";", "}", "emitter", ".", "emit", "(", "'status'", ",", "status", ")", ";", "}", "}", ";", "}" ]
Produces a listener for responding to callers of unary RPCs. @private @param {grpc~MethodDefinition} method_definition @param {EventEmitter} emitter @param {function} callback @return {grpc~Listener}
[ "Produces", "a", "listener", "for", "responding", "to", "callers", "of", "unary", "RPCs", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L1193-L1212
4,870
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
_getBidiStreamingListener
function _getBidiStreamingListener(method_definition, emitter) { var deserialize = common.wrapIgnoreNull( method_definition.responseDeserialize); return { onReceiveMetadata: function (metadata) { emitter.emit('metadata', metadata); }, onReceiveMessage: function(message, next, context) { if (emitter.push(message) && message !== null) { var call = context.call; var get_listener = function() { return context.listener; }; var read_batch = {}; read_batch[grpc.opType.RECV_MESSAGE] = true; call.startBatch(read_batch, _getStreamReadCallback(emitter, call, get_listener, deserialize)); } else { emitter.reading = false; } }, onReceiveStatus: function (status) { emitter._receiveStatus(status); } }; }
javascript
function _getBidiStreamingListener(method_definition, emitter) { var deserialize = common.wrapIgnoreNull( method_definition.responseDeserialize); return { onReceiveMetadata: function (metadata) { emitter.emit('metadata', metadata); }, onReceiveMessage: function(message, next, context) { if (emitter.push(message) && message !== null) { var call = context.call; var get_listener = function() { return context.listener; }; var read_batch = {}; read_batch[grpc.opType.RECV_MESSAGE] = true; call.startBatch(read_batch, _getStreamReadCallback(emitter, call, get_listener, deserialize)); } else { emitter.reading = false; } }, onReceiveStatus: function (status) { emitter._receiveStatus(status); } }; }
[ "function", "_getBidiStreamingListener", "(", "method_definition", ",", "emitter", ")", "{", "var", "deserialize", "=", "common", ".", "wrapIgnoreNull", "(", "method_definition", ".", "responseDeserialize", ")", ";", "return", "{", "onReceiveMetadata", ":", "function", "(", "metadata", ")", "{", "emitter", ".", "emit", "(", "'metadata'", ",", "metadata", ")", ";", "}", ",", "onReceiveMessage", ":", "function", "(", "message", ",", "next", ",", "context", ")", "{", "if", "(", "emitter", ".", "push", "(", "message", ")", "&&", "message", "!==", "null", ")", "{", "var", "call", "=", "context", ".", "call", ";", "var", "get_listener", "=", "function", "(", ")", "{", "return", "context", ".", "listener", ";", "}", ";", "var", "read_batch", "=", "{", "}", ";", "read_batch", "[", "grpc", ".", "opType", ".", "RECV_MESSAGE", "]", "=", "true", ";", "call", ".", "startBatch", "(", "read_batch", ",", "_getStreamReadCallback", "(", "emitter", ",", "call", ",", "get_listener", ",", "deserialize", ")", ")", ";", "}", "else", "{", "emitter", ".", "reading", "=", "false", ";", "}", "}", ",", "onReceiveStatus", ":", "function", "(", "status", ")", "{", "emitter", ".", "_receiveStatus", "(", "status", ")", ";", "}", "}", ";", "}" ]
Produces a listener for responding to callers of bi-directional RPCs. @private @param {grpc~MethodDefinition} method_definition @param {EventEmitter} emitter @return {grpc~Listener}
[ "Produces", "a", "listener", "for", "responding", "to", "callers", "of", "bi", "-", "directional", "RPCs", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L1284-L1309
4,871
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
getLastListener
function getLastListener(method_definition, emitter, callback) { if (emitter instanceof Function) { callback = emitter; callback = function() {}; } if (!(callback instanceof Function)) { callback = function() {}; } if (!((emitter instanceof EventEmitter) && (callback instanceof Function))) { throw new Error('Argument mismatch in getLastListener'); } var method_type = common.getMethodType(method_definition); var generator = listenerGenerators[method_type]; return generator(method_definition, emitter, callback); }
javascript
function getLastListener(method_definition, emitter, callback) { if (emitter instanceof Function) { callback = emitter; callback = function() {}; } if (!(callback instanceof Function)) { callback = function() {}; } if (!((emitter instanceof EventEmitter) && (callback instanceof Function))) { throw new Error('Argument mismatch in getLastListener'); } var method_type = common.getMethodType(method_definition); var generator = listenerGenerators[method_type]; return generator(method_definition, emitter, callback); }
[ "function", "getLastListener", "(", "method_definition", ",", "emitter", ",", "callback", ")", "{", "if", "(", "emitter", "instanceof", "Function", ")", "{", "callback", "=", "emitter", ";", "callback", "=", "function", "(", ")", "{", "}", ";", "}", "if", "(", "!", "(", "callback", "instanceof", "Function", ")", ")", "{", "callback", "=", "function", "(", ")", "{", "}", ";", "}", "if", "(", "!", "(", "(", "emitter", "instanceof", "EventEmitter", ")", "&&", "(", "callback", "instanceof", "Function", ")", ")", ")", "{", "throw", "new", "Error", "(", "'Argument mismatch in getLastListener'", ")", ";", "}", "var", "method_type", "=", "common", ".", "getMethodType", "(", "method_definition", ")", ";", "var", "generator", "=", "listenerGenerators", "[", "method_type", "]", ";", "return", "generator", "(", "method_definition", ",", "emitter", ",", "callback", ")", ";", "}" ]
Creates the last listener in an interceptor stack. @param {grpc~MethodDefinition} method_definition @param {EventEmitter} emitter @param {function=} callback @return {grpc~Listener}
[ "Creates", "the", "last", "listener", "in", "an", "interceptor", "stack", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L1332-L1347
4,872
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
_getLastInterceptor
function _getLastInterceptor(method_definition, channel, responder) { var callback = (responder instanceof Function) ? responder : function() {}; var emitter = (responder instanceof EventEmitter) ? responder : new EventEmitter(); var method_type = common.getMethodType(method_definition); var generator = interceptorGenerators[method_type]; return generator(method_definition, channel, emitter, callback); }
javascript
function _getLastInterceptor(method_definition, channel, responder) { var callback = (responder instanceof Function) ? responder : function() {}; var emitter = (responder instanceof EventEmitter) ? responder : new EventEmitter(); var method_type = common.getMethodType(method_definition); var generator = interceptorGenerators[method_type]; return generator(method_definition, channel, emitter, callback); }
[ "function", "_getLastInterceptor", "(", "method_definition", ",", "channel", ",", "responder", ")", "{", "var", "callback", "=", "(", "responder", "instanceof", "Function", ")", "?", "responder", ":", "function", "(", ")", "{", "}", ";", "var", "emitter", "=", "(", "responder", "instanceof", "EventEmitter", ")", "?", "responder", ":", "new", "EventEmitter", "(", ")", ";", "var", "method_type", "=", "common", ".", "getMethodType", "(", "method_definition", ")", ";", "var", "generator", "=", "interceptorGenerators", "[", "method_type", "]", ";", "return", "generator", "(", "method_definition", ",", "channel", ",", "emitter", ",", "callback", ")", ";", "}" ]
Creates the last interceptor in an interceptor stack. @private @param {grpc~MethodDefinition} method_definition @param {grpc.Channel} channel @param {function|EventEmitter} responder @return {Interceptor}
[ "Creates", "the", "last", "interceptor", "in", "an", "interceptor", "stack", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L1373-L1380
4,873
grpc/grpc-node
packages/grpc-native-core/src/client_interceptors.js
_buildChain
function _buildChain(interceptors, options) { var next = function(interceptors) { if (interceptors.length === 0) { return function (options) {}; } var head_interceptor = interceptors[0]; var rest_interceptors = interceptors.slice(1); return function (options) { return head_interceptor(options, next(rest_interceptors)); }; }; var chain = next(interceptors)(options); return new InterceptingCall(chain); }
javascript
function _buildChain(interceptors, options) { var next = function(interceptors) { if (interceptors.length === 0) { return function (options) {}; } var head_interceptor = interceptors[0]; var rest_interceptors = interceptors.slice(1); return function (options) { return head_interceptor(options, next(rest_interceptors)); }; }; var chain = next(interceptors)(options); return new InterceptingCall(chain); }
[ "function", "_buildChain", "(", "interceptors", ",", "options", ")", "{", "var", "next", "=", "function", "(", "interceptors", ")", "{", "if", "(", "interceptors", ".", "length", "===", "0", ")", "{", "return", "function", "(", "options", ")", "{", "}", ";", "}", "var", "head_interceptor", "=", "interceptors", "[", "0", "]", ";", "var", "rest_interceptors", "=", "interceptors", ".", "slice", "(", "1", ")", ";", "return", "function", "(", "options", ")", "{", "return", "head_interceptor", "(", "options", ",", "next", "(", "rest_interceptors", ")", ")", ";", "}", ";", "}", ";", "var", "chain", "=", "next", "(", "interceptors", ")", "(", "options", ")", ";", "return", "new", "InterceptingCall", "(", "chain", ")", ";", "}" ]
Chain a list of interceptors together and return the first InterceptingCall. @private @param {Interceptor[]} interceptors An interceptor stack. @param {grpc.Client~CallOptions} options Call options. @return {InterceptingCall}
[ "Chain", "a", "list", "of", "interceptors", "together", "and", "return", "the", "first", "InterceptingCall", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/client_interceptors.js#L1389-L1402
4,874
grpc/grpc-node
packages/grpc-native-core/src/server.js
handleError
function handleError(call, error) { var statusMetadata = new Metadata(); var status = { code: constants.status.UNKNOWN, details: 'Unknown Error' }; if (error.hasOwnProperty('message')) { status.details = error.message; } if (error.hasOwnProperty('code') && Number.isInteger(error.code)) { status.code = error.code; if (error.hasOwnProperty('details')) { status.details = error.details; } } if (error.hasOwnProperty('metadata')) { statusMetadata = error.metadata; } status.metadata = statusMetadata._getCoreRepresentation(); var error_batch = {}; if (!call.metadataSent) { error_batch[grpc.opType.SEND_INITIAL_METADATA] = (new Metadata())._getCoreRepresentation(); } error_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = status; call.startBatch(error_batch, function(){}); }
javascript
function handleError(call, error) { var statusMetadata = new Metadata(); var status = { code: constants.status.UNKNOWN, details: 'Unknown Error' }; if (error.hasOwnProperty('message')) { status.details = error.message; } if (error.hasOwnProperty('code') && Number.isInteger(error.code)) { status.code = error.code; if (error.hasOwnProperty('details')) { status.details = error.details; } } if (error.hasOwnProperty('metadata')) { statusMetadata = error.metadata; } status.metadata = statusMetadata._getCoreRepresentation(); var error_batch = {}; if (!call.metadataSent) { error_batch[grpc.opType.SEND_INITIAL_METADATA] = (new Metadata())._getCoreRepresentation(); } error_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = status; call.startBatch(error_batch, function(){}); }
[ "function", "handleError", "(", "call", ",", "error", ")", "{", "var", "statusMetadata", "=", "new", "Metadata", "(", ")", ";", "var", "status", "=", "{", "code", ":", "constants", ".", "status", ".", "UNKNOWN", ",", "details", ":", "'Unknown Error'", "}", ";", "if", "(", "error", ".", "hasOwnProperty", "(", "'message'", ")", ")", "{", "status", ".", "details", "=", "error", ".", "message", ";", "}", "if", "(", "error", ".", "hasOwnProperty", "(", "'code'", ")", "&&", "Number", ".", "isInteger", "(", "error", ".", "code", ")", ")", "{", "status", ".", "code", "=", "error", ".", "code", ";", "if", "(", "error", ".", "hasOwnProperty", "(", "'details'", ")", ")", "{", "status", ".", "details", "=", "error", ".", "details", ";", "}", "}", "if", "(", "error", ".", "hasOwnProperty", "(", "'metadata'", ")", ")", "{", "statusMetadata", "=", "error", ".", "metadata", ";", "}", "status", ".", "metadata", "=", "statusMetadata", ".", "_getCoreRepresentation", "(", ")", ";", "var", "error_batch", "=", "{", "}", ";", "if", "(", "!", "call", ".", "metadataSent", ")", "{", "error_batch", "[", "grpc", ".", "opType", ".", "SEND_INITIAL_METADATA", "]", "=", "(", "new", "Metadata", "(", ")", ")", ".", "_getCoreRepresentation", "(", ")", ";", "}", "error_batch", "[", "grpc", ".", "opType", ".", "SEND_STATUS_FROM_SERVER", "]", "=", "status", ";", "call", ".", "startBatch", "(", "error_batch", ",", "function", "(", ")", "{", "}", ")", ";", "}" ]
Handle an error on a call by sending it as a status @private @param {grpc.internal~Call} call The call to send the error on @param {(Object|Error)} error The error object
[ "Handle", "an", "error", "on", "a", "call", "by", "sending", "it", "as", "a", "status" ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L44-L70
4,875
grpc/grpc-node
packages/grpc-native-core/src/server.js
sendUnaryResponse
function sendUnaryResponse(call, value, serialize, metadata, flags) { var end_batch = {}; var statusMetadata = new Metadata(); var status = { code: constants.status.OK, details: 'OK' }; if (metadata) { statusMetadata = metadata; } var message; try { message = serialize(value); } catch (e) { e.code = constants.status.INTERNAL; handleError(call, e); return; } status.metadata = statusMetadata._getCoreRepresentation(); if (!call.metadataSent) { end_batch[grpc.opType.SEND_INITIAL_METADATA] = (new Metadata())._getCoreRepresentation(); call.metadataSent = true; } message.grpcWriteFlags = flags; end_batch[grpc.opType.SEND_MESSAGE] = message; end_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = status; call.startBatch(end_batch, function (){}); }
javascript
function sendUnaryResponse(call, value, serialize, metadata, flags) { var end_batch = {}; var statusMetadata = new Metadata(); var status = { code: constants.status.OK, details: 'OK' }; if (metadata) { statusMetadata = metadata; } var message; try { message = serialize(value); } catch (e) { e.code = constants.status.INTERNAL; handleError(call, e); return; } status.metadata = statusMetadata._getCoreRepresentation(); if (!call.metadataSent) { end_batch[grpc.opType.SEND_INITIAL_METADATA] = (new Metadata())._getCoreRepresentation(); call.metadataSent = true; } message.grpcWriteFlags = flags; end_batch[grpc.opType.SEND_MESSAGE] = message; end_batch[grpc.opType.SEND_STATUS_FROM_SERVER] = status; call.startBatch(end_batch, function (){}); }
[ "function", "sendUnaryResponse", "(", "call", ",", "value", ",", "serialize", ",", "metadata", ",", "flags", ")", "{", "var", "end_batch", "=", "{", "}", ";", "var", "statusMetadata", "=", "new", "Metadata", "(", ")", ";", "var", "status", "=", "{", "code", ":", "constants", ".", "status", ".", "OK", ",", "details", ":", "'OK'", "}", ";", "if", "(", "metadata", ")", "{", "statusMetadata", "=", "metadata", ";", "}", "var", "message", ";", "try", "{", "message", "=", "serialize", "(", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "e", ".", "code", "=", "constants", ".", "status", ".", "INTERNAL", ";", "handleError", "(", "call", ",", "e", ")", ";", "return", ";", "}", "status", ".", "metadata", "=", "statusMetadata", ".", "_getCoreRepresentation", "(", ")", ";", "if", "(", "!", "call", ".", "metadataSent", ")", "{", "end_batch", "[", "grpc", ".", "opType", ".", "SEND_INITIAL_METADATA", "]", "=", "(", "new", "Metadata", "(", ")", ")", ".", "_getCoreRepresentation", "(", ")", ";", "call", ".", "metadataSent", "=", "true", ";", "}", "message", ".", "grpcWriteFlags", "=", "flags", ";", "end_batch", "[", "grpc", ".", "opType", ".", "SEND_MESSAGE", "]", "=", "message", ";", "end_batch", "[", "grpc", ".", "opType", ".", "SEND_STATUS_FROM_SERVER", "]", "=", "status", ";", "call", ".", "startBatch", "(", "end_batch", ",", "function", "(", ")", "{", "}", ")", ";", "}" ]
Send a response to a unary or client streaming call. @private @param {grpc.Call} call The call to respond on @param {*} value The value to respond with @param {grpc~serialize} serialize Serialization function for the response @param {grpc.Metadata=} metadata Optional trailing metadata to send with status @param {number=} [flags=0] Flags for modifying how the message is sent.
[ "Send", "a", "response", "to", "a", "unary", "or", "client", "streaming", "call", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L83-L111
4,876
grpc/grpc-node
packages/grpc-native-core/src/server.js
setUpWritable
function setUpWritable(stream, serialize) { stream.finished = false; stream.status = { code : constants.status.OK, details : 'OK', metadata : new Metadata() }; stream.serialize = common.wrapIgnoreNull(serialize); function sendStatus() { var batch = {}; if (!stream.call.metadataSent) { stream.call.metadataSent = true; batch[grpc.opType.SEND_INITIAL_METADATA] = (new Metadata())._getCoreRepresentation(); } if (stream.status.metadata) { stream.status.metadata = stream.status.metadata._getCoreRepresentation(); } batch[grpc.opType.SEND_STATUS_FROM_SERVER] = stream.status; stream.call.startBatch(batch, function(){}); } stream.on('finish', sendStatus); /** * Set the pending status to a given error status. If the error does not have * code or details properties, the code will be set to grpc.status.UNKNOWN * and the details will be set to 'Unknown Error'. * @param {Error} err The error object */ function setStatus(err) { var code = constants.status.UNKNOWN; var details = 'Unknown Error'; var metadata = new Metadata(); if (err.hasOwnProperty('message')) { details = err.message; } if (err.hasOwnProperty('code')) { code = err.code; if (err.hasOwnProperty('details')) { details = err.details; } } if (err.hasOwnProperty('metadata')) { metadata = err.metadata; } stream.status = {code: code, details: details, metadata: metadata}; } /** * Terminate the call. This includes indicating that reads are done, draining * all pending writes, and sending the given error as a status * @param {Error} err The error object * @this GrpcServerStream */ function terminateCall(err) { // Drain readable data setStatus(err); stream.end(); } stream.on('error', terminateCall); /** * Override of Writable#end method that allows for sending metadata with a * success status. * @param {Metadata=} metadata Metadata to send with the status */ stream.end = function(metadata) { if (metadata) { stream.status.metadata = metadata; } Writable.prototype.end.call(this); }; }
javascript
function setUpWritable(stream, serialize) { stream.finished = false; stream.status = { code : constants.status.OK, details : 'OK', metadata : new Metadata() }; stream.serialize = common.wrapIgnoreNull(serialize); function sendStatus() { var batch = {}; if (!stream.call.metadataSent) { stream.call.metadataSent = true; batch[grpc.opType.SEND_INITIAL_METADATA] = (new Metadata())._getCoreRepresentation(); } if (stream.status.metadata) { stream.status.metadata = stream.status.metadata._getCoreRepresentation(); } batch[grpc.opType.SEND_STATUS_FROM_SERVER] = stream.status; stream.call.startBatch(batch, function(){}); } stream.on('finish', sendStatus); /** * Set the pending status to a given error status. If the error does not have * code or details properties, the code will be set to grpc.status.UNKNOWN * and the details will be set to 'Unknown Error'. * @param {Error} err The error object */ function setStatus(err) { var code = constants.status.UNKNOWN; var details = 'Unknown Error'; var metadata = new Metadata(); if (err.hasOwnProperty('message')) { details = err.message; } if (err.hasOwnProperty('code')) { code = err.code; if (err.hasOwnProperty('details')) { details = err.details; } } if (err.hasOwnProperty('metadata')) { metadata = err.metadata; } stream.status = {code: code, details: details, metadata: metadata}; } /** * Terminate the call. This includes indicating that reads are done, draining * all pending writes, and sending the given error as a status * @param {Error} err The error object * @this GrpcServerStream */ function terminateCall(err) { // Drain readable data setStatus(err); stream.end(); } stream.on('error', terminateCall); /** * Override of Writable#end method that allows for sending metadata with a * success status. * @param {Metadata=} metadata Metadata to send with the status */ stream.end = function(metadata) { if (metadata) { stream.status.metadata = metadata; } Writable.prototype.end.call(this); }; }
[ "function", "setUpWritable", "(", "stream", ",", "serialize", ")", "{", "stream", ".", "finished", "=", "false", ";", "stream", ".", "status", "=", "{", "code", ":", "constants", ".", "status", ".", "OK", ",", "details", ":", "'OK'", ",", "metadata", ":", "new", "Metadata", "(", ")", "}", ";", "stream", ".", "serialize", "=", "common", ".", "wrapIgnoreNull", "(", "serialize", ")", ";", "function", "sendStatus", "(", ")", "{", "var", "batch", "=", "{", "}", ";", "if", "(", "!", "stream", ".", "call", ".", "metadataSent", ")", "{", "stream", ".", "call", ".", "metadataSent", "=", "true", ";", "batch", "[", "grpc", ".", "opType", ".", "SEND_INITIAL_METADATA", "]", "=", "(", "new", "Metadata", "(", ")", ")", ".", "_getCoreRepresentation", "(", ")", ";", "}", "if", "(", "stream", ".", "status", ".", "metadata", ")", "{", "stream", ".", "status", ".", "metadata", "=", "stream", ".", "status", ".", "metadata", ".", "_getCoreRepresentation", "(", ")", ";", "}", "batch", "[", "grpc", ".", "opType", ".", "SEND_STATUS_FROM_SERVER", "]", "=", "stream", ".", "status", ";", "stream", ".", "call", ".", "startBatch", "(", "batch", ",", "function", "(", ")", "{", "}", ")", ";", "}", "stream", ".", "on", "(", "'finish'", ",", "sendStatus", ")", ";", "/**\n * Set the pending status to a given error status. If the error does not have\n * code or details properties, the code will be set to grpc.status.UNKNOWN\n * and the details will be set to 'Unknown Error'.\n * @param {Error} err The error object\n */", "function", "setStatus", "(", "err", ")", "{", "var", "code", "=", "constants", ".", "status", ".", "UNKNOWN", ";", "var", "details", "=", "'Unknown Error'", ";", "var", "metadata", "=", "new", "Metadata", "(", ")", ";", "if", "(", "err", ".", "hasOwnProperty", "(", "'message'", ")", ")", "{", "details", "=", "err", ".", "message", ";", "}", "if", "(", "err", ".", "hasOwnProperty", "(", "'code'", ")", ")", "{", "code", "=", "err", ".", "code", ";", "if", "(", "err", ".", "hasOwnProperty", "(", "'details'", ")", ")", "{", "details", "=", "err", ".", "details", ";", "}", "}", "if", "(", "err", ".", "hasOwnProperty", "(", "'metadata'", ")", ")", "{", "metadata", "=", "err", ".", "metadata", ";", "}", "stream", ".", "status", "=", "{", "code", ":", "code", ",", "details", ":", "details", ",", "metadata", ":", "metadata", "}", ";", "}", "/**\n * Terminate the call. This includes indicating that reads are done, draining\n * all pending writes, and sending the given error as a status\n * @param {Error} err The error object\n * @this GrpcServerStream\n */", "function", "terminateCall", "(", "err", ")", "{", "// Drain readable data", "setStatus", "(", "err", ")", ";", "stream", ".", "end", "(", ")", ";", "}", "stream", ".", "on", "(", "'error'", ",", "terminateCall", ")", ";", "/**\n * Override of Writable#end method that allows for sending metadata with a\n * success status.\n * @param {Metadata=} metadata Metadata to send with the status\n */", "stream", ".", "end", "=", "function", "(", "metadata", ")", "{", "if", "(", "metadata", ")", "{", "stream", ".", "status", ".", "metadata", "=", "metadata", ";", "}", "Writable", ".", "prototype", ".", "end", ".", "call", "(", "this", ")", ";", "}", ";", "}" ]
Initialize a writable stream. This is used for both the writable and duplex stream constructors. @private @param {Writable} stream The stream to set up @param {function(*):Buffer=} Serialization function for responses
[ "Initialize", "a", "writable", "stream", ".", "This", "is", "used", "for", "both", "the", "writable", "and", "duplex", "stream", "constructors", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L120-L190
4,877
grpc/grpc-node
packages/grpc-native-core/src/server.js
setStatus
function setStatus(err) { var code = constants.status.UNKNOWN; var details = 'Unknown Error'; var metadata = new Metadata(); if (err.hasOwnProperty('message')) { details = err.message; } if (err.hasOwnProperty('code')) { code = err.code; if (err.hasOwnProperty('details')) { details = err.details; } } if (err.hasOwnProperty('metadata')) { metadata = err.metadata; } stream.status = {code: code, details: details, metadata: metadata}; }
javascript
function setStatus(err) { var code = constants.status.UNKNOWN; var details = 'Unknown Error'; var metadata = new Metadata(); if (err.hasOwnProperty('message')) { details = err.message; } if (err.hasOwnProperty('code')) { code = err.code; if (err.hasOwnProperty('details')) { details = err.details; } } if (err.hasOwnProperty('metadata')) { metadata = err.metadata; } stream.status = {code: code, details: details, metadata: metadata}; }
[ "function", "setStatus", "(", "err", ")", "{", "var", "code", "=", "constants", ".", "status", ".", "UNKNOWN", ";", "var", "details", "=", "'Unknown Error'", ";", "var", "metadata", "=", "new", "Metadata", "(", ")", ";", "if", "(", "err", ".", "hasOwnProperty", "(", "'message'", ")", ")", "{", "details", "=", "err", ".", "message", ";", "}", "if", "(", "err", ".", "hasOwnProperty", "(", "'code'", ")", ")", "{", "code", "=", "err", ".", "code", ";", "if", "(", "err", ".", "hasOwnProperty", "(", "'details'", ")", ")", "{", "details", "=", "err", ".", "details", ";", "}", "}", "if", "(", "err", ".", "hasOwnProperty", "(", "'metadata'", ")", ")", "{", "metadata", "=", "err", ".", "metadata", ";", "}", "stream", ".", "status", "=", "{", "code", ":", "code", ",", "details", ":", "details", ",", "metadata", ":", "metadata", "}", ";", "}" ]
Set the pending status to a given error status. If the error does not have code or details properties, the code will be set to grpc.status.UNKNOWN and the details will be set to 'Unknown Error'. @param {Error} err The error object
[ "Set", "the", "pending", "status", "to", "a", "given", "error", "status", ".", "If", "the", "error", "does", "not", "have", "code", "or", "details", "properties", "the", "code", "will", "be", "set", "to", "grpc", ".", "status", ".", "UNKNOWN", "and", "the", "details", "will", "be", "set", "to", "Unknown", "Error", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L149-L166
4,878
grpc/grpc-node
packages/grpc-native-core/src/server.js
setUpReadable
function setUpReadable(stream, deserialize) { stream.deserialize = common.wrapIgnoreNull(deserialize); stream.finished = false; stream.reading = false; stream.terminate = function() { stream.finished = true; stream.on('data', function() {}); }; stream.on('cancelled', function() { stream.terminate(); }); }
javascript
function setUpReadable(stream, deserialize) { stream.deserialize = common.wrapIgnoreNull(deserialize); stream.finished = false; stream.reading = false; stream.terminate = function() { stream.finished = true; stream.on('data', function() {}); }; stream.on('cancelled', function() { stream.terminate(); }); }
[ "function", "setUpReadable", "(", "stream", ",", "deserialize", ")", "{", "stream", ".", "deserialize", "=", "common", ".", "wrapIgnoreNull", "(", "deserialize", ")", ";", "stream", ".", "finished", "=", "false", ";", "stream", ".", "reading", "=", "false", ";", "stream", ".", "terminate", "=", "function", "(", ")", "{", "stream", ".", "finished", "=", "true", ";", "stream", ".", "on", "(", "'data'", ",", "function", "(", ")", "{", "}", ")", ";", "}", ";", "stream", ".", "on", "(", "'cancelled'", ",", "function", "(", ")", "{", "stream", ".", "terminate", "(", ")", ";", "}", ")", ";", "}" ]
Initialize a readable stream. This is used for both the readable and duplex stream constructors. @private @param {Readable} stream The stream to initialize @param {grpc~deserialize} deserialize Deserialization function for incoming data.
[ "Initialize", "a", "readable", "stream", ".", "This", "is", "used", "for", "both", "the", "readable", "and", "duplex", "stream", "constructors", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L200-L213
4,879
grpc/grpc-node
packages/grpc-native-core/src/server.js
ServerUnaryCall
function ServerUnaryCall(call, metadata) { EventEmitter.call(this); this.call = call; /** * Indicates if the call has been cancelled * @member {boolean} grpc~ServerUnaryCall#cancelled */ this.cancelled = false; /** * The request metadata from the client * @member {grpc.Metadata} grpc~ServerUnaryCall#metadata */ this.metadata = metadata; /** * The request message from the client * @member {*} grpc~ServerUnaryCall#request */ this.request = undefined; }
javascript
function ServerUnaryCall(call, metadata) { EventEmitter.call(this); this.call = call; /** * Indicates if the call has been cancelled * @member {boolean} grpc~ServerUnaryCall#cancelled */ this.cancelled = false; /** * The request metadata from the client * @member {grpc.Metadata} grpc~ServerUnaryCall#metadata */ this.metadata = metadata; /** * The request message from the client * @member {*} grpc~ServerUnaryCall#request */ this.request = undefined; }
[ "function", "ServerUnaryCall", "(", "call", ",", "metadata", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "call", "=", "call", ";", "/**\n * Indicates if the call has been cancelled\n * @member {boolean} grpc~ServerUnaryCall#cancelled\n */", "this", ".", "cancelled", "=", "false", ";", "/**\n * The request metadata from the client\n * @member {grpc.Metadata} grpc~ServerUnaryCall#metadata\n */", "this", ".", "metadata", "=", "metadata", ";", "/**\n * The request message from the client\n * @member {*} grpc~ServerUnaryCall#request\n */", "this", ".", "request", "=", "undefined", ";", "}" ]
An EventEmitter. Used for unary calls. @constructor grpc~ServerUnaryCall @extends external:EventEmitter @param {grpc.internal~Call} call The call object associated with the request @param {grpc.Metadata} metadata The request metadata from the client
[ "An", "EventEmitter", ".", "Used", "for", "unary", "calls", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L230-L248
4,880
grpc/grpc-node
packages/grpc-native-core/src/server.js
ServerWritableStream
function ServerWritableStream(call, metadata, serialize) { Writable.call(this, {objectMode: true}); this.call = call; this.finished = false; setUpWritable(this, serialize); /** * Indicates if the call has been cancelled * @member {boolean} grpc~ServerWritableStream#cancelled */ this.cancelled = false; /** * The request metadata from the client * @member {grpc.Metadata} grpc~ServerWritableStream#metadata */ this.metadata = metadata; /** * The request message from the client * @member {*} grpc~ServerWritableStream#request */ this.request = undefined; }
javascript
function ServerWritableStream(call, metadata, serialize) { Writable.call(this, {objectMode: true}); this.call = call; this.finished = false; setUpWritable(this, serialize); /** * Indicates if the call has been cancelled * @member {boolean} grpc~ServerWritableStream#cancelled */ this.cancelled = false; /** * The request metadata from the client * @member {grpc.Metadata} grpc~ServerWritableStream#metadata */ this.metadata = metadata; /** * The request message from the client * @member {*} grpc~ServerWritableStream#request */ this.request = undefined; }
[ "function", "ServerWritableStream", "(", "call", ",", "metadata", ",", "serialize", ")", "{", "Writable", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "call", "=", "call", ";", "this", ".", "finished", "=", "false", ";", "setUpWritable", "(", "this", ",", "serialize", ")", ";", "/**\n * Indicates if the call has been cancelled\n * @member {boolean} grpc~ServerWritableStream#cancelled\n */", "this", ".", "cancelled", "=", "false", ";", "/**\n * The request metadata from the client\n * @member {grpc.Metadata} grpc~ServerWritableStream#metadata\n */", "this", ".", "metadata", "=", "metadata", ";", "/**\n * The request message from the client\n * @member {*} grpc~ServerWritableStream#request\n */", "this", ".", "request", "=", "undefined", ";", "}" ]
A stream that the server can write to. Used for calls that are streaming from the server side. @constructor grpc~ServerWritableStream @extends external:Writable @borrows grpc~ServerUnaryCall#sendMetadata as grpc~ServerWritableStream#sendMetadata @borrows grpc~ServerUnaryCall#getPeer as grpc~ServerWritableStream#getPeer @param {grpc.internal~Call} call The call object to send data with @param {grpc.Metadata} metadata The request metadata from the client @param {grpc~serialize} serialize Serialization function for writes
[ "A", "stream", "that", "the", "server", "can", "write", "to", ".", "Used", "for", "calls", "that", "are", "streaming", "from", "the", "server", "side", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L270-L291
4,881
grpc/grpc-node
packages/grpc-native-core/src/server.js
_write
function _write(chunk, encoding, callback) { /* jshint validthis: true */ var batch = {}; var self = this; var message; try { message = this.serialize(chunk); } catch (e) { e.code = constants.status.INTERNAL; callback(e); return; } if (!this.call.metadataSent) { batch[grpc.opType.SEND_INITIAL_METADATA] = (new Metadata())._getCoreRepresentation(); this.call.metadataSent = true; } if (Number.isFinite(encoding)) { /* Attach the encoding if it is a finite number. This is the closest we * can get to checking that it is valid flags */ message.grpcWriteFlags = encoding; } batch[grpc.opType.SEND_MESSAGE] = message; this.call.startBatch(batch, function(err, value) { if (err) { self.emit('error', err); return; } callback(); }); }
javascript
function _write(chunk, encoding, callback) { /* jshint validthis: true */ var batch = {}; var self = this; var message; try { message = this.serialize(chunk); } catch (e) { e.code = constants.status.INTERNAL; callback(e); return; } if (!this.call.metadataSent) { batch[grpc.opType.SEND_INITIAL_METADATA] = (new Metadata())._getCoreRepresentation(); this.call.metadataSent = true; } if (Number.isFinite(encoding)) { /* Attach the encoding if it is a finite number. This is the closest we * can get to checking that it is valid flags */ message.grpcWriteFlags = encoding; } batch[grpc.opType.SEND_MESSAGE] = message; this.call.startBatch(batch, function(err, value) { if (err) { self.emit('error', err); return; } callback(); }); }
[ "function", "_write", "(", "chunk", ",", "encoding", ",", "callback", ")", "{", "/* jshint validthis: true */", "var", "batch", "=", "{", "}", ";", "var", "self", "=", "this", ";", "var", "message", ";", "try", "{", "message", "=", "this", ".", "serialize", "(", "chunk", ")", ";", "}", "catch", "(", "e", ")", "{", "e", ".", "code", "=", "constants", ".", "status", ".", "INTERNAL", ";", "callback", "(", "e", ")", ";", "return", ";", "}", "if", "(", "!", "this", ".", "call", ".", "metadataSent", ")", "{", "batch", "[", "grpc", ".", "opType", ".", "SEND_INITIAL_METADATA", "]", "=", "(", "new", "Metadata", "(", ")", ")", ".", "_getCoreRepresentation", "(", ")", ";", "this", ".", "call", ".", "metadataSent", "=", "true", ";", "}", "if", "(", "Number", ".", "isFinite", "(", "encoding", ")", ")", "{", "/* Attach the encoding if it is a finite number. This is the closest we\n * can get to checking that it is valid flags */", "message", ".", "grpcWriteFlags", "=", "encoding", ";", "}", "batch", "[", "grpc", ".", "opType", ".", "SEND_MESSAGE", "]", "=", "message", ";", "this", ".", "call", ".", "startBatch", "(", "batch", ",", "function", "(", "err", ",", "value", ")", "{", "if", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "return", ";", "}", "callback", "(", ")", ";", "}", ")", ";", "}" ]
Start writing a chunk of data. This is an implementation of a method required for implementing stream.Writable. @private @param {Buffer} chunk The chunk of data to write @param {string} encoding Used to pass write flags @param {function(Error=)} callback Callback to indicate that the write is complete
[ "Start", "writing", "a", "chunk", "of", "data", ".", "This", "is", "an", "implementation", "of", "a", "method", "required", "for", "implementing", "stream", ".", "Writable", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L302-L332
4,882
grpc/grpc-node
packages/grpc-native-core/src/server.js
ServerReadableStream
function ServerReadableStream(call, metadata, deserialize) { Readable.call(this, {objectMode: true}); this.call = call; setUpReadable(this, deserialize); /** * Indicates if the call has been cancelled * @member {boolean} grpc~ServerReadableStream#cancelled */ this.cancelled = false; /** * The request metadata from the client * @member {grpc.Metadata} grpc~ServerReadableStream#metadata */ this.metadata = metadata; }
javascript
function ServerReadableStream(call, metadata, deserialize) { Readable.call(this, {objectMode: true}); this.call = call; setUpReadable(this, deserialize); /** * Indicates if the call has been cancelled * @member {boolean} grpc~ServerReadableStream#cancelled */ this.cancelled = false; /** * The request metadata from the client * @member {grpc.Metadata} grpc~ServerReadableStream#metadata */ this.metadata = metadata; }
[ "function", "ServerReadableStream", "(", "call", ",", "metadata", ",", "deserialize", ")", "{", "Readable", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "call", "=", "call", ";", "setUpReadable", "(", "this", ",", "deserialize", ")", ";", "/**\n * Indicates if the call has been cancelled\n * @member {boolean} grpc~ServerReadableStream#cancelled\n */", "this", ".", "cancelled", "=", "false", ";", "/**\n * The request metadata from the client\n * @member {grpc.Metadata} grpc~ServerReadableStream#metadata\n */", "this", ".", "metadata", "=", "metadata", ";", "}" ]
A stream that the server can read from. Used for calls that are streaming from the client side. @constructor grpc~ServerReadableStream @extends external:Readable @borrows grpc~ServerUnaryCall#sendMetadata as grpc~ServerReadableStream#sendMetadata @borrows grpc~ServerUnaryCall#getPeer as grpc~ServerReadableStream#getPeer @param {grpc.internal~Call} call The call object to read data with @param {grpc.Metadata} metadata The request metadata from the client @param {grpc~deserialize} deserialize Deserialization function for reads
[ "A", "stream", "that", "the", "server", "can", "read", "from", ".", "Used", "for", "calls", "that", "are", "streaming", "from", "the", "client", "side", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L356-L370
4,883
grpc/grpc-node
packages/grpc-native-core/src/server.js
_read
function _read(size) { /* jshint validthis: true */ var self = this; /** * Callback to be called when a READ event is received. Pushes the data onto * the read queue and starts reading again if applicable * @param {grpc.Event} event READ event object */ function readCallback(err, event) { if (err) { self.terminate(); return; } if (self.finished) { self.push(null); return; } var data = event.read; var deserialized; try { deserialized = self.deserialize(data); } catch (e) { e.code = constants.status.INTERNAL; self.emit('error', e); return; } if (self.push(deserialized) && data !== null) { var read_batch = {}; read_batch[grpc.opType.RECV_MESSAGE] = true; self.call.startBatch(read_batch, readCallback); } else { self.reading = false; } } if (self.finished) { self.push(null); } else { if (!self.reading) { self.reading = true; var batch = {}; batch[grpc.opType.RECV_MESSAGE] = true; self.call.startBatch(batch, readCallback); } } }
javascript
function _read(size) { /* jshint validthis: true */ var self = this; /** * Callback to be called when a READ event is received. Pushes the data onto * the read queue and starts reading again if applicable * @param {grpc.Event} event READ event object */ function readCallback(err, event) { if (err) { self.terminate(); return; } if (self.finished) { self.push(null); return; } var data = event.read; var deserialized; try { deserialized = self.deserialize(data); } catch (e) { e.code = constants.status.INTERNAL; self.emit('error', e); return; } if (self.push(deserialized) && data !== null) { var read_batch = {}; read_batch[grpc.opType.RECV_MESSAGE] = true; self.call.startBatch(read_batch, readCallback); } else { self.reading = false; } } if (self.finished) { self.push(null); } else { if (!self.reading) { self.reading = true; var batch = {}; batch[grpc.opType.RECV_MESSAGE] = true; self.call.startBatch(batch, readCallback); } } }
[ "function", "_read", "(", "size", ")", "{", "/* jshint validthis: true */", "var", "self", "=", "this", ";", "/**\n * Callback to be called when a READ event is received. Pushes the data onto\n * the read queue and starts reading again if applicable\n * @param {grpc.Event} event READ event object\n */", "function", "readCallback", "(", "err", ",", "event", ")", "{", "if", "(", "err", ")", "{", "self", ".", "terminate", "(", ")", ";", "return", ";", "}", "if", "(", "self", ".", "finished", ")", "{", "self", ".", "push", "(", "null", ")", ";", "return", ";", "}", "var", "data", "=", "event", ".", "read", ";", "var", "deserialized", ";", "try", "{", "deserialized", "=", "self", ".", "deserialize", "(", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "e", ".", "code", "=", "constants", ".", "status", ".", "INTERNAL", ";", "self", ".", "emit", "(", "'error'", ",", "e", ")", ";", "return", ";", "}", "if", "(", "self", ".", "push", "(", "deserialized", ")", "&&", "data", "!==", "null", ")", "{", "var", "read_batch", "=", "{", "}", ";", "read_batch", "[", "grpc", ".", "opType", ".", "RECV_MESSAGE", "]", "=", "true", ";", "self", ".", "call", ".", "startBatch", "(", "read_batch", ",", "readCallback", ")", ";", "}", "else", "{", "self", ".", "reading", "=", "false", ";", "}", "}", "if", "(", "self", ".", "finished", ")", "{", "self", ".", "push", "(", "null", ")", ";", "}", "else", "{", "if", "(", "!", "self", ".", "reading", ")", "{", "self", ".", "reading", "=", "true", ";", "var", "batch", "=", "{", "}", ";", "batch", "[", "grpc", ".", "opType", ".", "RECV_MESSAGE", "]", "=", "true", ";", "self", ".", "call", ".", "startBatch", "(", "batch", ",", "readCallback", ")", ";", "}", "}", "}" ]
Start reading from the gRPC data source. This is an implementation of a method required for implementing stream.Readable @access private @param {number} size Ignored
[ "Start", "reading", "from", "the", "gRPC", "data", "source", ".", "This", "is", "an", "implementation", "of", "a", "method", "required", "for", "implementing", "stream", ".", "Readable" ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L378-L422
4,884
grpc/grpc-node
packages/grpc-native-core/src/server.js
readCallback
function readCallback(err, event) { if (err) { self.terminate(); return; } if (self.finished) { self.push(null); return; } var data = event.read; var deserialized; try { deserialized = self.deserialize(data); } catch (e) { e.code = constants.status.INTERNAL; self.emit('error', e); return; } if (self.push(deserialized) && data !== null) { var read_batch = {}; read_batch[grpc.opType.RECV_MESSAGE] = true; self.call.startBatch(read_batch, readCallback); } else { self.reading = false; } }
javascript
function readCallback(err, event) { if (err) { self.terminate(); return; } if (self.finished) { self.push(null); return; } var data = event.read; var deserialized; try { deserialized = self.deserialize(data); } catch (e) { e.code = constants.status.INTERNAL; self.emit('error', e); return; } if (self.push(deserialized) && data !== null) { var read_batch = {}; read_batch[grpc.opType.RECV_MESSAGE] = true; self.call.startBatch(read_batch, readCallback); } else { self.reading = false; } }
[ "function", "readCallback", "(", "err", ",", "event", ")", "{", "if", "(", "err", ")", "{", "self", ".", "terminate", "(", ")", ";", "return", ";", "}", "if", "(", "self", ".", "finished", ")", "{", "self", ".", "push", "(", "null", ")", ";", "return", ";", "}", "var", "data", "=", "event", ".", "read", ";", "var", "deserialized", ";", "try", "{", "deserialized", "=", "self", ".", "deserialize", "(", "data", ")", ";", "}", "catch", "(", "e", ")", "{", "e", ".", "code", "=", "constants", ".", "status", ".", "INTERNAL", ";", "self", ".", "emit", "(", "'error'", ",", "e", ")", ";", "return", ";", "}", "if", "(", "self", ".", "push", "(", "deserialized", ")", "&&", "data", "!==", "null", ")", "{", "var", "read_batch", "=", "{", "}", ";", "read_batch", "[", "grpc", ".", "opType", ".", "RECV_MESSAGE", "]", "=", "true", ";", "self", ".", "call", ".", "startBatch", "(", "read_batch", ",", "readCallback", ")", ";", "}", "else", "{", "self", ".", "reading", "=", "false", ";", "}", "}" ]
Callback to be called when a READ event is received. Pushes the data onto the read queue and starts reading again if applicable @param {grpc.Event} event READ event object
[ "Callback", "to", "be", "called", "when", "a", "READ", "event", "is", "received", ".", "Pushes", "the", "data", "onto", "the", "read", "queue", "and", "starts", "reading", "again", "if", "applicable" ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L386-L411
4,885
grpc/grpc-node
packages/grpc-native-core/src/server.js
ServerDuplexStream
function ServerDuplexStream(call, metadata, serialize, deserialize) { Duplex.call(this, {objectMode: true}); this.call = call; setUpWritable(this, serialize); setUpReadable(this, deserialize); /** * Indicates if the call has been cancelled * @member {boolean} grpc~ServerReadableStream#cancelled */ this.cancelled = false; /** * The request metadata from the client * @member {grpc.Metadata} grpc~ServerReadableStream#metadata */ this.metadata = metadata; }
javascript
function ServerDuplexStream(call, metadata, serialize, deserialize) { Duplex.call(this, {objectMode: true}); this.call = call; setUpWritable(this, serialize); setUpReadable(this, deserialize); /** * Indicates if the call has been cancelled * @member {boolean} grpc~ServerReadableStream#cancelled */ this.cancelled = false; /** * The request metadata from the client * @member {grpc.Metadata} grpc~ServerReadableStream#metadata */ this.metadata = metadata; }
[ "function", "ServerDuplexStream", "(", "call", ",", "metadata", ",", "serialize", ",", "deserialize", ")", "{", "Duplex", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "call", "=", "call", ";", "setUpWritable", "(", "this", ",", "serialize", ")", ";", "setUpReadable", "(", "this", ",", "deserialize", ")", ";", "/**\n * Indicates if the call has been cancelled\n * @member {boolean} grpc~ServerReadableStream#cancelled\n */", "this", ".", "cancelled", "=", "false", ";", "/**\n * The request metadata from the client\n * @member {grpc.Metadata} grpc~ServerReadableStream#metadata\n */", "this", ".", "metadata", "=", "metadata", ";", "}" ]
A stream that the server can read from or write to. Used for calls with duplex streaming. @constructor grpc~ServerDuplexStream @extends external:Duplex @borrows grpc~ServerUnaryCall#sendMetadata as grpc~ServerDuplexStream#sendMetadata @borrows grpc~ServerUnaryCall#getPeer as grpc~ServerDuplexStream#getPeer @param {grpc.internal~Call} call Call object to proxy @param {grpc.Metadata} metadata The request metadata from the client @param {grpc~serialize} serialize Serialization function for requests @param {grpc~deserialize} deserialize Deserialization function for responses
[ "A", "stream", "that", "the", "server", "can", "read", "from", "or", "write", "to", ".", "Used", "for", "calls", "with", "duplex", "streaming", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L448-L463
4,886
grpc/grpc-node
packages/grpc-native-core/src/server.js
sendMetadata
function sendMetadata(responseMetadata) { /* jshint validthis: true */ var self = this; if (!this.call.metadataSent) { this.call.metadataSent = true; var batch = {}; batch[grpc.opType.SEND_INITIAL_METADATA] = responseMetadata._getCoreRepresentation(); this.call.startBatch(batch, function(err) { if (err) { self.emit('error', err); return; } }); } }
javascript
function sendMetadata(responseMetadata) { /* jshint validthis: true */ var self = this; if (!this.call.metadataSent) { this.call.metadataSent = true; var batch = {}; batch[grpc.opType.SEND_INITIAL_METADATA] = responseMetadata._getCoreRepresentation(); this.call.startBatch(batch, function(err) { if (err) { self.emit('error', err); return; } }); } }
[ "function", "sendMetadata", "(", "responseMetadata", ")", "{", "/* jshint validthis: true */", "var", "self", "=", "this", ";", "if", "(", "!", "this", ".", "call", ".", "metadataSent", ")", "{", "this", ".", "call", ".", "metadataSent", "=", "true", ";", "var", "batch", "=", "{", "}", ";", "batch", "[", "grpc", ".", "opType", ".", "SEND_INITIAL_METADATA", "]", "=", "responseMetadata", ".", "_getCoreRepresentation", "(", ")", ";", "this", ".", "call", ".", "startBatch", "(", "batch", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "return", ";", "}", "}", ")", ";", "}", "}" ]
Send the initial metadata for a writable stream. @alias grpc~ServerUnaryCall#sendMetadata @param {grpc.Metadata} responseMetadata Metadata to send
[ "Send", "the", "initial", "metadata", "for", "a", "writable", "stream", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L473-L488
4,887
grpc/grpc-node
packages/grpc-native-core/src/server.js
waitForCancel
function waitForCancel() { /* jshint validthis: true */ var self = this; var cancel_batch = {}; cancel_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; self.call.startBatch(cancel_batch, function(err, result) { if (err) { self.emit('error', err); } if (result.cancelled) { self.cancelled = true; self.emit('cancelled'); } }); }
javascript
function waitForCancel() { /* jshint validthis: true */ var self = this; var cancel_batch = {}; cancel_batch[grpc.opType.RECV_CLOSE_ON_SERVER] = true; self.call.startBatch(cancel_batch, function(err, result) { if (err) { self.emit('error', err); } if (result.cancelled) { self.cancelled = true; self.emit('cancelled'); } }); }
[ "function", "waitForCancel", "(", ")", "{", "/* jshint validthis: true */", "var", "self", "=", "this", ";", "var", "cancel_batch", "=", "{", "}", ";", "cancel_batch", "[", "grpc", ".", "opType", ".", "RECV_CLOSE_ON_SERVER", "]", "=", "true", ";", "self", ".", "call", ".", "startBatch", "(", "cancel_batch", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", "if", "(", "result", ".", "cancelled", ")", "{", "self", ".", "cancelled", "=", "true", ";", "self", ".", "emit", "(", "'cancelled'", ")", ";", "}", "}", ")", ";", "}" ]
Wait for the client to close, then emit a cancelled event if the client cancelled. @private
[ "Wait", "for", "the", "client", "to", "close", "then", "emit", "a", "cancelled", "event", "if", "the", "client", "cancelled", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L515-L529
4,888
grpc/grpc-node
packages/grpc-native-core/src/server.js
handleUnary
function handleUnary(call, handler, metadata) { var emitter = new ServerUnaryCall(call, metadata); emitter.on('error', function(error) { handleError(call, error); }); emitter.waitForCancel(); var batch = {}; batch[grpc.opType.RECV_MESSAGE] = true; call.startBatch(batch, function(err, result) { if (err) { handleError(call, err); return; } try { emitter.request = handler.deserialize(result.read); } catch (e) { e.code = constants.status.INTERNAL; handleError(call, e); return; } if (emitter.cancelled) { return; } handler.func(emitter, function sendUnaryData(err, value, trailer, flags) { if (err) { if (trailer) { err.metadata = trailer; } handleError(call, err); } else { sendUnaryResponse(call, value, handler.serialize, trailer, flags); } }); }); }
javascript
function handleUnary(call, handler, metadata) { var emitter = new ServerUnaryCall(call, metadata); emitter.on('error', function(error) { handleError(call, error); }); emitter.waitForCancel(); var batch = {}; batch[grpc.opType.RECV_MESSAGE] = true; call.startBatch(batch, function(err, result) { if (err) { handleError(call, err); return; } try { emitter.request = handler.deserialize(result.read); } catch (e) { e.code = constants.status.INTERNAL; handleError(call, e); return; } if (emitter.cancelled) { return; } handler.func(emitter, function sendUnaryData(err, value, trailer, flags) { if (err) { if (trailer) { err.metadata = trailer; } handleError(call, err); } else { sendUnaryResponse(call, value, handler.serialize, trailer, flags); } }); }); }
[ "function", "handleUnary", "(", "call", ",", "handler", ",", "metadata", ")", "{", "var", "emitter", "=", "new", "ServerUnaryCall", "(", "call", ",", "metadata", ")", ";", "emitter", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "handleError", "(", "call", ",", "error", ")", ";", "}", ")", ";", "emitter", ".", "waitForCancel", "(", ")", ";", "var", "batch", "=", "{", "}", ";", "batch", "[", "grpc", ".", "opType", ".", "RECV_MESSAGE", "]", "=", "true", ";", "call", ".", "startBatch", "(", "batch", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "handleError", "(", "call", ",", "err", ")", ";", "return", ";", "}", "try", "{", "emitter", ".", "request", "=", "handler", ".", "deserialize", "(", "result", ".", "read", ")", ";", "}", "catch", "(", "e", ")", "{", "e", ".", "code", "=", "constants", ".", "status", ".", "INTERNAL", ";", "handleError", "(", "call", ",", "e", ")", ";", "return", ";", "}", "if", "(", "emitter", ".", "cancelled", ")", "{", "return", ";", "}", "handler", ".", "func", "(", "emitter", ",", "function", "sendUnaryData", "(", "err", ",", "value", ",", "trailer", ",", "flags", ")", "{", "if", "(", "err", ")", "{", "if", "(", "trailer", ")", "{", "err", ".", "metadata", "=", "trailer", ";", "}", "handleError", "(", "call", ",", "err", ")", ";", "}", "else", "{", "sendUnaryResponse", "(", "call", ",", "value", ",", "handler", ".", "serialize", ",", "trailer", ",", "flags", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
User-provided method to handle unary requests on a server @callback grpc.Server~handleUnaryCall @param {grpc~ServerUnaryCall} call The call object @param {grpc.Server~sendUnaryData} callback The callback to call to respond to the request Fully handle a unary call @private @param {grpc.internal~Call} call The call to handle @param {Object} handler Request handler object for the method that was called @param {grpc~Server.handleUnaryCall} handler.func The handler function @param {grpc~deserialize} handler.deserialize The deserialization function for request data @param {grpc~serialize} handler.serialize The serialization function for response data @param {grpc.Metadata} metadata Metadata from the client
[ "User", "-", "provided", "method", "to", "handle", "unary", "requests", "on", "a", "server" ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L567-L601
4,889
grpc/grpc-node
packages/grpc-native-core/src/server.js
handleServerStreaming
function handleServerStreaming(call, handler, metadata) { var stream = new ServerWritableStream(call, metadata, handler.serialize); stream.waitForCancel(); var batch = {}; batch[grpc.opType.RECV_MESSAGE] = true; call.startBatch(batch, function(err, result) { if (err) { stream.emit('error', err); return; } try { stream.request = handler.deserialize(result.read); } catch (e) { e.code = constants.status.INTERNAL; stream.emit('error', e); return; } handler.func(stream); }); }
javascript
function handleServerStreaming(call, handler, metadata) { var stream = new ServerWritableStream(call, metadata, handler.serialize); stream.waitForCancel(); var batch = {}; batch[grpc.opType.RECV_MESSAGE] = true; call.startBatch(batch, function(err, result) { if (err) { stream.emit('error', err); return; } try { stream.request = handler.deserialize(result.read); } catch (e) { e.code = constants.status.INTERNAL; stream.emit('error', e); return; } handler.func(stream); }); }
[ "function", "handleServerStreaming", "(", "call", ",", "handler", ",", "metadata", ")", "{", "var", "stream", "=", "new", "ServerWritableStream", "(", "call", ",", "metadata", ",", "handler", ".", "serialize", ")", ";", "stream", ".", "waitForCancel", "(", ")", ";", "var", "batch", "=", "{", "}", ";", "batch", "[", "grpc", ".", "opType", ".", "RECV_MESSAGE", "]", "=", "true", ";", "call", ".", "startBatch", "(", "batch", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "stream", ".", "emit", "(", "'error'", ",", "err", ")", ";", "return", ";", "}", "try", "{", "stream", ".", "request", "=", "handler", ".", "deserialize", "(", "result", ".", "read", ")", ";", "}", "catch", "(", "e", ")", "{", "e", ".", "code", "=", "constants", ".", "status", ".", "INTERNAL", ";", "stream", ".", "emit", "(", "'error'", ",", "e", ")", ";", "return", ";", "}", "handler", ".", "func", "(", "stream", ")", ";", "}", ")", ";", "}" ]
User provided method to handle server streaming methods on the server. @callback grpc.Server~handleServerStreamingCall @param {grpc~ServerWritableStream} call The call object Fully handle a server streaming call @private @param {grpc.internal~Call} call The call to handle @param {Object} handler Request handler object for the method that was called @param {grpc~Server.handleServerStreamingCall} handler.func The handler function @param {grpc~deserialize} handler.deserialize The deserialization function for request data @param {grpc~serialize} handler.serialize The serialization function for response data @param {grpc.Metadata} metadata Metadata from the client
[ "User", "provided", "method", "to", "handle", "server", "streaming", "methods", "on", "the", "server", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L622-L641
4,890
grpc/grpc-node
packages/grpc-native-core/src/server.js
handleClientStreaming
function handleClientStreaming(call, handler, metadata) { var stream = new ServerReadableStream(call, metadata, handler.deserialize); stream.on('error', function(error) { handleError(call, error); }); stream.waitForCancel(); handler.func(stream, function(err, value, trailer, flags) { stream.terminate(); if (err) { if (trailer) { err.metadata = trailer; } handleError(call, err); } else { sendUnaryResponse(call, value, handler.serialize, trailer, flags); } }); }
javascript
function handleClientStreaming(call, handler, metadata) { var stream = new ServerReadableStream(call, metadata, handler.deserialize); stream.on('error', function(error) { handleError(call, error); }); stream.waitForCancel(); handler.func(stream, function(err, value, trailer, flags) { stream.terminate(); if (err) { if (trailer) { err.metadata = trailer; } handleError(call, err); } else { sendUnaryResponse(call, value, handler.serialize, trailer, flags); } }); }
[ "function", "handleClientStreaming", "(", "call", ",", "handler", ",", "metadata", ")", "{", "var", "stream", "=", "new", "ServerReadableStream", "(", "call", ",", "metadata", ",", "handler", ".", "deserialize", ")", ";", "stream", ".", "on", "(", "'error'", ",", "function", "(", "error", ")", "{", "handleError", "(", "call", ",", "error", ")", ";", "}", ")", ";", "stream", ".", "waitForCancel", "(", ")", ";", "handler", ".", "func", "(", "stream", ",", "function", "(", "err", ",", "value", ",", "trailer", ",", "flags", ")", "{", "stream", ".", "terminate", "(", ")", ";", "if", "(", "err", ")", "{", "if", "(", "trailer", ")", "{", "err", ".", "metadata", "=", "trailer", ";", "}", "handleError", "(", "call", ",", "err", ")", ";", "}", "else", "{", "sendUnaryResponse", "(", "call", ",", "value", ",", "handler", ".", "serialize", ",", "trailer", ",", "flags", ")", ";", "}", "}", ")", ";", "}" ]
User provided method to handle client streaming methods on the server. @callback grpc.Server~handleClientStreamingCall @param {grpc~ServerReadableStream} call The call object @param {grpc.Server~sendUnaryData} callback The callback to call to respond to the request Fully handle a client streaming call @access private @param {grpc.internal~Call} call The call to handle @param {Object} handler Request handler object for the method that was called @param {grpc~Server.handleClientStreamingCall} handler.func The handler function @param {grpc~deserialize} handler.deserialize The deserialization function for request data @param {grpc~serialize} handler.serialize The serialization function for response data @param {grpc.Metadata} metadata Metadata from the client
[ "User", "provided", "method", "to", "handle", "client", "streaming", "methods", "on", "the", "server", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L664-L681
4,891
grpc/grpc-node
packages/grpc-native-core/src/server.js
handleBidiStreaming
function handleBidiStreaming(call, handler, metadata) { var stream = new ServerDuplexStream(call, metadata, handler.serialize, handler.deserialize); stream.waitForCancel(); handler.func(stream); }
javascript
function handleBidiStreaming(call, handler, metadata) { var stream = new ServerDuplexStream(call, metadata, handler.serialize, handler.deserialize); stream.waitForCancel(); handler.func(stream); }
[ "function", "handleBidiStreaming", "(", "call", ",", "handler", ",", "metadata", ")", "{", "var", "stream", "=", "new", "ServerDuplexStream", "(", "call", ",", "metadata", ",", "handler", ".", "serialize", ",", "handler", ".", "deserialize", ")", ";", "stream", ".", "waitForCancel", "(", ")", ";", "handler", ".", "func", "(", "stream", ")", ";", "}" ]
User provided method to handle bidirectional streaming calls on the server. @callback grpc.Server~handleBidiStreamingCall @param {grpc~ServerDuplexStream} call The call object Fully handle a bidirectional streaming call @private @param {grpc.internal~Call} call The call to handle @param {Object} handler Request handler object for the method that was called @param {grpc~Server.handleBidiStreamingCall} handler.func The handler function @param {grpc~deserialize} handler.deserialize The deserialization function for request data @param {grpc~serialize} handler.serialize The serialization function for response data @param {Metadata} metadata Metadata from the client
[ "User", "provided", "method", "to", "handle", "bidirectional", "streaming", "calls", "on", "the", "server", "." ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L702-L707
4,892
grpc/grpc-node
packages/grpc-native-core/src/server.js
Server
function Server(options) { this.handlers = {}; var server = new grpc.Server(options); this._server = server; this.started = false; }
javascript
function Server(options) { this.handlers = {}; var server = new grpc.Server(options); this._server = server; this.started = false; }
[ "function", "Server", "(", "options", ")", "{", "this", ".", "handlers", "=", "{", "}", ";", "var", "server", "=", "new", "grpc", ".", "Server", "(", "options", ")", ";", "this", ".", "_server", "=", "server", ";", "this", ".", "started", "=", "false", ";", "}" ]
Constructs a server object that stores request handlers and delegates incoming requests to those handlers @memberof grpc @constructor @param {Object=} options Options that should be passed to the internal server implementation @example var server = new grpc.Server(); server.addProtoService(protobuf_service_descriptor, service_implementation); server.bind('address:port', server_credential); server.start();
[ "Constructs", "a", "server", "object", "that", "stores", "request", "handlers", "and", "delegates", "incoming", "requests", "to", "those", "handlers" ]
b36b285f4cdb334bbd48f74c12c13bec69961488
https://github.com/grpc/grpc-node/blob/b36b285f4cdb334bbd48f74c12c13bec69961488/packages/grpc-native-core/src/server.js#L729-L734
4,893
angular/material
src/components/colors/colors.spec.js
checkColorMode
function checkColorMode() { if (angular.isUndefined(usesRGBA)) { var testerElement = compile('<div md-colors="{background: \'red\'}" >'); usesRGBA = testerElement[0].style.background.indexOf('rgba') === 0; } }
javascript
function checkColorMode() { if (angular.isUndefined(usesRGBA)) { var testerElement = compile('<div md-colors="{background: \'red\'}" >'); usesRGBA = testerElement[0].style.background.indexOf('rgba') === 0; } }
[ "function", "checkColorMode", "(", ")", "{", "if", "(", "angular", ".", "isUndefined", "(", "usesRGBA", ")", ")", "{", "var", "testerElement", "=", "compile", "(", "'<div md-colors=\"{background: \\'red\\'}\" >'", ")", ";", "usesRGBA", "=", "testerElement", "[", "0", "]", ".", "style", ".", "background", ".", "indexOf", "(", "'rgba'", ")", "===", "0", ";", "}", "}" ]
Checks whether the current browser uses RGB or RGBA colors. This is necessary, because IE and Edge automatically convert RGB colors to RGBA.
[ "Checks", "whether", "the", "current", "browser", "uses", "RGB", "or", "RGBA", "colors", ".", "This", "is", "necessary", "because", "IE", "and", "Edge", "automatically", "convert", "RGB", "colors", "to", "RGBA", "." ]
84ac558674e73958be84312444c48d9f823f6684
https://github.com/angular/material/blob/84ac558674e73958be84312444c48d9f823f6684/src/components/colors/colors.spec.js#L49-L54
4,894
angular/material
src/core/services/registry/componentRegistry.js
function(handle) { if (!isValidID(handle)) return null; var i, j, instance; for (i = 0, j = instances.length; i < j; i++) { instance = instances[i]; if (instance.$$mdHandle === handle) { return instance; } } return null; }
javascript
function(handle) { if (!isValidID(handle)) return null; var i, j, instance; for (i = 0, j = instances.length; i < j; i++) { instance = instances[i]; if (instance.$$mdHandle === handle) { return instance; } } return null; }
[ "function", "(", "handle", ")", "{", "if", "(", "!", "isValidID", "(", "handle", ")", ")", "return", "null", ";", "var", "i", ",", "j", ",", "instance", ";", "for", "(", "i", "=", "0", ",", "j", "=", "instances", ".", "length", ";", "i", "<", "j", ";", "i", "++", ")", "{", "instance", "=", "instances", "[", "i", "]", ";", "if", "(", "instance", ".", "$$mdHandle", "===", "handle", ")", "{", "return", "instance", ";", "}", "}", "return", "null", ";", "}" ]
Get a registered instance. @param handle the String handle to look up for a registered instance.
[ "Get", "a", "registered", "instance", "." ]
84ac558674e73958be84312444c48d9f823f6684
https://github.com/angular/material/blob/84ac558674e73958be84312444c48d9f823f6684/src/core/services/registry/componentRegistry.js#L43-L54
4,895
angular/material
src/core/services/registry/componentRegistry.js
function(instance, handle) { if (!handle) return angular.noop; instance.$$mdHandle = handle; instances.push(instance); resolveWhen(); return deregister; /** * Remove registration for an instance */ function deregister() { var index = instances.indexOf(instance); if (index !== -1) { instances.splice(index, 1); } } /** * Resolve any pending promises for this instance */ function resolveWhen() { var dfd = pendings[handle]; if (dfd) { dfd.forEach(function (promise) { promise.resolve(instance); }); delete pendings[handle]; } } }
javascript
function(instance, handle) { if (!handle) return angular.noop; instance.$$mdHandle = handle; instances.push(instance); resolveWhen(); return deregister; /** * Remove registration for an instance */ function deregister() { var index = instances.indexOf(instance); if (index !== -1) { instances.splice(index, 1); } } /** * Resolve any pending promises for this instance */ function resolveWhen() { var dfd = pendings[handle]; if (dfd) { dfd.forEach(function (promise) { promise.resolve(instance); }); delete pendings[handle]; } } }
[ "function", "(", "instance", ",", "handle", ")", "{", "if", "(", "!", "handle", ")", "return", "angular", ".", "noop", ";", "instance", ".", "$$mdHandle", "=", "handle", ";", "instances", ".", "push", "(", "instance", ")", ";", "resolveWhen", "(", ")", ";", "return", "deregister", ";", "/**\n * Remove registration for an instance\n */", "function", "deregister", "(", ")", "{", "var", "index", "=", "instances", ".", "indexOf", "(", "instance", ")", ";", "if", "(", "index", "!==", "-", "1", ")", "{", "instances", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "}", "/**\n * Resolve any pending promises for this instance\n */", "function", "resolveWhen", "(", ")", "{", "var", "dfd", "=", "pendings", "[", "handle", "]", ";", "if", "(", "dfd", ")", "{", "dfd", ".", "forEach", "(", "function", "(", "promise", ")", "{", "promise", ".", "resolve", "(", "instance", ")", ";", "}", ")", ";", "delete", "pendings", "[", "handle", "]", ";", "}", "}", "}" ]
Register an instance. @param instance the instance to register @param handle the handle to identify the instance under.
[ "Register", "an", "instance", "." ]
84ac558674e73958be84312444c48d9f823f6684
https://github.com/angular/material/blob/84ac558674e73958be84312444c48d9f823f6684/src/core/services/registry/componentRegistry.js#L61-L92
4,896
angular/material
src/core/services/registry/componentRegistry.js
resolveWhen
function resolveWhen() { var dfd = pendings[handle]; if (dfd) { dfd.forEach(function (promise) { promise.resolve(instance); }); delete pendings[handle]; } }
javascript
function resolveWhen() { var dfd = pendings[handle]; if (dfd) { dfd.forEach(function (promise) { promise.resolve(instance); }); delete pendings[handle]; } }
[ "function", "resolveWhen", "(", ")", "{", "var", "dfd", "=", "pendings", "[", "handle", "]", ";", "if", "(", "dfd", ")", "{", "dfd", ".", "forEach", "(", "function", "(", "promise", ")", "{", "promise", ".", "resolve", "(", "instance", ")", ";", "}", ")", ";", "delete", "pendings", "[", "handle", "]", ";", "}", "}" ]
Resolve any pending promises for this instance
[ "Resolve", "any", "pending", "promises", "for", "this", "instance" ]
84ac558674e73958be84312444c48d9f823f6684
https://github.com/angular/material/blob/84ac558674e73958be84312444c48d9f823f6684/src/core/services/registry/componentRegistry.js#L83-L91
4,897
angular/material
src/core/services/registry/componentRegistry.js
function(handle) { if (isValidID(handle)) { var deferred = $q.defer(); var instance = self.get(handle); if (instance) { deferred.resolve(instance); } else { if (pendings[handle] === undefined) { pendings[handle] = []; } pendings[handle].push(deferred); } return deferred.promise; } return $q.reject("Invalid `md-component-id` value."); }
javascript
function(handle) { if (isValidID(handle)) { var deferred = $q.defer(); var instance = self.get(handle); if (instance) { deferred.resolve(instance); } else { if (pendings[handle] === undefined) { pendings[handle] = []; } pendings[handle].push(deferred); } return deferred.promise; } return $q.reject("Invalid `md-component-id` value."); }
[ "function", "(", "handle", ")", "{", "if", "(", "isValidID", "(", "handle", ")", ")", "{", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "var", "instance", "=", "self", ".", "get", "(", "handle", ")", ";", "if", "(", "instance", ")", "{", "deferred", ".", "resolve", "(", "instance", ")", ";", "}", "else", "{", "if", "(", "pendings", "[", "handle", "]", "===", "undefined", ")", "{", "pendings", "[", "handle", "]", "=", "[", "]", ";", "}", "pendings", "[", "handle", "]", ".", "push", "(", "deferred", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}", "return", "$q", ".", "reject", "(", "\"Invalid `md-component-id` value.\"", ")", ";", "}" ]
Async accessor to registered component instance If not available then a promise is created to notify all listeners when the instance is registered.
[ "Async", "accessor", "to", "registered", "component", "instance", "If", "not", "available", "then", "a", "promise", "is", "created", "to", "notify", "all", "listeners", "when", "the", "instance", "is", "registered", "." ]
84ac558674e73958be84312444c48d9f823f6684
https://github.com/angular/material/blob/84ac558674e73958be84312444c48d9f823f6684/src/core/services/registry/componentRegistry.js#L99-L116
4,898
angular/material
src/components/chips/demoCustomInputs/script.js
querySearch
function querySearch (query) { var results = query ? self.vegetables.filter(createFilterFor(query)) : []; return results; }
javascript
function querySearch (query) { var results = query ? self.vegetables.filter(createFilterFor(query)) : []; return results; }
[ "function", "querySearch", "(", "query", ")", "{", "var", "results", "=", "query", "?", "self", ".", "vegetables", ".", "filter", "(", "createFilterFor", "(", "query", ")", ")", ":", "[", "]", ";", "return", "results", ";", "}" ]
Search for vegetables.
[ "Search", "for", "vegetables", "." ]
84ac558674e73958be84312444c48d9f823f6684
https://github.com/angular/material/blob/84ac558674e73958be84312444c48d9f823f6684/src/components/chips/demoCustomInputs/script.js#L38-L41
4,899
angular/material
src/components/icon/icon.spec.js
clean
function clean(style) { return style .replace(/ng-scope|ng-isolate-scope|md-default-theme/gi,'') .replace(/\s\s+/g,' ') .replace(/\s+"/g,'"') .trim(); }
javascript
function clean(style) { return style .replace(/ng-scope|ng-isolate-scope|md-default-theme/gi,'') .replace(/\s\s+/g,' ') .replace(/\s+"/g,'"') .trim(); }
[ "function", "clean", "(", "style", ")", "{", "return", "style", ".", "replace", "(", "/", "ng-scope|ng-isolate-scope|md-default-theme", "/", "gi", ",", "''", ")", ".", "replace", "(", "/", "\\s\\s+", "/", "g", ",", "' '", ")", ".", "replace", "(", "/", "\\s+\"", "/", "g", ",", "'\"'", ")", ".", "trim", "(", ")", ";", "}" ]
Utility to remove extra attributes to the specs are easy to compare
[ "Utility", "to", "remove", "extra", "attributes", "to", "the", "specs", "are", "easy", "to", "compare" ]
84ac558674e73958be84312444c48d9f823f6684
https://github.com/angular/material/blob/84ac558674e73958be84312444c48d9f823f6684/src/components/icon/icon.spec.js#L384-L390