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
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
12,700
WebReflection/document-register-element
examples/bower_components/polymer/polymer.js
function(prototype) { if (prototype.PolymerBase) { return prototype; } var extended = Object.create(prototype); // we need a unique copy of base api for each base prototype // therefore we 'extend' here instead of simply chaining api.publish(api.instance, extended); // TODO(sjmiles): sharing methods across prototype chains is // not supported by 'super' implementation which optimizes // by memoizing prototype relationships. // Probably we should have a version of 'extend' that is // share-aware: it could study the text of each function, // look for usage of 'super', and wrap those functions in // closures. // As of now, there is only one problematic method, so // we just patch it manually. // To avoid re-entrancy problems, the special super method // installed is called `mixinSuper` and the mixin method // must use this method instead of the default `super`. this.mixinMethod(extended, prototype, api.instance.mdv, 'bind'); // return buffed-up prototype return extended; }
javascript
function(prototype) { if (prototype.PolymerBase) { return prototype; } var extended = Object.create(prototype); // we need a unique copy of base api for each base prototype // therefore we 'extend' here instead of simply chaining api.publish(api.instance, extended); // TODO(sjmiles): sharing methods across prototype chains is // not supported by 'super' implementation which optimizes // by memoizing prototype relationships. // Probably we should have a version of 'extend' that is // share-aware: it could study the text of each function, // look for usage of 'super', and wrap those functions in // closures. // As of now, there is only one problematic method, so // we just patch it manually. // To avoid re-entrancy problems, the special super method // installed is called `mixinSuper` and the mixin method // must use this method instead of the default `super`. this.mixinMethod(extended, prototype, api.instance.mdv, 'bind'); // return buffed-up prototype return extended; }
[ "function", "(", "prototype", ")", "{", "if", "(", "prototype", ".", "PolymerBase", ")", "{", "return", "prototype", ";", "}", "var", "extended", "=", "Object", ".", "create", "(", "prototype", ")", ";", "// we need a unique copy of base api for each base prototype", "// therefore we 'extend' here instead of simply chaining", "api", ".", "publish", "(", "api", ".", "instance", ",", "extended", ")", ";", "// TODO(sjmiles): sharing methods across prototype chains is", "// not supported by 'super' implementation which optimizes", "// by memoizing prototype relationships.", "// Probably we should have a version of 'extend' that is ", "// share-aware: it could study the text of each function,", "// look for usage of 'super', and wrap those functions in", "// closures.", "// As of now, there is only one problematic method, so ", "// we just patch it manually.", "// To avoid re-entrancy problems, the special super method", "// installed is called `mixinSuper` and the mixin method", "// must use this method instead of the default `super`.", "this", ".", "mixinMethod", "(", "extended", ",", "prototype", ",", "api", ".", "instance", ".", "mdv", ",", "'bind'", ")", ";", "// return buffed-up prototype", "return", "extended", ";", "}" ]
install Polymer instance api into prototype chain, as needed
[ "install", "Polymer", "instance", "api", "into", "prototype", "chain", "as", "needed" ]
f50fb6d3a712745e9f317db241f4c3c523eecb25
https://github.com/WebReflection/document-register-element/blob/f50fb6d3a712745e9f317db241f4c3c523eecb25/examples/bower_components/polymer/polymer.js#L11245-L11268
12,701
WebReflection/document-register-element
examples/bower_components/polymer/polymer.js
function(name, extendee) { var info = { prototype: this.prototype } // native element must be specified in extends var typeExtension = this.findTypeExtension(extendee); if (typeExtension) { info.extends = typeExtension; } // register the prototype with HTMLElement for name lookup HTMLElement.register(name, this.prototype); // register the custom type this.ctor = document.registerElement(name, info); }
javascript
function(name, extendee) { var info = { prototype: this.prototype } // native element must be specified in extends var typeExtension = this.findTypeExtension(extendee); if (typeExtension) { info.extends = typeExtension; } // register the prototype with HTMLElement for name lookup HTMLElement.register(name, this.prototype); // register the custom type this.ctor = document.registerElement(name, info); }
[ "function", "(", "name", ",", "extendee", ")", "{", "var", "info", "=", "{", "prototype", ":", "this", ".", "prototype", "}", "// native element must be specified in extends", "var", "typeExtension", "=", "this", ".", "findTypeExtension", "(", "extendee", ")", ";", "if", "(", "typeExtension", ")", "{", "info", ".", "extends", "=", "typeExtension", ";", "}", "// register the prototype with HTMLElement for name lookup", "HTMLElement", ".", "register", "(", "name", ",", "this", ".", "prototype", ")", ";", "// register the custom type", "this", ".", "ctor", "=", "document", ".", "registerElement", "(", "name", ",", "info", ")", ";", "}" ]
register 'prototype' to custom element 'name', store constructor
[ "register", "prototype", "to", "custom", "element", "name", "store", "constructor" ]
f50fb6d3a712745e9f317db241f4c3c523eecb25
https://github.com/WebReflection/document-register-element/blob/f50fb6d3a712745e9f317db241f4c3c523eecb25/examples/bower_components/polymer/polymer.js#L11289-L11302
12,702
WebReflection/document-register-element
examples/bower_components/polymer/polymer.js
function(element, check, go) { var shouldAdd = element.__queue && !element.__queue.check; if (shouldAdd) { queueForElement(element).push(element); element.__queue.check = check; element.__queue.go = go; } return (this.indexOf(element) !== 0); }
javascript
function(element, check, go) { var shouldAdd = element.__queue && !element.__queue.check; if (shouldAdd) { queueForElement(element).push(element); element.__queue.check = check; element.__queue.go = go; } return (this.indexOf(element) !== 0); }
[ "function", "(", "element", ",", "check", ",", "go", ")", "{", "var", "shouldAdd", "=", "element", ".", "__queue", "&&", "!", "element", ".", "__queue", ".", "check", ";", "if", "(", "shouldAdd", ")", "{", "queueForElement", "(", "element", ")", ".", "push", "(", "element", ")", ";", "element", ".", "__queue", ".", "check", "=", "check", ";", "element", ".", "__queue", ".", "go", "=", "go", ";", "}", "return", "(", "this", ".", "indexOf", "(", "element", ")", "!==", "0", ")", ";", "}" ]
enqueue an element to the next spot in the queue.
[ "enqueue", "an", "element", "to", "the", "next", "spot", "in", "the", "queue", "." ]
f50fb6d3a712745e9f317db241f4c3c523eecb25
https://github.com/WebReflection/document-register-element/blob/f50fb6d3a712745e9f317db241f4c3c523eecb25/examples/bower_components/polymer/polymer.js#L11392-L11400
12,703
WebReflection/document-register-element
examples/bower_components/polymer/polymer.js
function(element) { var readied = this.remove(element); if (readied) { element.__queue.flushable = true; this.addToFlushQueue(readied); this.check(); } }
javascript
function(element) { var readied = this.remove(element); if (readied) { element.__queue.flushable = true; this.addToFlushQueue(readied); this.check(); } }
[ "function", "(", "element", ")", "{", "var", "readied", "=", "this", ".", "remove", "(", "element", ")", ";", "if", "(", "readied", ")", "{", "element", ".", "__queue", ".", "flushable", "=", "true", ";", "this", ".", "addToFlushQueue", "(", "readied", ")", ";", "this", ".", "check", "(", ")", ";", "}", "}" ]
tell the queue an element is ready to be registered
[ "tell", "the", "queue", "an", "element", "is", "ready", "to", "be", "registered" ]
f50fb6d3a712745e9f317db241f4c3c523eecb25
https://github.com/WebReflection/document-register-element/blob/f50fb6d3a712745e9f317db241f4c3c523eecb25/examples/bower_components/polymer/polymer.js#L11412-L11419
12,704
WebReflection/document-register-element
examples/bower_components/polymer/polymer.js
function() { var e$ = []; for (var i=0, l=elements.length, e; (i<l) && (e=elements[i]); i++) { if (e.__queue && !e.__queue.flushable) { e$.push(e); } } return e$; }
javascript
function() { var e$ = []; for (var i=0, l=elements.length, e; (i<l) && (e=elements[i]); i++) { if (e.__queue && !e.__queue.flushable) { e$.push(e); } } return e$; }
[ "function", "(", ")", "{", "var", "e$", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "elements", ".", "length", ",", "e", ";", "(", "i", "<", "l", ")", "&&", "(", "e", "=", "elements", "[", "i", "]", ")", ";", "i", "++", ")", "{", "if", "(", "e", ".", "__queue", "&&", "!", "e", ".", "__queue", ".", "flushable", ")", "{", "e$", ".", "push", "(", "e", ")", ";", "}", "}", "return", "e$", ";", "}" ]
Returns a list of elements that have had polymer-elements created but are not yet ready to register. The list is an array of element definitions.
[ "Returns", "a", "list", "of", "elements", "that", "have", "had", "polymer", "-", "elements", "created", "but", "are", "not", "yet", "ready", "to", "register", ".", "The", "list", "is", "an", "array", "of", "element", "definitions", "." ]
f50fb6d3a712745e9f317db241f4c3c523eecb25
https://github.com/WebReflection/document-register-element/blob/f50fb6d3a712745e9f317db241f4c3c523eecb25/examples/bower_components/polymer/polymer.js#L11517-L11526
12,705
WebReflection/document-register-element
examples/bower_components/polymer/polymer.js
forceReady
function forceReady(timeout) { if (timeout === undefined) { queue.ready(); return; } var handle = setTimeout(function() { queue.ready(); }, timeout); Polymer.whenReady(function() { clearTimeout(handle); }); }
javascript
function forceReady(timeout) { if (timeout === undefined) { queue.ready(); return; } var handle = setTimeout(function() { queue.ready(); }, timeout); Polymer.whenReady(function() { clearTimeout(handle); }); }
[ "function", "forceReady", "(", "timeout", ")", "{", "if", "(", "timeout", "===", "undefined", ")", "{", "queue", ".", "ready", "(", ")", ";", "return", ";", "}", "var", "handle", "=", "setTimeout", "(", "function", "(", ")", "{", "queue", ".", "ready", "(", ")", ";", "}", ",", "timeout", ")", ";", "Polymer", ".", "whenReady", "(", "function", "(", ")", "{", "clearTimeout", "(", "handle", ")", ";", "}", ")", ";", "}" ]
Forces polymer to register any pending elements. Can be used to abort waiting for elements that are partially defined. @param timeout {Integer} Optional timeout in milliseconds
[ "Forces", "polymer", "to", "register", "any", "pending", "elements", ".", "Can", "be", "used", "to", "abort", "waiting", "for", "elements", "that", "are", "partially", "defined", "." ]
f50fb6d3a712745e9f317db241f4c3c523eecb25
https://github.com/WebReflection/document-register-element/blob/f50fb6d3a712745e9f317db241f4c3c523eecb25/examples/bower_components/polymer/polymer.js#L11562-L11573
12,706
WebReflection/document-register-element
examples/bower_components/polymer/polymer.js
_import
function _import(urls, callback) { if (urls && urls.length) { var frag = document.createDocumentFragment(); for (var i=0, l=urls.length, url, link; (i<l) && (url=urls[i]); i++) { link = document.createElement('link'); link.rel = 'import'; link.href = url; frag.appendChild(link); } importElements(frag, callback); } else if (callback) { callback(); } }
javascript
function _import(urls, callback) { if (urls && urls.length) { var frag = document.createDocumentFragment(); for (var i=0, l=urls.length, url, link; (i<l) && (url=urls[i]); i++) { link = document.createElement('link'); link.rel = 'import'; link.href = url; frag.appendChild(link); } importElements(frag, callback); } else if (callback) { callback(); } }
[ "function", "_import", "(", "urls", ",", "callback", ")", "{", "if", "(", "urls", "&&", "urls", ".", "length", ")", "{", "var", "frag", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "urls", ".", "length", ",", "url", ",", "link", ";", "(", "i", "<", "l", ")", "&&", "(", "url", "=", "urls", "[", "i", "]", ")", ";", "i", "++", ")", "{", "link", "=", "document", ".", "createElement", "(", "'link'", ")", ";", "link", ".", "rel", "=", "'import'", ";", "link", ".", "href", "=", "url", ";", "frag", ".", "appendChild", "(", "link", ")", ";", "}", "importElements", "(", "frag", ",", "callback", ")", ";", "}", "else", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}" ]
Loads an HTMLImport for each url specified in the `urls` array. Notifies when all the imports have loaded by calling the `callback` function argument. This method can be used to lazily load imports. For example, Polymer.import(['my-import1.html', 'my-import2.html'], function() { console.log('imports lazily loaded'); }); @method import @param {Array} urls Array of urls to load as HTMLImports. @param {Function} callback Callback called when all imports have loaded.
[ "Loads", "an", "HTMLImport", "for", "each", "url", "specified", "in", "the", "urls", "array", ".", "Notifies", "when", "all", "the", "imports", "have", "loaded", "by", "calling", "the", "callback", "function", "argument", ".", "This", "method", "can", "be", "used", "to", "lazily", "load", "imports", ".", "For", "example" ]
f50fb6d3a712745e9f317db241f4c3c523eecb25
https://github.com/WebReflection/document-register-element/blob/f50fb6d3a712745e9f317db241f4c3c523eecb25/examples/bower_components/polymer/polymer.js#L11763-L11776
12,707
WebReflection/document-register-element
examples/js/sor-table.js
slice
function slice(what, start) { for (var j = 0, i = start || 0, arr = []; i < what.length; i++) { arr[j++] = what[i]; } return arr; }
javascript
function slice(what, start) { for (var j = 0, i = start || 0, arr = []; i < what.length; i++) { arr[j++] = what[i]; } return arr; }
[ "function", "slice", "(", "what", ",", "start", ")", "{", "for", "(", "var", "j", "=", "0", ",", "i", "=", "start", "||", "0", ",", "arr", "=", "[", "]", ";", "i", "<", "what", ".", "length", ";", "i", "++", ")", "{", "arr", "[", "j", "++", "]", "=", "what", "[", "i", "]", ";", "}", "return", "arr", ";", "}" ]
es5 shim is broken
[ "es5", "shim", "is", "broken" ]
f50fb6d3a712745e9f317db241f4c3c523eecb25
https://github.com/WebReflection/document-register-element/blob/f50fb6d3a712745e9f317db241f4c3c523eecb25/examples/js/sor-table.js#L12-L17
12,708
WebReflection/document-register-element
examples/js/Object.prototype.watch.js
function (newValue) { // and no inheritance is involved if (this === self) { // notify the method but ... var value = oldValue; updateValue(newValue); // ... do not update the get value oldValue = value; } else { // with inheritance, simply set the property // as if it was a regular assignment operation setValue(this, prop, newValue); } }
javascript
function (newValue) { // and no inheritance is involved if (this === self) { // notify the method but ... var value = oldValue; updateValue(newValue); // ... do not update the get value oldValue = value; } else { // with inheritance, simply set the property // as if it was a regular assignment operation setValue(this, prop, newValue); } }
[ "function", "(", "newValue", ")", "{", "// and no inheritance is involved", "if", "(", "this", "===", "self", ")", "{", "// notify the method but ...", "var", "value", "=", "oldValue", ";", "updateValue", "(", "newValue", ")", ";", "// ... do not update the get value", "oldValue", "=", "value", ";", "}", "else", "{", "// with inheritance, simply set the property", "// as if it was a regular assignment operation", "setValue", "(", "this", ",", "prop", ",", "newValue", ")", ";", "}", "}" ]
if not writable ...
[ "if", "not", "writable", "..." ]
f50fb6d3a712745e9f317db241f4c3c523eecb25
https://github.com/WebReflection/document-register-element/blob/f50fb6d3a712745e9f317db241f4c3c523eecb25/examples/js/Object.prototype.watch.js#L110-L123
12,709
emberjs/ember-inspector
ember_debug/adapters/web-extension.js
deepClone
function deepClone(item) { let clone = item; if (isArray(item)) { clone = new Array(item.length); item.forEach((child, key) => { clone[key] = deepClone(child); }); } else if (item && typeOf(item) === 'object') { clone = {}; keys(item).forEach(key => { clone[key] = deepClone(item[key]); }); } return clone; }
javascript
function deepClone(item) { let clone = item; if (isArray(item)) { clone = new Array(item.length); item.forEach((child, key) => { clone[key] = deepClone(child); }); } else if (item && typeOf(item) === 'object') { clone = {}; keys(item).forEach(key => { clone[key] = deepClone(item[key]); }); } return clone; }
[ "function", "deepClone", "(", "item", ")", "{", "let", "clone", "=", "item", ";", "if", "(", "isArray", "(", "item", ")", ")", "{", "clone", "=", "new", "Array", "(", "item", ".", "length", ")", ";", "item", ".", "forEach", "(", "(", "child", ",", "key", ")", "=>", "{", "clone", "[", "key", "]", "=", "deepClone", "(", "child", ")", ";", "}", ")", ";", "}", "else", "if", "(", "item", "&&", "typeOf", "(", "item", ")", "===", "'object'", ")", "{", "clone", "=", "{", "}", ";", "keys", "(", "item", ")", ".", "forEach", "(", "key", "=>", "{", "clone", "[", "key", "]", "=", "deepClone", "(", "item", "[", "key", "]", ")", ";", "}", ")", ";", "}", "return", "clone", ";", "}" ]
Recursively clones all arrays. Needed because Chrome refuses to clone Ember Arrays when extend prototypes is disabled. If the item passed is an array, a clone of the array is returned. If the item is an object or an array, or array properties/items are cloned. @param {Mixed} item The item to clone @return {Mixed}
[ "Recursively", "clones", "all", "arrays", ".", "Needed", "because", "Chrome", "refuses", "to", "clone", "Ember", "Arrays", "when", "extend", "prototypes", "is", "disabled", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/ember_debug/adapters/web-extension.js#L78-L92
12,710
emberjs/ember-inspector
skeletons/web-extension/options.js
loadOptions
function loadOptions() { chrome.storage.sync.get('options', function(data) { var options = data.options; document.querySelector('[data-settings=tomster]').checked = options && options.showTomster; }); }
javascript
function loadOptions() { chrome.storage.sync.get('options', function(data) { var options = data.options; document.querySelector('[data-settings=tomster]').checked = options && options.showTomster; }); }
[ "function", "loadOptions", "(", ")", "{", "chrome", ".", "storage", ".", "sync", ".", "get", "(", "'options'", ",", "function", "(", "data", ")", "{", "var", "options", "=", "data", ".", "options", ";", "document", ".", "querySelector", "(", "'[data-settings=tomster]'", ")", ".", "checked", "=", "options", "&&", "options", ".", "showTomster", ";", "}", ")", ";", "}" ]
Load the options from storage.
[ "Load", "the", "options", "from", "storage", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/skeletons/web-extension/options.js#L17-L23
12,711
emberjs/ember-inspector
skeletons/web-extension/options.js
storeOptions
function storeOptions() { var showTomster = this.checked; chrome.storage.sync.set({ options: { showTomster: showTomster } }, function optionsSaved() { console.log("saved!"); }); }
javascript
function storeOptions() { var showTomster = this.checked; chrome.storage.sync.set({ options: { showTomster: showTomster } }, function optionsSaved() { console.log("saved!"); }); }
[ "function", "storeOptions", "(", ")", "{", "var", "showTomster", "=", "this", ".", "checked", ";", "chrome", ".", "storage", ".", "sync", ".", "set", "(", "{", "options", ":", "{", "showTomster", ":", "showTomster", "}", "}", ",", "function", "optionsSaved", "(", ")", "{", "console", ".", "log", "(", "\"saved!\"", ")", ";", "}", ")", ";", "}" ]
Save the updated options to storage.
[ "Save", "the", "updated", "options", "to", "storage", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/skeletons/web-extension/options.js#L28-L36
12,712
emberjs/ember-inspector
ember_debug/object-inspector.js
customizeProperties
function customizeProperties(mixinDetails, propertyInfo) { let newMixinDetails = []; let neededProperties = {}; let groups = propertyInfo.groups || []; let skipProperties = propertyInfo.skipProperties || []; let skipMixins = propertyInfo.skipMixins || []; if (groups.length) { mixinDetails[0].expand = false; } groups.forEach(group => { group.properties.forEach(prop => { neededProperties[prop] = true; }); }); mixinDetails.forEach(mixin => { let newProperties = []; mixin.properties.forEach(item => { // If 2.10.0 or 2.10.x but < 2.11 if (compareVersion(VERSION, '2.10.0') === 0 || (compareVersion(VERSION, '2.10.0') === 1 && compareVersion(VERSION, '2.11.0') === -1)) { skipProperties = twoTenfilterHack(item.name, skipProperties); } if (skipProperties.indexOf(item.name) !== -1) { return true; } if (!item.overridden && neededProperties.hasOwnProperty(item.name) && neededProperties[item.name]) { neededProperties[item.name] = item; } else { newProperties.push(item); } }); mixin.properties = newProperties; if (skipMixins.indexOf(mixin.name) === -1) { newMixinDetails.push(mixin); } }); groups.slice().reverse().forEach(group => { let newMixin = { name: group.name, expand: group.expand, properties: [] }; group.properties.forEach(function(prop) { // make sure it's not `true` which means property wasn't found if (neededProperties[prop] !== true) { newMixin.properties.push(neededProperties[prop]); } }); newMixinDetails.unshift(newMixin); }); return newMixinDetails; }
javascript
function customizeProperties(mixinDetails, propertyInfo) { let newMixinDetails = []; let neededProperties = {}; let groups = propertyInfo.groups || []; let skipProperties = propertyInfo.skipProperties || []; let skipMixins = propertyInfo.skipMixins || []; if (groups.length) { mixinDetails[0].expand = false; } groups.forEach(group => { group.properties.forEach(prop => { neededProperties[prop] = true; }); }); mixinDetails.forEach(mixin => { let newProperties = []; mixin.properties.forEach(item => { // If 2.10.0 or 2.10.x but < 2.11 if (compareVersion(VERSION, '2.10.0') === 0 || (compareVersion(VERSION, '2.10.0') === 1 && compareVersion(VERSION, '2.11.0') === -1)) { skipProperties = twoTenfilterHack(item.name, skipProperties); } if (skipProperties.indexOf(item.name) !== -1) { return true; } if (!item.overridden && neededProperties.hasOwnProperty(item.name) && neededProperties[item.name]) { neededProperties[item.name] = item; } else { newProperties.push(item); } }); mixin.properties = newProperties; if (skipMixins.indexOf(mixin.name) === -1) { newMixinDetails.push(mixin); } }); groups.slice().reverse().forEach(group => { let newMixin = { name: group.name, expand: group.expand, properties: [] }; group.properties.forEach(function(prop) { // make sure it's not `true` which means property wasn't found if (neededProperties[prop] !== true) { newMixin.properties.push(neededProperties[prop]); } }); newMixinDetails.unshift(newMixin); }); return newMixinDetails; }
[ "function", "customizeProperties", "(", "mixinDetails", ",", "propertyInfo", ")", "{", "let", "newMixinDetails", "=", "[", "]", ";", "let", "neededProperties", "=", "{", "}", ";", "let", "groups", "=", "propertyInfo", ".", "groups", "||", "[", "]", ";", "let", "skipProperties", "=", "propertyInfo", ".", "skipProperties", "||", "[", "]", ";", "let", "skipMixins", "=", "propertyInfo", ".", "skipMixins", "||", "[", "]", ";", "if", "(", "groups", ".", "length", ")", "{", "mixinDetails", "[", "0", "]", ".", "expand", "=", "false", ";", "}", "groups", ".", "forEach", "(", "group", "=>", "{", "group", ".", "properties", ".", "forEach", "(", "prop", "=>", "{", "neededProperties", "[", "prop", "]", "=", "true", ";", "}", ")", ";", "}", ")", ";", "mixinDetails", ".", "forEach", "(", "mixin", "=>", "{", "let", "newProperties", "=", "[", "]", ";", "mixin", ".", "properties", ".", "forEach", "(", "item", "=>", "{", "// If 2.10.0 or 2.10.x but < 2.11", "if", "(", "compareVersion", "(", "VERSION", ",", "'2.10.0'", ")", "===", "0", "||", "(", "compareVersion", "(", "VERSION", ",", "'2.10.0'", ")", "===", "1", "&&", "compareVersion", "(", "VERSION", ",", "'2.11.0'", ")", "===", "-", "1", ")", ")", "{", "skipProperties", "=", "twoTenfilterHack", "(", "item", ".", "name", ",", "skipProperties", ")", ";", "}", "if", "(", "skipProperties", ".", "indexOf", "(", "item", ".", "name", ")", "!==", "-", "1", ")", "{", "return", "true", ";", "}", "if", "(", "!", "item", ".", "overridden", "&&", "neededProperties", ".", "hasOwnProperty", "(", "item", ".", "name", ")", "&&", "neededProperties", "[", "item", ".", "name", "]", ")", "{", "neededProperties", "[", "item", ".", "name", "]", "=", "item", ";", "}", "else", "{", "newProperties", ".", "push", "(", "item", ")", ";", "}", "}", ")", ";", "mixin", ".", "properties", "=", "newProperties", ";", "if", "(", "skipMixins", ".", "indexOf", "(", "mixin", ".", "name", ")", "===", "-", "1", ")", "{", "newMixinDetails", ".", "push", "(", "mixin", ")", ";", "}", "}", ")", ";", "groups", ".", "slice", "(", ")", ".", "reverse", "(", ")", ".", "forEach", "(", "group", "=>", "{", "let", "newMixin", "=", "{", "name", ":", "group", ".", "name", ",", "expand", ":", "group", ".", "expand", ",", "properties", ":", "[", "]", "}", ";", "group", ".", "properties", ".", "forEach", "(", "function", "(", "prop", ")", "{", "// make sure it's not `true` which means property wasn't found", "if", "(", "neededProperties", "[", "prop", "]", "!==", "true", ")", "{", "newMixin", ".", "properties", ".", "push", "(", "neededProperties", "[", "prop", "]", ")", ";", "}", "}", ")", ";", "newMixinDetails", ".", "unshift", "(", "newMixin", ")", ";", "}", ")", ";", "return", "newMixinDetails", ";", "}" ]
Customizes an object's properties based on the property `propertyInfo` of the object's `_debugInfo` method. Possible options: - `groups` An array of groups that contains the properties for each group For example: ```javascript groups: [ { name: 'Attributes', properties: ['firstName', 'lastName'] }, { name: 'Belongs To', properties: ['country'] } ] ``` - `includeOtherProperties` Boolean, - `true` to include other non-listed properties, - `false` to only include given properties - `skipProperties` Array containing list of properties *not* to include - `skipMixins` Array containing list of mixins *not* to include - `expensiveProperties` An array of computed properties that are too expensive. Adding a property to this array makes sure the CP is not calculated automatically. Example: ```javascript { propertyInfo: { includeOtherProperties: true, skipProperties: ['toString', 'send', 'withTransaction'], skipMixins: [ 'Ember.Evented'], calculate: ['firstName', 'lastName'], groups: [ { name: 'Attributes', properties: [ 'id', 'firstName', 'lastName' ], expand: true // open by default }, { name: 'Belongs To', properties: [ 'maritalStatus', 'avatar' ], expand: true }, { name: 'Has Many', properties: [ 'phoneNumbers' ], expand: true }, { name: 'Flags', properties: ['isLoaded', 'isLoading', 'isNew', 'isDirty'] } ] } } ```
[ "Customizes", "an", "object", "s", "properties", "based", "on", "the", "property", "propertyInfo", "of", "the", "object", "s", "_debugInfo", "method", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/ember_debug/object-inspector.js#L678-L731
12,713
emberjs/ember-inspector
skeletons/web-extension/background-script.js
generateVersionsTooltip
function generateVersionsTooltip(versions) { return versions.map(function(lib) { return lib.name + " " + lib.version; }).join("\n"); }
javascript
function generateVersionsTooltip(versions) { return versions.map(function(lib) { return lib.name + " " + lib.version; }).join("\n"); }
[ "function", "generateVersionsTooltip", "(", "versions", ")", "{", "return", "versions", ".", "map", "(", "function", "(", "lib", ")", "{", "return", "lib", ".", "name", "+", "\" \"", "+", "lib", ".", "version", ";", "}", ")", ".", "join", "(", "\"\\n\"", ")", ";", "}" ]
Creates the tooltip string to show the version of libraries used in the ClientApp @param {Array} versions - array of library objects @return {String} - string of library names and versions
[ "Creates", "the", "tooltip", "string", "to", "show", "the", "version", "of", "libraries", "used", "in", "the", "ClientApp" ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/skeletons/web-extension/background-script.js#L28-L32
12,714
emberjs/ember-inspector
skeletons/web-extension/background-script.js
setActionTitle
function setActionTitle(tabId) { chrome.pageAction.setTitle({ tabId: tabId, title: generateVersionsTooltip(activeTabs[tabId]) }); }
javascript
function setActionTitle(tabId) { chrome.pageAction.setTitle({ tabId: tabId, title: generateVersionsTooltip(activeTabs[tabId]) }); }
[ "function", "setActionTitle", "(", "tabId", ")", "{", "chrome", ".", "pageAction", ".", "setTitle", "(", "{", "tabId", ":", "tabId", ",", "title", ":", "generateVersionsTooltip", "(", "activeTabs", "[", "tabId", "]", ")", "}", ")", ";", "}" ]
Creates the title for the pageAction for the current ClientApp @param {Number} tabId - the current tab
[ "Creates", "the", "title", "for", "the", "pageAction", "for", "the", "current", "ClientApp" ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/skeletons/web-extension/background-script.js#L38-L43
12,715
emberjs/ember-inspector
ember_debug/vendor/source-map.js
relative
function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); }
javascript
function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); }
[ "function", "relative", "(", "aRoot", ",", "aPath", ")", "{", "if", "(", "aRoot", "===", "\"\"", ")", "{", "aRoot", "=", "\".\"", ";", "}", "aRoot", "=", "aRoot", ".", "replace", "(", "/", "\\/$", "/", ",", "''", ")", ";", "// It is possible for the path to be above the root. In this case, simply", "// checking whether the root is a prefix of the path won't work. Instead, we", "// need to remove components from the root one by one, until either we find", "// a prefix that fits, or we run out of components to remove.", "var", "level", "=", "0", ";", "while", "(", "aPath", ".", "indexOf", "(", "aRoot", "+", "'/'", ")", "!==", "0", ")", "{", "var", "index", "=", "aRoot", ".", "lastIndexOf", "(", "\"/\"", ")", ";", "if", "(", "index", "<", "0", ")", "{", "return", "aPath", ";", "}", "// If the only part of the root that is left is the scheme (i.e. http://,", "// file:///, etc.), one or more slashes (/), or simply nothing at all, we", "// have exhausted all components, so the path is not relative to the root.", "aRoot", "=", "aRoot", ".", "slice", "(", "0", ",", "index", ")", ";", "if", "(", "aRoot", ".", "match", "(", "/", "^([^\\/]+:\\/)?\\/*$", "/", ")", ")", "{", "return", "aPath", ";", "}", "++", "level", ";", "}", "// Make sure we add a \"../\" for each component we removed from the root.", "return", "Array", "(", "level", "+", "1", ")", ".", "join", "(", "\"../\"", ")", "+", "aPath", ".", "substr", "(", "aRoot", ".", "length", "+", "1", ")", ";", "}" ]
Make a path relative to a URL or another path. @param aRoot The root path or URL. @param aPath The path or URL to be made relative to aRoot.
[ "Make", "a", "path", "relative", "to", "a", "URL", "or", "another", "path", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/ember_debug/vendor/source-map.js#L958-L989
12,716
emberjs/ember-inspector
ember_debug/vendor/source-map.js
recursiveSearch
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } }
javascript
function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } }
[ "function", "recursiveSearch", "(", "aLow", ",", "aHigh", ",", "aNeedle", ",", "aHaystack", ",", "aCompare", ",", "aBias", ")", "{", "// This function terminates when one of the following is true:", "//", "// 1. We find the exact element we are looking for.", "//", "// 2. We did not find the exact element, but we can return the index of", "// the next-closest element.", "//", "// 3. We did not find the exact element, and there is no next-closest", "// element than the one we are searching for, so we return -1.", "var", "mid", "=", "Math", ".", "floor", "(", "(", "aHigh", "-", "aLow", ")", "/", "2", ")", "+", "aLow", ";", "var", "cmp", "=", "aCompare", "(", "aNeedle", ",", "aHaystack", "[", "mid", "]", ",", "true", ")", ";", "if", "(", "cmp", "===", "0", ")", "{", "// Found the element we are looking for.", "return", "mid", ";", "}", "else", "if", "(", "cmp", ">", "0", ")", "{", "// Our needle is greater than aHaystack[mid].", "if", "(", "aHigh", "-", "mid", ">", "1", ")", "{", "// The element is in the upper half.", "return", "recursiveSearch", "(", "mid", ",", "aHigh", ",", "aNeedle", ",", "aHaystack", ",", "aCompare", ",", "aBias", ")", ";", "}", "// The exact needle element was not found in this haystack. Determine if", "// we are in termination case (3) or (2) and return the appropriate thing.", "if", "(", "aBias", "==", "exports", ".", "LEAST_UPPER_BOUND", ")", "{", "return", "aHigh", "<", "aHaystack", ".", "length", "?", "aHigh", ":", "-", "1", ";", "}", "else", "{", "return", "mid", ";", "}", "}", "else", "{", "// Our needle is less than aHaystack[mid].", "if", "(", "mid", "-", "aLow", ">", "1", ")", "{", "// The element is in the lower half.", "return", "recursiveSearch", "(", "aLow", ",", "mid", ",", "aNeedle", ",", "aHaystack", ",", "aCompare", ",", "aBias", ")", ";", "}", "// we are in termination case (3) or (2) and return the appropriate thing.", "if", "(", "aBias", "==", "exports", ".", "LEAST_UPPER_BOUND", ")", "{", "return", "mid", ";", "}", "else", "{", "return", "aLow", "<", "0", "?", "-", "1", ":", "aLow", ";", "}", "}", "}" ]
Recursive implementation of binary search. @param aLow Indices here and lower do not contain the needle. @param aHigh Indices here and higher do not contain the needle. @param aNeedle The element being searched for. @param aHaystack The non-empty array being searched. @param aCompare Function which takes two elements and returns -1, 0, or 1. @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found.
[ "Recursive", "implementation", "of", "binary", "search", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/ember_debug/vendor/source-map.js#L2430-L2475
12,717
emberjs/ember-inspector
ember_debug/vendor/source-map.js
randomIntInRange
function randomIntInRange(low, high) { return Math.round(low + (Math.random() * (high - low))); }
javascript
function randomIntInRange(low, high) { return Math.round(low + (Math.random() * (high - low))); }
[ "function", "randomIntInRange", "(", "low", ",", "high", ")", "{", "return", "Math", ".", "round", "(", "low", "+", "(", "Math", ".", "random", "(", ")", "*", "(", "high", "-", "low", ")", ")", ")", ";", "}" ]
Returns a random integer within the range `low .. high` inclusive. @param {Number} low The lower bound on the range. @param {Number} high The upper bound on the range.
[ "Returns", "a", "random", "integer", "within", "the", "range", "low", "..", "high", "inclusive", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/ember_debug/vendor/source-map.js#L2562-L2564
12,718
emberjs/ember-inspector
ember_debug/general-debug.js
findMetaTag
function findMetaTag(attribute, regExp = /.*/) { let metas = document.querySelectorAll(`meta[${attribute}]`); for (let i = 0; i < metas.length; i++) { let match = metas[i].getAttribute(attribute).match(regExp); if (match) { return metas[i]; } } return null; }
javascript
function findMetaTag(attribute, regExp = /.*/) { let metas = document.querySelectorAll(`meta[${attribute}]`); for (let i = 0; i < metas.length; i++) { let match = metas[i].getAttribute(attribute).match(regExp); if (match) { return metas[i]; } } return null; }
[ "function", "findMetaTag", "(", "attribute", ",", "regExp", "=", "/", ".*", "/", ")", "{", "let", "metas", "=", "document", ".", "querySelectorAll", "(", "`", "${", "attribute", "}", "`", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "metas", ".", "length", ";", "i", "++", ")", "{", "let", "match", "=", "metas", "[", "i", "]", ".", "getAttribute", "(", "attribute", ")", ".", "match", "(", "regExp", ")", ";", "if", "(", "match", ")", "{", "return", "metas", "[", "i", "]", ";", "}", "}", "return", "null", ";", "}" ]
Finds a meta tag by searching through a certain meta attribute. @param {String} attribute @param {RegExp} regExp @return {Element}
[ "Finds", "a", "meta", "tag", "by", "searching", "through", "a", "certain", "meta", "attribute", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/ember_debug/general-debug.js#L115-L124
12,719
emberjs/ember-inspector
skeletons/web-extension/content-script.js
listenToEmberDebugPort
function listenToEmberDebugPort(emberDebugPort) { // listen for messages from EmberDebug, and pass them on to the background-script emberDebugPort.addEventListener('message', function(event) { chrome.runtime.sendMessage(event.data); }); // listen for messages from the EmberInspector, and pass them on to EmberDebug chrome.runtime.onMessage.addListener(function(message) { if (message.from === 'devtools') { // forward message to EmberDebug emberDebugPort.postMessage(message); } }); emberDebugPort.start(); }
javascript
function listenToEmberDebugPort(emberDebugPort) { // listen for messages from EmberDebug, and pass them on to the background-script emberDebugPort.addEventListener('message', function(event) { chrome.runtime.sendMessage(event.data); }); // listen for messages from the EmberInspector, and pass them on to EmberDebug chrome.runtime.onMessage.addListener(function(message) { if (message.from === 'devtools') { // forward message to EmberDebug emberDebugPort.postMessage(message); } }); emberDebugPort.start(); }
[ "function", "listenToEmberDebugPort", "(", "emberDebugPort", ")", "{", "// listen for messages from EmberDebug, and pass them on to the background-script", "emberDebugPort", ".", "addEventListener", "(", "'message'", ",", "function", "(", "event", ")", "{", "chrome", ".", "runtime", ".", "sendMessage", "(", "event", ".", "data", ")", ";", "}", ")", ";", "// listen for messages from the EmberInspector, and pass them on to EmberDebug", "chrome", ".", "runtime", ".", "onMessage", ".", "addListener", "(", "function", "(", "message", ")", "{", "if", "(", "message", ".", "from", "===", "'devtools'", ")", "{", "// forward message to EmberDebug", "emberDebugPort", ".", "postMessage", "(", "message", ")", ";", "}", "}", ")", ";", "emberDebugPort", ".", "start", "(", ")", ";", "}" ]
Listen for messages from EmberDebug. @param {Object} emberDebugPort
[ "Listen", "for", "messages", "from", "EmberDebug", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/skeletons/web-extension/content-script.js#L40-L55
12,720
emberjs/ember-inspector
ember_debug/vendor/startup-wrapper.js
onApplicationStart
function onApplicationStart(callback) { if (typeof Ember === 'undefined') { return; } const adapterInstance = requireModule('ember-debug/adapters/' + currentAdapter)['default'].create(); adapterInstance.onMessageReceived(function(message) { if (message.type === 'app-picker-loaded') { sendApps(adapterInstance, getApplications()); } if (message.type === 'app-selected') { const appInstance = getApplications().find(app => Ember.guidFor(app) === message.applicationId); if (appInstance && appInstance.__deprecatedInstance__) { bootEmberInspector(appInstance.__deprecatedInstance__); } } }); var apps = getApplications(); sendApps(adapterInstance, apps); var app; for (var i = 0, l = apps.length; i < l; i++) { app = apps[i]; // We check for the existance of an application instance because // in Ember > 3 tests don't destroy the app when they're done but the app has no booted instances. if (app._readinessDeferrals === 0) { let instance = app.__deprecatedInstance__ || (app._applicationInstances && app._applicationInstances[0]); if (instance) { // App started setupInstanceInitializer(app, callback); callback(instance); break; } } } Ember.Application.initializer({ name: 'ember-inspector-booted', initialize: function(app) { setupInstanceInitializer(app, callback); } }); }
javascript
function onApplicationStart(callback) { if (typeof Ember === 'undefined') { return; } const adapterInstance = requireModule('ember-debug/adapters/' + currentAdapter)['default'].create(); adapterInstance.onMessageReceived(function(message) { if (message.type === 'app-picker-loaded') { sendApps(adapterInstance, getApplications()); } if (message.type === 'app-selected') { const appInstance = getApplications().find(app => Ember.guidFor(app) === message.applicationId); if (appInstance && appInstance.__deprecatedInstance__) { bootEmberInspector(appInstance.__deprecatedInstance__); } } }); var apps = getApplications(); sendApps(adapterInstance, apps); var app; for (var i = 0, l = apps.length; i < l; i++) { app = apps[i]; // We check for the existance of an application instance because // in Ember > 3 tests don't destroy the app when they're done but the app has no booted instances. if (app._readinessDeferrals === 0) { let instance = app.__deprecatedInstance__ || (app._applicationInstances && app._applicationInstances[0]); if (instance) { // App started setupInstanceInitializer(app, callback); callback(instance); break; } } } Ember.Application.initializer({ name: 'ember-inspector-booted', initialize: function(app) { setupInstanceInitializer(app, callback); } }); }
[ "function", "onApplicationStart", "(", "callback", ")", "{", "if", "(", "typeof", "Ember", "===", "'undefined'", ")", "{", "return", ";", "}", "const", "adapterInstance", "=", "requireModule", "(", "'ember-debug/adapters/'", "+", "currentAdapter", ")", "[", "'default'", "]", ".", "create", "(", ")", ";", "adapterInstance", ".", "onMessageReceived", "(", "function", "(", "message", ")", "{", "if", "(", "message", ".", "type", "===", "'app-picker-loaded'", ")", "{", "sendApps", "(", "adapterInstance", ",", "getApplications", "(", ")", ")", ";", "}", "if", "(", "message", ".", "type", "===", "'app-selected'", ")", "{", "const", "appInstance", "=", "getApplications", "(", ")", ".", "find", "(", "app", "=>", "Ember", ".", "guidFor", "(", "app", ")", "===", "message", ".", "applicationId", ")", ";", "if", "(", "appInstance", "&&", "appInstance", ".", "__deprecatedInstance__", ")", "{", "bootEmberInspector", "(", "appInstance", ".", "__deprecatedInstance__", ")", ";", "}", "}", "}", ")", ";", "var", "apps", "=", "getApplications", "(", ")", ";", "sendApps", "(", "adapterInstance", ",", "apps", ")", ";", "var", "app", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "apps", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "app", "=", "apps", "[", "i", "]", ";", "// We check for the existance of an application instance because", "// in Ember > 3 tests don't destroy the app when they're done but the app has no booted instances.", "if", "(", "app", ".", "_readinessDeferrals", "===", "0", ")", "{", "let", "instance", "=", "app", ".", "__deprecatedInstance__", "||", "(", "app", ".", "_applicationInstances", "&&", "app", ".", "_applicationInstances", "[", "0", "]", ")", ";", "if", "(", "instance", ")", "{", "// App started", "setupInstanceInitializer", "(", "app", ",", "callback", ")", ";", "callback", "(", "instance", ")", ";", "break", ";", "}", "}", "}", "Ember", ".", "Application", ".", "initializer", "(", "{", "name", ":", "'ember-inspector-booted'", ",", "initialize", ":", "function", "(", "app", ")", "{", "setupInstanceInitializer", "(", "app", ",", "callback", ")", ";", "}", "}", ")", ";", "}" ]
There's probably a better way to determine when the application starts but this definitely works
[ "There", "s", "probably", "a", "better", "way", "to", "determine", "when", "the", "application", "starts", "but", "this", "definitely", "works" ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/ember_debug/vendor/startup-wrapper.js#L131-L177
12,721
emberjs/ember-inspector
ember_debug/vendor/startup-wrapper.js
getApplications
function getApplications() { var namespaces = Ember.A(Ember.Namespace.NAMESPACES); var apps = namespaces.filter(function(namespace) { return namespace instanceof Ember.Application; }); return apps.map(function(app) { // Add applicationId and applicationName to the app var applicationId = Ember.guidFor(app); var applicationName = app.name || app.modulePrefix || `(unknown app - ${applicationId})`; Object.assign(app, { applicationId, applicationName }); return app; }); }
javascript
function getApplications() { var namespaces = Ember.A(Ember.Namespace.NAMESPACES); var apps = namespaces.filter(function(namespace) { return namespace instanceof Ember.Application; }); return apps.map(function(app) { // Add applicationId and applicationName to the app var applicationId = Ember.guidFor(app); var applicationName = app.name || app.modulePrefix || `(unknown app - ${applicationId})`; Object.assign(app, { applicationId, applicationName }); return app; }); }
[ "function", "getApplications", "(", ")", "{", "var", "namespaces", "=", "Ember", ".", "A", "(", "Ember", ".", "Namespace", ".", "NAMESPACES", ")", ";", "var", "apps", "=", "namespaces", ".", "filter", "(", "function", "(", "namespace", ")", "{", "return", "namespace", "instanceof", "Ember", ".", "Application", ";", "}", ")", ";", "return", "apps", ".", "map", "(", "function", "(", "app", ")", "{", "// Add applicationId and applicationName to the app", "var", "applicationId", "=", "Ember", ".", "guidFor", "(", "app", ")", ";", "var", "applicationName", "=", "app", ".", "name", "||", "app", ".", "modulePrefix", "||", "`", "${", "applicationId", "}", "`", ";", "Object", ".", "assign", "(", "app", ",", "{", "applicationId", ",", "applicationName", "}", ")", ";", "return", "app", ";", "}", ")", ";", "}" ]
Get all the Ember.Application instances from Ember.Namespace.NAMESPACES and add our own applicationId and applicationName to them @return {*}
[ "Get", "all", "the", "Ember", ".", "Application", "instances", "from", "Ember", ".", "Namespace", ".", "NAMESPACES", "and", "add", "our", "own", "applicationId", "and", "applicationName", "to", "them" ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/ember_debug/vendor/startup-wrapper.js#L200-L219
12,722
emberjs/ember-inspector
ember_debug/vendor/startup-wrapper.js
sendVersionMiss
function sendVersionMiss() { var adapter = requireModule('ember-debug/adapters/' + currentAdapter)['default'].create(); adapter.onMessageReceived(function(message) { if (message.type === 'check-version') { sendVersionMismatch(); } }); sendVersionMismatch(); function sendVersionMismatch() { adapter.sendMessage({ name: 'version-mismatch', version: Ember.VERSION, from: 'inspectedWindow' }); } }
javascript
function sendVersionMiss() { var adapter = requireModule('ember-debug/adapters/' + currentAdapter)['default'].create(); adapter.onMessageReceived(function(message) { if (message.type === 'check-version') { sendVersionMismatch(); } }); sendVersionMismatch(); function sendVersionMismatch() { adapter.sendMessage({ name: 'version-mismatch', version: Ember.VERSION, from: 'inspectedWindow' }); } }
[ "function", "sendVersionMiss", "(", ")", "{", "var", "adapter", "=", "requireModule", "(", "'ember-debug/adapters/'", "+", "currentAdapter", ")", "[", "'default'", "]", ".", "create", "(", ")", ";", "adapter", ".", "onMessageReceived", "(", "function", "(", "message", ")", "{", "if", "(", "message", ".", "type", "===", "'check-version'", ")", "{", "sendVersionMismatch", "(", ")", ";", "}", "}", ")", ";", "sendVersionMismatch", "(", ")", ";", "function", "sendVersionMismatch", "(", ")", "{", "adapter", ".", "sendMessage", "(", "{", "name", ":", "'version-mismatch'", ",", "version", ":", "Ember", ".", "VERSION", ",", "from", ":", "'inspectedWindow'", "}", ")", ";", "}", "}" ]
This function is called if the app's Ember version is not supported by this version of the inspector. It sends a message to the inspector app to redirect to an inspector version that supports this Ember version.
[ "This", "function", "is", "called", "if", "the", "app", "s", "Ember", "version", "is", "not", "supported", "by", "this", "version", "of", "the", "inspector", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/ember_debug/vendor/startup-wrapper.js#L228-L244
12,723
emberjs/ember-inspector
app/adapters/basic.js
compareVersion
function compareVersion(version1, version2) { version1 = cleanupVersion(version1).split('.'); version2 = cleanupVersion(version2).split('.'); for (let i = 0; i < 3; i++) { let compared = compare(+version1[i], +version2[i]); if (compared !== 0) { return compared; } } return 0; }
javascript
function compareVersion(version1, version2) { version1 = cleanupVersion(version1).split('.'); version2 = cleanupVersion(version2).split('.'); for (let i = 0; i < 3; i++) { let compared = compare(+version1[i], +version2[i]); if (compared !== 0) { return compared; } } return 0; }
[ "function", "compareVersion", "(", "version1", ",", "version2", ")", "{", "version1", "=", "cleanupVersion", "(", "version1", ")", ".", "split", "(", "'.'", ")", ";", "version2", "=", "cleanupVersion", "(", "version2", ")", ".", "split", "(", "'.'", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "3", ";", "i", "++", ")", "{", "let", "compared", "=", "compare", "(", "+", "version1", "[", "i", "]", ",", "+", "version2", "[", "i", "]", ")", ";", "if", "(", "compared", "!==", "0", ")", "{", "return", "compared", ";", "}", "}", "return", "0", ";", "}" ]
Compares two Ember versions. Returns: `-1` if version < version 0 if version1 == version2 1 if version1 > version2 @param {String} version1 @param {String} version2 @return {Boolean} result of the comparison
[ "Compares", "two", "Ember", "versions", "." ]
2237dc1b4818e31a856f3348f35305b10f42f60a
https://github.com/emberjs/ember-inspector/blob/2237dc1b4818e31a856f3348f35305b10f42f60a/app/adapters/basic.js#L119-L129
12,724
mtth/avsc
etc/browser/avsc-types.js
parse
function parse(any, opts) { var schema; if (typeof any == 'string') { try { schema = JSON.parse(any); } catch (err) { schema = any; } } else { schema = any; } return types.Type.forSchema(schema, opts); }
javascript
function parse(any, opts) { var schema; if (typeof any == 'string') { try { schema = JSON.parse(any); } catch (err) { schema = any; } } else { schema = any; } return types.Type.forSchema(schema, opts); }
[ "function", "parse", "(", "any", ",", "opts", ")", "{", "var", "schema", ";", "if", "(", "typeof", "any", "==", "'string'", ")", "{", "try", "{", "schema", "=", "JSON", ".", "parse", "(", "any", ")", ";", "}", "catch", "(", "err", ")", "{", "schema", "=", "any", ";", "}", "}", "else", "{", "schema", "=", "any", ";", "}", "return", "types", ".", "Type", ".", "forSchema", "(", "schema", ",", "opts", ")", ";", "}" ]
Basic parse method, only supporting JSON parsing.
[ "Basic", "parse", "method", "only", "supporting", "JSON", "parsing", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/etc/browser/avsc-types.js#L15-L27
12,725
mtth/avsc
lib/utils.js
bufferFrom
function bufferFrom(data, enc) { if (typeof Buffer.from == 'function') { return Buffer.from(data, enc); } else { return new Buffer(data, enc); } }
javascript
function bufferFrom(data, enc) { if (typeof Buffer.from == 'function') { return Buffer.from(data, enc); } else { return new Buffer(data, enc); } }
[ "function", "bufferFrom", "(", "data", ",", "enc", ")", "{", "if", "(", "typeof", "Buffer", ".", "from", "==", "'function'", ")", "{", "return", "Buffer", ".", "from", "(", "data", ",", "enc", ")", ";", "}", "else", "{", "return", "new", "Buffer", "(", "data", ",", "enc", ")", ";", "}", "}" ]
Create a new buffer with the input contents. @param data {Array|String} The buffer's data. @param enc {String} Encoding, used if data is a string.
[ "Create", "a", "new", "buffer", "with", "the", "input", "contents", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/utils.js#L35-L41
12,726
mtth/avsc
lib/utils.js
getOption
function getOption(opts, key, def) { var value = opts[key]; return value === undefined ? def : value; }
javascript
function getOption(opts, key, def) { var value = opts[key]; return value === undefined ? def : value; }
[ "function", "getOption", "(", "opts", ",", "key", ",", "def", ")", "{", "var", "value", "=", "opts", "[", "key", "]", ";", "return", "value", "===", "undefined", "?", "def", ":", "value", ";", "}" ]
Get option or default if undefined. @param opts {Object} Options. @param key {String} Name of the option. @param def {...} Default value. This is useful mostly for true-ish defaults and false-ish values (where the usual `||` idiom breaks down).
[ "Get", "option", "or", "default", "if", "undefined", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/utils.js#L68-L71
12,727
mtth/avsc
lib/utils.js
getHash
function getHash(str, algorithm) { algorithm = algorithm || 'md5'; var hash = crypto.createHash(algorithm); hash.end(str); return hash.read(); }
javascript
function getHash(str, algorithm) { algorithm = algorithm || 'md5'; var hash = crypto.createHash(algorithm); hash.end(str); return hash.read(); }
[ "function", "getHash", "(", "str", ",", "algorithm", ")", "{", "algorithm", "=", "algorithm", "||", "'md5'", ";", "var", "hash", "=", "crypto", ".", "createHash", "(", "algorithm", ")", ";", "hash", ".", "end", "(", "str", ")", ";", "return", "hash", ".", "read", "(", ")", ";", "}" ]
Compute a string's hash. @param str {String} The string to hash. @param algorithm {String} The algorithm used. Defaults to MD5.
[ "Compute", "a", "string", "s", "hash", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/utils.js#L79-L84
12,728
mtth/avsc
lib/utils.js
singleIndexOf
function singleIndexOf(arr, v) { var pos = -1; var i, l; if (!arr) { return -1; } for (i = 0, l = arr.length; i < l; i++) { if (arr[i] === v) { if (pos >= 0) { return -2; } pos = i; } } return pos; }
javascript
function singleIndexOf(arr, v) { var pos = -1; var i, l; if (!arr) { return -1; } for (i = 0, l = arr.length; i < l; i++) { if (arr[i] === v) { if (pos >= 0) { return -2; } pos = i; } } return pos; }
[ "function", "singleIndexOf", "(", "arr", ",", "v", ")", "{", "var", "pos", "=", "-", "1", ";", "var", "i", ",", "l", ";", "if", "(", "!", "arr", ")", "{", "return", "-", "1", ";", "}", "for", "(", "i", "=", "0", ",", "l", "=", "arr", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "arr", "[", "i", "]", "===", "v", ")", "{", "if", "(", "pos", ">=", "0", ")", "{", "return", "-", "2", ";", "}", "pos", "=", "i", ";", "}", "}", "return", "pos", ";", "}" ]
Find index of value in array. @param arr {Array} Can also be a false-ish value. @param v {Object} Value to find. Returns -1 if not found, -2 if found multiple times.
[ "Find", "index", "of", "value", "in", "array", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/utils.js#L94-L109
12,729
mtth/avsc
lib/utils.js
toMap
function toMap(arr, fn) { var obj = {}; var i, elem; for (i = 0; i < arr.length; i++) { elem = arr[i]; obj[fn(elem)] = elem; } return obj; }
javascript
function toMap(arr, fn) { var obj = {}; var i, elem; for (i = 0; i < arr.length; i++) { elem = arr[i]; obj[fn(elem)] = elem; } return obj; }
[ "function", "toMap", "(", "arr", ",", "fn", ")", "{", "var", "obj", "=", "{", "}", ";", "var", "i", ",", "elem", ";", "for", "(", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "elem", "=", "arr", "[", "i", "]", ";", "obj", "[", "fn", "(", "elem", ")", "]", "=", "elem", ";", "}", "return", "obj", ";", "}" ]
Convert array to map. @param arr {Array} Elements. @param fn {Function} Function returning an element's key.
[ "Convert", "array", "to", "map", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/utils.js#L117-L125
12,730
mtth/avsc
lib/utils.js
hasDuplicates
function hasDuplicates(arr, fn) { var obj = {}; var i, l, elem; for (i = 0, l = arr.length; i < l; i++) { elem = arr[i]; if (fn) { elem = fn(elem); } if (obj[elem]) { return true; } obj[elem] = true; } return false; }
javascript
function hasDuplicates(arr, fn) { var obj = {}; var i, l, elem; for (i = 0, l = arr.length; i < l; i++) { elem = arr[i]; if (fn) { elem = fn(elem); } if (obj[elem]) { return true; } obj[elem] = true; } return false; }
[ "function", "hasDuplicates", "(", "arr", ",", "fn", ")", "{", "var", "obj", "=", "{", "}", ";", "var", "i", ",", "l", ",", "elem", ";", "for", "(", "i", "=", "0", ",", "l", "=", "arr", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "elem", "=", "arr", "[", "i", "]", ";", "if", "(", "fn", ")", "{", "elem", "=", "fn", "(", "elem", ")", ";", "}", "if", "(", "obj", "[", "elem", "]", ")", "{", "return", "true", ";", "}", "obj", "[", "elem", "]", "=", "true", ";", "}", "return", "false", ";", "}" ]
Check whether an array has duplicates. @param arr {Array} The array. @param fn {Function} Optional function to apply to each element.
[ "Check", "whether", "an", "array", "has", "duplicates", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/utils.js#L142-L156
12,731
mtth/avsc
lib/utils.js
copyOwnProperties
function copyOwnProperties(src, dst, overwrite) { var names = Object.getOwnPropertyNames(src); var i, l, name; for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (!dst.hasOwnProperty(name) || overwrite) { var descriptor = Object.getOwnPropertyDescriptor(src, name); Object.defineProperty(dst, name, descriptor); } } return dst; }
javascript
function copyOwnProperties(src, dst, overwrite) { var names = Object.getOwnPropertyNames(src); var i, l, name; for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (!dst.hasOwnProperty(name) || overwrite) { var descriptor = Object.getOwnPropertyDescriptor(src, name); Object.defineProperty(dst, name, descriptor); } } return dst; }
[ "function", "copyOwnProperties", "(", "src", ",", "dst", ",", "overwrite", ")", "{", "var", "names", "=", "Object", ".", "getOwnPropertyNames", "(", "src", ")", ";", "var", "i", ",", "l", ",", "name", ";", "for", "(", "i", "=", "0", ",", "l", "=", "names", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "name", "=", "names", "[", "i", "]", ";", "if", "(", "!", "dst", ".", "hasOwnProperty", "(", "name", ")", "||", "overwrite", ")", "{", "var", "descriptor", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "src", ",", "name", ")", ";", "Object", ".", "defineProperty", "(", "dst", ",", "name", ",", "descriptor", ")", ";", "}", "}", "return", "dst", ";", "}" ]
Copy properties from one object to another. @param src {Object} The source object. @param dst {Object} The destination object. @param overwrite {Boolean} Whether to overwrite existing destination properties. Defaults to false.
[ "Copy", "properties", "from", "one", "object", "to", "another", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/utils.js#L166-L177
12,732
mtth/avsc
lib/utils.js
addDeprecatedGetters
function addDeprecatedGetters(obj, props) { var proto = obj.prototype; var i, l, prop, getter; for (i = 0, l = props.length; i < l; i++) { prop = props[i]; getter = 'get' + capitalize(prop); proto[getter] = util.deprecate( createGetter(prop), 'use `.' + prop + '` instead of `.' + getter + '()`' ); } function createGetter(prop) { return function () { var delegate = this[prop]; return typeof delegate == 'function' ? delegate.apply(this, arguments) : delegate; }; } }
javascript
function addDeprecatedGetters(obj, props) { var proto = obj.prototype; var i, l, prop, getter; for (i = 0, l = props.length; i < l; i++) { prop = props[i]; getter = 'get' + capitalize(prop); proto[getter] = util.deprecate( createGetter(prop), 'use `.' + prop + '` instead of `.' + getter + '()`' ); } function createGetter(prop) { return function () { var delegate = this[prop]; return typeof delegate == 'function' ? delegate.apply(this, arguments) : delegate; }; } }
[ "function", "addDeprecatedGetters", "(", "obj", ",", "props", ")", "{", "var", "proto", "=", "obj", ".", "prototype", ";", "var", "i", ",", "l", ",", "prop", ",", "getter", ";", "for", "(", "i", "=", "0", ",", "l", "=", "props", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "prop", "=", "props", "[", "i", "]", ";", "getter", "=", "'get'", "+", "capitalize", "(", "prop", ")", ";", "proto", "[", "getter", "]", "=", "util", ".", "deprecate", "(", "createGetter", "(", "prop", ")", ",", "'use `.'", "+", "prop", "+", "'` instead of `.'", "+", "getter", "+", "'()`'", ")", ";", "}", "function", "createGetter", "(", "prop", ")", "{", "return", "function", "(", ")", "{", "var", "delegate", "=", "this", "[", "prop", "]", ";", "return", "typeof", "delegate", "==", "'function'", "?", "delegate", ".", "apply", "(", "this", ",", "arguments", ")", ":", "delegate", ";", "}", ";", "}", "}" ]
Batch-deprecate "getters" from an object's prototype.
[ "Batch", "-", "deprecate", "getters", "from", "an", "object", "s", "prototype", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/utils.js#L239-L259
12,733
mtth/avsc
lib/utils.js
Lcg
function Lcg(seed) { var a = 1103515245; var c = 12345; var m = Math.pow(2, 31); var state = Math.floor(seed || Math.random() * (m - 1)); this._max = m; this._nextInt = function () { return state = (a * state + c) % m; }; }
javascript
function Lcg(seed) { var a = 1103515245; var c = 12345; var m = Math.pow(2, 31); var state = Math.floor(seed || Math.random() * (m - 1)); this._max = m; this._nextInt = function () { return state = (a * state + c) % m; }; }
[ "function", "Lcg", "(", "seed", ")", "{", "var", "a", "=", "1103515245", ";", "var", "c", "=", "12345", ";", "var", "m", "=", "Math", ".", "pow", "(", "2", ",", "31", ")", ";", "var", "state", "=", "Math", ".", "floor", "(", "seed", "||", "Math", ".", "random", "(", ")", "*", "(", "m", "-", "1", ")", ")", ";", "this", ".", "_max", "=", "m", ";", "this", ".", "_nextInt", "=", "function", "(", ")", "{", "return", "state", "=", "(", "a", "*", "state", "+", "c", ")", "%", "m", ";", "}", ";", "}" ]
Generator of random things. Inspired by: http://stackoverflow.com/a/424445/1062617
[ "Generator", "of", "random", "things", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/utils.js#L289-L297
12,734
mtth/avsc
lib/index.js
parse
function parse(any, opts) { var schemaOrProtocol = specs.read(any); return schemaOrProtocol.protocol ? services.Service.forProtocol(schemaOrProtocol, opts) : types.Type.forSchema(schemaOrProtocol, opts); }
javascript
function parse(any, opts) { var schemaOrProtocol = specs.read(any); return schemaOrProtocol.protocol ? services.Service.forProtocol(schemaOrProtocol, opts) : types.Type.forSchema(schemaOrProtocol, opts); }
[ "function", "parse", "(", "any", ",", "opts", ")", "{", "var", "schemaOrProtocol", "=", "specs", ".", "read", "(", "any", ")", ";", "return", "schemaOrProtocol", ".", "protocol", "?", "services", ".", "Service", ".", "forProtocol", "(", "schemaOrProtocol", ",", "opts", ")", ":", "types", ".", "Type", ".", "forSchema", "(", "schemaOrProtocol", ",", "opts", ")", ";", "}" ]
Parse a schema and return the corresponding type or service.
[ "Parse", "a", "schema", "and", "return", "the", "corresponding", "type", "or", "service", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/index.js#L22-L27
12,735
mtth/avsc
lib/index.js
createFileDecoder
function createFileDecoder(path, opts) { return fs.createReadStream(path) .pipe(new containers.streams.BlockDecoder(opts)); }
javascript
function createFileDecoder(path, opts) { return fs.createReadStream(path) .pipe(new containers.streams.BlockDecoder(opts)); }
[ "function", "createFileDecoder", "(", "path", ",", "opts", ")", "{", "return", "fs", ".", "createReadStream", "(", "path", ")", ".", "pipe", "(", "new", "containers", ".", "streams", ".", "BlockDecoder", "(", "opts", ")", ")", ";", "}" ]
Readable stream of records from a local Avro file.
[ "Readable", "stream", "of", "records", "from", "a", "local", "Avro", "file", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/index.js#L74-L77
12,736
mtth/avsc
lib/index.js
createFileEncoder
function createFileEncoder(path, schema, opts) { var encoder = new containers.streams.BlockEncoder(schema, opts); encoder.pipe(fs.createWriteStream(path, {defaultEncoding: 'binary'})); return encoder; }
javascript
function createFileEncoder(path, schema, opts) { var encoder = new containers.streams.BlockEncoder(schema, opts); encoder.pipe(fs.createWriteStream(path, {defaultEncoding: 'binary'})); return encoder; }
[ "function", "createFileEncoder", "(", "path", ",", "schema", ",", "opts", ")", "{", "var", "encoder", "=", "new", "containers", ".", "streams", ".", "BlockEncoder", "(", "schema", ",", "opts", ")", ";", "encoder", ".", "pipe", "(", "fs", ".", "createWriteStream", "(", "path", ",", "{", "defaultEncoding", ":", "'binary'", "}", ")", ")", ";", "return", "encoder", ";", "}" ]
Writable stream of records to a local Avro file.
[ "Writable", "stream", "of", "records", "to", "a", "local", "Avro", "file", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/index.js#L80-L84
12,737
mtth/avsc
lib/types.js
FixedType
function FixedType(schema, opts) { Type.call(this, schema, opts); if (schema.size !== (schema.size | 0) || schema.size < 1) { throw new Error(f('invalid %s size', this.branchName)); } this.size = schema.size | 0; this._branchConstructor = this._createBranchConstructor(); Object.freeze(this); }
javascript
function FixedType(schema, opts) { Type.call(this, schema, opts); if (schema.size !== (schema.size | 0) || schema.size < 1) { throw new Error(f('invalid %s size', this.branchName)); } this.size = schema.size | 0; this._branchConstructor = this._createBranchConstructor(); Object.freeze(this); }
[ "function", "FixedType", "(", "schema", ",", "opts", ")", "{", "Type", ".", "call", "(", "this", ",", "schema", ",", "opts", ")", ";", "if", "(", "schema", ".", "size", "!==", "(", "schema", ".", "size", "|", "0", ")", "||", "schema", ".", "size", "<", "1", ")", "{", "throw", "new", "Error", "(", "f", "(", "'invalid %s size'", ",", "this", ".", "branchName", ")", ")", ";", "}", "this", ".", "size", "=", "schema", ".", "size", "|", "0", ";", "this", ".", "_branchConstructor", "=", "this", ".", "_createBranchConstructor", "(", ")", ";", "Object", ".", "freeze", "(", "this", ")", ";", "}" ]
Avro fixed type. Represented simply as a `Buffer`.
[ "Avro", "fixed", "type", ".", "Represented", "simply", "as", "a", "Buffer", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L1704-L1712
12,738
mtth/avsc
lib/types.js
MapType
function MapType(schema, opts) { Type.call(this); if (!schema.values) { throw new Error(f('missing map values: %j', schema)); } this.valuesType = Type.forSchema(schema.values, opts); this._branchConstructor = this._createBranchConstructor(); Object.freeze(this); }
javascript
function MapType(schema, opts) { Type.call(this); if (!schema.values) { throw new Error(f('missing map values: %j', schema)); } this.valuesType = Type.forSchema(schema.values, opts); this._branchConstructor = this._createBranchConstructor(); Object.freeze(this); }
[ "function", "MapType", "(", "schema", ",", "opts", ")", "{", "Type", ".", "call", "(", "this", ")", ";", "if", "(", "!", "schema", ".", "values", ")", "{", "throw", "new", "Error", "(", "f", "(", "'missing map values: %j'", ",", "schema", ")", ")", ";", "}", "this", ".", "valuesType", "=", "Type", ".", "forSchema", "(", "schema", ".", "values", ",", "opts", ")", ";", "this", ".", "_branchConstructor", "=", "this", ".", "_createBranchConstructor", "(", ")", ";", "Object", ".", "freeze", "(", "this", ")", ";", "}" ]
Avro map. Represented as vanilla objects.
[ "Avro", "map", ".", "Represented", "as", "vanilla", "objects", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L1768-L1776
12,739
mtth/avsc
lib/types.js
ArrayType
function ArrayType(schema, opts) { Type.call(this); if (!schema.items) { throw new Error(f('missing array items: %j', schema)); } this.itemsType = Type.forSchema(schema.items, opts); this._branchConstructor = this._createBranchConstructor(); Object.freeze(this); }
javascript
function ArrayType(schema, opts) { Type.call(this); if (!schema.items) { throw new Error(f('missing array items: %j', schema)); } this.itemsType = Type.forSchema(schema.items, opts); this._branchConstructor = this._createBranchConstructor(); Object.freeze(this); }
[ "function", "ArrayType", "(", "schema", ",", "opts", ")", "{", "Type", ".", "call", "(", "this", ")", ";", "if", "(", "!", "schema", ".", "items", ")", "{", "throw", "new", "Error", "(", "f", "(", "'missing array items: %j'", ",", "schema", ")", ")", ";", "}", "this", ".", "itemsType", "=", "Type", ".", "forSchema", "(", "schema", ".", "items", ",", "opts", ")", ";", "this", ".", "_branchConstructor", "=", "this", ".", "_createBranchConstructor", "(", ")", ";", "Object", ".", "freeze", "(", "this", ")", ";", "}" ]
Avro array. Represented as vanilla arrays.
[ "Avro", "array", ".", "Represented", "as", "vanilla", "arrays", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L1906-L1914
12,740
mtth/avsc
lib/types.js
Field
function Field(schema, opts) { var name = schema.name; if (typeof name != 'string' || !isValidName(name)) { throw new Error(f('invalid field name: %s', name)); } this.name = name; this.type = Type.forSchema(schema.type, opts); this.aliases = schema.aliases || []; this.doc = schema.doc !== undefined ? '' + schema.doc : undefined; this._order = (function (order) { switch (order) { case 'ascending': return 1; case 'descending': return -1; case 'ignore': return 0; default: throw new Error(f('invalid order: %j', order)); } })(schema.order === undefined ? 'ascending' : schema.order); var value = schema['default']; if (value !== undefined) { // We need to convert defaults back to a valid format (unions are // disallowed in default definitions, only the first type of each union is // allowed instead). // http://apache-avro.679487.n3.nabble.com/field-union-default-in-Java-td1175327.html var type = this.type; var val = type._copy(value, {coerce: 2, wrap: 2}); // The clone call above will throw an error if the default is invalid. if (isPrimitive(type.typeName) && type.typeName !== 'bytes') { // These are immutable. this.defaultValue = function () { return val; }; } else { this.defaultValue = function () { return type._copy(val); }; } } Object.freeze(this); }
javascript
function Field(schema, opts) { var name = schema.name; if (typeof name != 'string' || !isValidName(name)) { throw new Error(f('invalid field name: %s', name)); } this.name = name; this.type = Type.forSchema(schema.type, opts); this.aliases = schema.aliases || []; this.doc = schema.doc !== undefined ? '' + schema.doc : undefined; this._order = (function (order) { switch (order) { case 'ascending': return 1; case 'descending': return -1; case 'ignore': return 0; default: throw new Error(f('invalid order: %j', order)); } })(schema.order === undefined ? 'ascending' : schema.order); var value = schema['default']; if (value !== undefined) { // We need to convert defaults back to a valid format (unions are // disallowed in default definitions, only the first type of each union is // allowed instead). // http://apache-avro.679487.n3.nabble.com/field-union-default-in-Java-td1175327.html var type = this.type; var val = type._copy(value, {coerce: 2, wrap: 2}); // The clone call above will throw an error if the default is invalid. if (isPrimitive(type.typeName) && type.typeName !== 'bytes') { // These are immutable. this.defaultValue = function () { return val; }; } else { this.defaultValue = function () { return type._copy(val); }; } } Object.freeze(this); }
[ "function", "Field", "(", "schema", ",", "opts", ")", "{", "var", "name", "=", "schema", ".", "name", ";", "if", "(", "typeof", "name", "!=", "'string'", "||", "!", "isValidName", "(", "name", ")", ")", "{", "throw", "new", "Error", "(", "f", "(", "'invalid field name: %s'", ",", "name", ")", ")", ";", "}", "this", ".", "name", "=", "name", ";", "this", ".", "type", "=", "Type", ".", "forSchema", "(", "schema", ".", "type", ",", "opts", ")", ";", "this", ".", "aliases", "=", "schema", ".", "aliases", "||", "[", "]", ";", "this", ".", "doc", "=", "schema", ".", "doc", "!==", "undefined", "?", "''", "+", "schema", ".", "doc", ":", "undefined", ";", "this", ".", "_order", "=", "(", "function", "(", "order", ")", "{", "switch", "(", "order", ")", "{", "case", "'ascending'", ":", "return", "1", ";", "case", "'descending'", ":", "return", "-", "1", ";", "case", "'ignore'", ":", "return", "0", ";", "default", ":", "throw", "new", "Error", "(", "f", "(", "'invalid order: %j'", ",", "order", ")", ")", ";", "}", "}", ")", "(", "schema", ".", "order", "===", "undefined", "?", "'ascending'", ":", "schema", ".", "order", ")", ";", "var", "value", "=", "schema", "[", "'default'", "]", ";", "if", "(", "value", "!==", "undefined", ")", "{", "// We need to convert defaults back to a valid format (unions are", "// disallowed in default definitions, only the first type of each union is", "// allowed instead).", "// http://apache-avro.679487.n3.nabble.com/field-union-default-in-Java-td1175327.html", "var", "type", "=", "this", ".", "type", ";", "var", "val", "=", "type", ".", "_copy", "(", "value", ",", "{", "coerce", ":", "2", ",", "wrap", ":", "2", "}", ")", ";", "// The clone call above will throw an error if the default is invalid.", "if", "(", "isPrimitive", "(", "type", ".", "typeName", ")", "&&", "type", ".", "typeName", "!==", "'bytes'", ")", "{", "// These are immutable.", "this", ".", "defaultValue", "=", "function", "(", ")", "{", "return", "val", ";", "}", ";", "}", "else", "{", "this", ".", "defaultValue", "=", "function", "(", ")", "{", "return", "type", ".", "_copy", "(", "val", ")", ";", "}", ";", "}", "}", "Object", ".", "freeze", "(", "this", ")", ";", "}" ]
A record field.
[ "A", "record", "field", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L2768-L2810
12,741
mtth/avsc
lib/types.js
readValue
function readValue(type, tap, resolver, lazy) { if (resolver) { if (resolver._readerType !== type) { throw new Error('invalid resolver'); } return resolver._read(tap, lazy); } else { return type._read(tap); } }
javascript
function readValue(type, tap, resolver, lazy) { if (resolver) { if (resolver._readerType !== type) { throw new Error('invalid resolver'); } return resolver._read(tap, lazy); } else { return type._read(tap); } }
[ "function", "readValue", "(", "type", ",", "tap", ",", "resolver", ",", "lazy", ")", "{", "if", "(", "resolver", ")", "{", "if", "(", "resolver", ".", "_readerType", "!==", "type", ")", "{", "throw", "new", "Error", "(", "'invalid resolver'", ")", ";", "}", "return", "resolver", ".", "_read", "(", "tap", ",", "lazy", ")", ";", "}", "else", "{", "return", "type", ".", "_read", "(", "tap", ")", ";", "}", "}" ]
Read a value from a tap. @param type {Type} The type to decode. @param tap {Tap} The tap to read from. No checks are performed here. @param resolver {Resolver} Optional resolver. It must match the input type. @param lazy {Boolean} Skip trailing fields when using a resolver.
[ "Read", "a", "value", "from", "a", "tap", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L2863-L2872
12,742
mtth/avsc
lib/types.js
qualify
function qualify(name, namespace) { if (~name.indexOf('.')) { name = name.replace(/^\./, ''); // Allow absolute referencing. } else if (namespace) { name = namespace + '.' + name; } name.split('.').forEach(function (part) { if (!isValidName(part)) { throw new Error(f('invalid name: %j', name)); } }); var tail = unqualify(name); // Primitives are always in the global namespace. return isPrimitive(tail) ? tail : name; }
javascript
function qualify(name, namespace) { if (~name.indexOf('.')) { name = name.replace(/^\./, ''); // Allow absolute referencing. } else if (namespace) { name = namespace + '.' + name; } name.split('.').forEach(function (part) { if (!isValidName(part)) { throw new Error(f('invalid name: %j', name)); } }); var tail = unqualify(name); // Primitives are always in the global namespace. return isPrimitive(tail) ? tail : name; }
[ "function", "qualify", "(", "name", ",", "namespace", ")", "{", "if", "(", "~", "name", ".", "indexOf", "(", "'.'", ")", ")", "{", "name", "=", "name", ".", "replace", "(", "/", "^\\.", "/", ",", "''", ")", ";", "// Allow absolute referencing.", "}", "else", "if", "(", "namespace", ")", "{", "name", "=", "namespace", "+", "'.'", "+", "name", ";", "}", "name", ".", "split", "(", "'.'", ")", ".", "forEach", "(", "function", "(", "part", ")", "{", "if", "(", "!", "isValidName", "(", "part", ")", ")", "{", "throw", "new", "Error", "(", "f", "(", "'invalid name: %j'", ",", "name", ")", ")", ";", "}", "}", ")", ";", "var", "tail", "=", "unqualify", "(", "name", ")", ";", "// Primitives are always in the global namespace.", "return", "isPrimitive", "(", "tail", ")", "?", "tail", ":", "name", ";", "}" ]
Verify and return fully qualified name. @param name {String} Full or short name. It can be prefixed with a dot to force global namespace. @param namespace {String} Optional namespace.
[ "Verify", "and", "return", "fully", "qualified", "name", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L2891-L2905
12,743
mtth/avsc
lib/types.js
getClassName
function getClassName(typeName) { if (typeName === 'error') { typeName = 'record'; } else { var match = /^([^:]+):(.*)$/.exec(typeName); if (match) { if (match[1] === 'union') { typeName = match[2] + 'Union'; } else { // Logical type. typeName = match[1]; } } } return utils.capitalize(typeName) + 'Type'; }
javascript
function getClassName(typeName) { if (typeName === 'error') { typeName = 'record'; } else { var match = /^([^:]+):(.*)$/.exec(typeName); if (match) { if (match[1] === 'union') { typeName = match[2] + 'Union'; } else { // Logical type. typeName = match[1]; } } } return utils.capitalize(typeName) + 'Type'; }
[ "function", "getClassName", "(", "typeName", ")", "{", "if", "(", "typeName", "===", "'error'", ")", "{", "typeName", "=", "'record'", ";", "}", "else", "{", "var", "match", "=", "/", "^([^:]+):(.*)$", "/", ".", "exec", "(", "typeName", ")", ";", "if", "(", "match", ")", "{", "if", "(", "match", "[", "1", "]", "===", "'union'", ")", "{", "typeName", "=", "match", "[", "2", "]", "+", "'Union'", ";", "}", "else", "{", "// Logical type.", "typeName", "=", "match", "[", "1", "]", ";", "}", "}", "}", "return", "utils", ".", "capitalize", "(", "typeName", ")", "+", "'Type'", ";", "}" ]
Return a type's class name from its Avro type name. We can't simply use `constructor.name` since it isn't supported in all browsers. @param typeName {String} Type name.
[ "Return", "a", "type", "s", "class", "name", "from", "its", "Avro", "type", "name", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L2945-L2960
12,744
mtth/avsc
lib/types.js
readArraySize
function readArraySize(tap) { var n = tap.readLong(); if (n < 0) { n = -n; tap.skipLong(); // Skip size. } return n; }
javascript
function readArraySize(tap) { var n = tap.readLong(); if (n < 0) { n = -n; tap.skipLong(); // Skip size. } return n; }
[ "function", "readArraySize", "(", "tap", ")", "{", "var", "n", "=", "tap", ".", "readLong", "(", ")", ";", "if", "(", "n", "<", "0", ")", "{", "n", "=", "-", "n", ";", "tap", ".", "skipLong", "(", ")", ";", "// Skip size.", "}", "return", "n", ";", "}" ]
Get the number of elements in an array block. @param tap {Tap} A tap positioned at the beginning of an array block.
[ "Get", "the", "number", "of", "elements", "in", "an", "array", "block", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L2967-L2974
12,745
mtth/avsc
lib/types.js
isAmbiguous
function isAmbiguous(types) { var buckets = {}; var i, l, bucket, type; for (i = 0, l = types.length; i < l; i++) { type = types[i]; if (!Type.isType(type, 'logical')) { bucket = getTypeBucket(type); if (buckets[bucket]) { return true; } buckets[bucket] = true; } } return false; }
javascript
function isAmbiguous(types) { var buckets = {}; var i, l, bucket, type; for (i = 0, l = types.length; i < l; i++) { type = types[i]; if (!Type.isType(type, 'logical')) { bucket = getTypeBucket(type); if (buckets[bucket]) { return true; } buckets[bucket] = true; } } return false; }
[ "function", "isAmbiguous", "(", "types", ")", "{", "var", "buckets", "=", "{", "}", ";", "var", "i", ",", "l", ",", "bucket", ",", "type", ";", "for", "(", "i", "=", "0", ",", "l", "=", "types", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "type", "=", "types", "[", "i", "]", ";", "if", "(", "!", "Type", ".", "isType", "(", "type", ",", "'logical'", ")", ")", "{", "bucket", "=", "getTypeBucket", "(", "type", ")", ";", "if", "(", "buckets", "[", "bucket", "]", ")", "{", "return", "true", ";", "}", "buckets", "[", "bucket", "]", "=", "true", ";", "}", "}", "return", "false", ";", "}" ]
Check whether a collection of types leads to an ambiguous union. @param types {Array} Array of types.
[ "Check", "whether", "a", "collection", "of", "types", "leads", "to", "an", "ambiguous", "union", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L3072-L3086
12,746
mtth/avsc
lib/types.js
combineNumbers
function combineNumbers(types) { var typeNames = ['int', 'long', 'float', 'double']; var superIndex = -1; var superType = null; var i, l, type, index; for (i = 0, l = types.length; i < l; i++) { type = types[i]; index = typeNames.indexOf(type.typeName); if (index > superIndex) { superIndex = index; superType = type; } } return superType; }
javascript
function combineNumbers(types) { var typeNames = ['int', 'long', 'float', 'double']; var superIndex = -1; var superType = null; var i, l, type, index; for (i = 0, l = types.length; i < l; i++) { type = types[i]; index = typeNames.indexOf(type.typeName); if (index > superIndex) { superIndex = index; superType = type; } } return superType; }
[ "function", "combineNumbers", "(", "types", ")", "{", "var", "typeNames", "=", "[", "'int'", ",", "'long'", ",", "'float'", ",", "'double'", "]", ";", "var", "superIndex", "=", "-", "1", ";", "var", "superType", "=", "null", ";", "var", "i", ",", "l", ",", "type", ",", "index", ";", "for", "(", "i", "=", "0", ",", "l", "=", "types", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "type", "=", "types", "[", "i", "]", ";", "index", "=", "typeNames", ".", "indexOf", "(", "type", ".", "typeName", ")", ";", "if", "(", "index", ">", "superIndex", ")", "{", "superIndex", "=", "index", ";", "superType", "=", "type", ";", "}", "}", "return", "superType", ";", "}" ]
Combine number types. Note that never have to create a new type here, we are guaranteed to be able to reuse one of the input types as super-type.
[ "Combine", "number", "types", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/types.js#L3094-L3108
12,747
mtth/avsc
etc/benchmarks/js-serialization-libraries/index.js
generateStats
function generateStats(schema, opts) { opts = opts || {}; var type = avro.parse(schema, {wrapUnions: opts.wrapUnions}); return [DecodeSuite, EncodeSuite].map(function (Suite) { var stats = []; var suite = new Suite(type, opts) .on('start', function () { console.error(Suite.key_ + ' ' + type); }) .on('cycle', function (evt) { console.error('' + evt.target); }) .run(); stats.push({ value: suite.getValue(), stats: suite.map(function (benchmark) { var stats = benchmark.stats; return { name: benchmark.name, mean: stats.mean, rme: stats.rme }; }) }); return {name: Suite.key_, stats: stats}; }); }
javascript
function generateStats(schema, opts) { opts = opts || {}; var type = avro.parse(schema, {wrapUnions: opts.wrapUnions}); return [DecodeSuite, EncodeSuite].map(function (Suite) { var stats = []; var suite = new Suite(type, opts) .on('start', function () { console.error(Suite.key_ + ' ' + type); }) .on('cycle', function (evt) { console.error('' + evt.target); }) .run(); stats.push({ value: suite.getValue(), stats: suite.map(function (benchmark) { var stats = benchmark.stats; return { name: benchmark.name, mean: stats.mean, rme: stats.rme }; }) }); return {name: Suite.key_, stats: stats}; }); }
[ "function", "generateStats", "(", "schema", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "type", "=", "avro", ".", "parse", "(", "schema", ",", "{", "wrapUnions", ":", "opts", ".", "wrapUnions", "}", ")", ";", "return", "[", "DecodeSuite", ",", "EncodeSuite", "]", ".", "map", "(", "function", "(", "Suite", ")", "{", "var", "stats", "=", "[", "]", ";", "var", "suite", "=", "new", "Suite", "(", "type", ",", "opts", ")", ".", "on", "(", "'start'", ",", "function", "(", ")", "{", "console", ".", "error", "(", "Suite", ".", "key_", "+", "' '", "+", "type", ")", ";", "}", ")", ".", "on", "(", "'cycle'", ",", "function", "(", "evt", ")", "{", "console", ".", "error", "(", "''", "+", "evt", ".", "target", ")", ";", "}", ")", ".", "run", "(", ")", ";", "stats", ".", "push", "(", "{", "value", ":", "suite", ".", "getValue", "(", ")", ",", "stats", ":", "suite", ".", "map", "(", "function", "(", "benchmark", ")", "{", "var", "stats", "=", "benchmark", ".", "stats", ";", "return", "{", "name", ":", "benchmark", ".", "name", ",", "mean", ":", "stats", ".", "mean", ",", "rme", ":", "stats", ".", "rme", "}", ";", "}", ")", "}", ")", ";", "return", "{", "name", ":", "Suite", ".", "key_", ",", "stats", ":", "stats", "}", ";", "}", ")", ";", "}" ]
Generate statistics for a given schema.
[ "Generate", "statistics", "for", "a", "given", "schema", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/etc/benchmarks/js-serialization-libraries/index.js#L30-L53
12,748
mtth/avsc
etc/benchmarks/js-serialization-libraries/index.js
Suite
function Suite(type, opts) { Benchmark.Suite.call(this); opts = opts || {}; this._type = type; this._compatibleType = avro.parse(type.getSchema(), { typeHook: typeHook, wrapUnions: opts.wrapUnions }); this._value = opts.value ? type.fromString(opts.value) : type.random(); Object.keys(opts).forEach(function (name) { if (!name.indexOf('_')) { return; } var fn = this['__' + name]; if (typeof fn == 'function') { this.add(name, fn.call(this, opts[name])); // Add benchmark. } }, this); }
javascript
function Suite(type, opts) { Benchmark.Suite.call(this); opts = opts || {}; this._type = type; this._compatibleType = avro.parse(type.getSchema(), { typeHook: typeHook, wrapUnions: opts.wrapUnions }); this._value = opts.value ? type.fromString(opts.value) : type.random(); Object.keys(opts).forEach(function (name) { if (!name.indexOf('_')) { return; } var fn = this['__' + name]; if (typeof fn == 'function') { this.add(name, fn.call(this, opts[name])); // Add benchmark. } }, this); }
[ "function", "Suite", "(", "type", ",", "opts", ")", "{", "Benchmark", ".", "Suite", ".", "call", "(", "this", ")", ";", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "_type", "=", "type", ";", "this", ".", "_compatibleType", "=", "avro", ".", "parse", "(", "type", ".", "getSchema", "(", ")", ",", "{", "typeHook", ":", "typeHook", ",", "wrapUnions", ":", "opts", ".", "wrapUnions", "}", ")", ";", "this", ".", "_value", "=", "opts", ".", "value", "?", "type", ".", "fromString", "(", "opts", ".", "value", ")", ":", "type", ".", "random", "(", ")", ";", "Object", ".", "keys", "(", "opts", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "if", "(", "!", "name", ".", "indexOf", "(", "'_'", ")", ")", "{", "return", ";", "}", "var", "fn", "=", "this", "[", "'__'", "+", "name", "]", ";", "if", "(", "typeof", "fn", "==", "'function'", ")", "{", "this", ".", "add", "(", "name", ",", "fn", ".", "call", "(", "this", ",", "opts", "[", "name", "]", ")", ")", ";", "// Add benchmark.", "}", "}", ",", "this", ")", ";", "}" ]
Custom benchmark suite.
[ "Custom", "benchmark", "suite", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/etc/benchmarks/js-serialization-libraries/index.js#L60-L80
12,749
mtth/avsc
lib/specs.js
read
function read(str) { var schema; if (typeof str == 'string' && ~str.indexOf(path.sep) && files.existsSync(str)) { // Try interpreting `str` as path to a file contain a JSON schema or an IDL // protocol. Note that we add the second check to skip primitive references // (e.g. `"int"`, the most common use-case for `avro.parse`). var contents = files.readFileSync(str, {encoding: 'utf8'}); try { return JSON.parse(contents); } catch (err) { var opts = {importHook: files.createSyncImportHook()}; assembleProtocol(str, opts, function (err, protocolSchema) { schema = err ? contents : protocolSchema; }); } } else { schema = str; } if (typeof schema != 'string' || schema === 'null') { // This last predicate is to allow `read('null')` to work similarly to // `read('int')` and other primitives (null needs to be handled separately // since it is also a valid JSON identifier). return schema; } try { return JSON.parse(schema); } catch (err) { try { return Reader.readProtocol(schema); } catch (err) { try { return Reader.readSchema(schema); } catch (err) { return schema; } } } }
javascript
function read(str) { var schema; if (typeof str == 'string' && ~str.indexOf(path.sep) && files.existsSync(str)) { // Try interpreting `str` as path to a file contain a JSON schema or an IDL // protocol. Note that we add the second check to skip primitive references // (e.g. `"int"`, the most common use-case for `avro.parse`). var contents = files.readFileSync(str, {encoding: 'utf8'}); try { return JSON.parse(contents); } catch (err) { var opts = {importHook: files.createSyncImportHook()}; assembleProtocol(str, opts, function (err, protocolSchema) { schema = err ? contents : protocolSchema; }); } } else { schema = str; } if (typeof schema != 'string' || schema === 'null') { // This last predicate is to allow `read('null')` to work similarly to // `read('int')` and other primitives (null needs to be handled separately // since it is also a valid JSON identifier). return schema; } try { return JSON.parse(schema); } catch (err) { try { return Reader.readProtocol(schema); } catch (err) { try { return Reader.readSchema(schema); } catch (err) { return schema; } } } }
[ "function", "read", "(", "str", ")", "{", "var", "schema", ";", "if", "(", "typeof", "str", "==", "'string'", "&&", "~", "str", ".", "indexOf", "(", "path", ".", "sep", ")", "&&", "files", ".", "existsSync", "(", "str", ")", ")", "{", "// Try interpreting `str` as path to a file contain a JSON schema or an IDL", "// protocol. Note that we add the second check to skip primitive references", "// (e.g. `\"int\"`, the most common use-case for `avro.parse`).", "var", "contents", "=", "files", ".", "readFileSync", "(", "str", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "try", "{", "return", "JSON", ".", "parse", "(", "contents", ")", ";", "}", "catch", "(", "err", ")", "{", "var", "opts", "=", "{", "importHook", ":", "files", ".", "createSyncImportHook", "(", ")", "}", ";", "assembleProtocol", "(", "str", ",", "opts", ",", "function", "(", "err", ",", "protocolSchema", ")", "{", "schema", "=", "err", "?", "contents", ":", "protocolSchema", ";", "}", ")", ";", "}", "}", "else", "{", "schema", "=", "str", ";", "}", "if", "(", "typeof", "schema", "!=", "'string'", "||", "schema", "===", "'null'", ")", "{", "// This last predicate is to allow `read('null')` to work similarly to", "// `read('int')` and other primitives (null needs to be handled separately", "// since it is also a valid JSON identifier).", "return", "schema", ";", "}", "try", "{", "return", "JSON", ".", "parse", "(", "schema", ")", ";", "}", "catch", "(", "err", ")", "{", "try", "{", "return", "Reader", ".", "readProtocol", "(", "schema", ")", ";", "}", "catch", "(", "err", ")", "{", "try", "{", "return", "Reader", ".", "readSchema", "(", "schema", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "schema", ";", "}", "}", "}", "}" ]
Parsing functions. Convenience function to parse multiple inputs into protocols and schemas. It should cover most basic use-cases but has a few limitations: + It doesn't allow passing options to the parsing step. + The protocol/type inference logic can be deceived. The parsing logic is as follows: + If `str` contains `path.sep` (on windows `\`, otherwise `/`) and is a path to an existing file, it will first be read as JSON, then as an IDL specification if JSON parsing failed. If either succeeds, the result is returned, otherwise the next steps are run using the file's content instead of the input path. + If `str` is a valid JSON string, it is parsed then returned. + If `str` is a valid IDL protocol specification, it is parsed and returned if no imports are present (and an error is thrown if there are any imports). + If `str` is a valid IDL type specification, it is parsed and returned. + If neither of the above cases apply, `str` is returned.
[ "Parsing", "functions", ".", "Convenience", "function", "to", "parse", "multiple", "inputs", "into", "protocols", "and", "schemas", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/specs.js#L183-L220
12,750
mtth/avsc
lib/specs.js
extractJavadoc
function extractJavadoc(str) { var lines = str .replace(/^[ \t]+|[ \t]+$/g, '') // Trim whitespace. .split('\n').map(function (line, i) { return i ? line.replace(/^\s*\*\s?/, '') : line; }); while (!lines[0]) { lines.shift(); } while (!lines[lines.length - 1]) { lines.pop(); } return lines.join('\n'); }
javascript
function extractJavadoc(str) { var lines = str .replace(/^[ \t]+|[ \t]+$/g, '') // Trim whitespace. .split('\n').map(function (line, i) { return i ? line.replace(/^\s*\*\s?/, '') : line; }); while (!lines[0]) { lines.shift(); } while (!lines[lines.length - 1]) { lines.pop(); } return lines.join('\n'); }
[ "function", "extractJavadoc", "(", "str", ")", "{", "var", "lines", "=", "str", ".", "replace", "(", "/", "^[ \\t]+|[ \\t]+$", "/", "g", ",", "''", ")", "// Trim whitespace.", ".", "split", "(", "'\\n'", ")", ".", "map", "(", "function", "(", "line", ",", "i", ")", "{", "return", "i", "?", "line", ".", "replace", "(", "/", "^\\s*\\*\\s?", "/", ",", "''", ")", ":", "line", ";", "}", ")", ";", "while", "(", "!", "lines", "[", "0", "]", ")", "{", "lines", ".", "shift", "(", ")", ";", "}", "while", "(", "!", "lines", "[", "lines", ".", "length", "-", "1", "]", ")", "{", "lines", ".", "pop", "(", ")", ";", "}", "return", "lines", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Extract Javadoc contents from the comment. The parsing done is very simple and simply removes the line prefixes and leading / trailing empty lines. It's better to be conservative with formatting rather than risk losing information.
[ "Extract", "Javadoc", "contents", "from", "the", "comment", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/specs.js#L713-L726
12,751
mtth/avsc
etc/browser/avsc.js
BlobReader
function BlobReader(blob, opts) { stream.Readable.call(this); opts = opts || {}; this._batchSize = opts.batchSize || 65536; this._blob = blob; this._pos = 0; }
javascript
function BlobReader(blob, opts) { stream.Readable.call(this); opts = opts || {}; this._batchSize = opts.batchSize || 65536; this._blob = blob; this._pos = 0; }
[ "function", "BlobReader", "(", "blob", ",", "opts", ")", "{", "stream", ".", "Readable", ".", "call", "(", "this", ")", ";", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "_batchSize", "=", "opts", ".", "batchSize", "||", "65536", ";", "this", ".", "_blob", "=", "blob", ";", "this", ".", "_pos", "=", "0", ";", "}" ]
Transform stream which lazily reads a blob's contents.
[ "Transform", "stream", "which", "lazily", "reads", "a", "blob", "s", "contents", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/etc/browser/avsc.js#L20-L27
12,752
mtth/avsc
etc/browser/avsc.js
createBlobDecoder
function createBlobDecoder(blob, opts) { return new BlobReader(blob).pipe(new containers.streams.BlockDecoder(opts)); }
javascript
function createBlobDecoder(blob, opts) { return new BlobReader(blob).pipe(new containers.streams.BlockDecoder(opts)); }
[ "function", "createBlobDecoder", "(", "blob", ",", "opts", ")", "{", "return", "new", "BlobReader", "(", "blob", ")", ".", "pipe", "(", "new", "containers", ".", "streams", ".", "BlockDecoder", "(", "opts", ")", ")", ";", "}" ]
Read an Avro-container stored as a blob.
[ "Read", "an", "Avro", "-", "container", "stored", "as", "a", "blob", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/etc/browser/avsc.js#L70-L72
12,753
mtth/avsc
etc/browser/avsc.js
createBlobEncoder
function createBlobEncoder(schema, opts) { var encoder = new containers.streams.BlockEncoder(schema, opts); var builder = new BlobWriter(); encoder.pipe(builder); return new stream.Duplex({ objectMode: true, read: function () { // Not the fastest implementation, but it will only be called at most // once (since the builder only ever emits a single value) so it'll do. // It's also likely impractical to create very large blobs. var val = builder.read(); if (val) { done(val); } else { builder.once('readable', done); } var self = this; function done(val) { self.push(val || builder.read()); self.push(null); } }, write: function (val, encoding, cb) { return encoder.write(val, encoding, cb); } }).on('finish', function () { encoder.end(); }); }
javascript
function createBlobEncoder(schema, opts) { var encoder = new containers.streams.BlockEncoder(schema, opts); var builder = new BlobWriter(); encoder.pipe(builder); return new stream.Duplex({ objectMode: true, read: function () { // Not the fastest implementation, but it will only be called at most // once (since the builder only ever emits a single value) so it'll do. // It's also likely impractical to create very large blobs. var val = builder.read(); if (val) { done(val); } else { builder.once('readable', done); } var self = this; function done(val) { self.push(val || builder.read()); self.push(null); } }, write: function (val, encoding, cb) { return encoder.write(val, encoding, cb); } }).on('finish', function () { encoder.end(); }); }
[ "function", "createBlobEncoder", "(", "schema", ",", "opts", ")", "{", "var", "encoder", "=", "new", "containers", ".", "streams", ".", "BlockEncoder", "(", "schema", ",", "opts", ")", ";", "var", "builder", "=", "new", "BlobWriter", "(", ")", ";", "encoder", ".", "pipe", "(", "builder", ")", ";", "return", "new", "stream", ".", "Duplex", "(", "{", "objectMode", ":", "true", ",", "read", ":", "function", "(", ")", "{", "// Not the fastest implementation, but it will only be called at most", "// once (since the builder only ever emits a single value) so it'll do.", "// It's also likely impractical to create very large blobs.", "var", "val", "=", "builder", ".", "read", "(", ")", ";", "if", "(", "val", ")", "{", "done", "(", "val", ")", ";", "}", "else", "{", "builder", ".", "once", "(", "'readable'", ",", "done", ")", ";", "}", "var", "self", "=", "this", ";", "function", "done", "(", "val", ")", "{", "self", ".", "push", "(", "val", "||", "builder", ".", "read", "(", ")", ")", ";", "self", ".", "push", "(", "null", ")", ";", "}", "}", ",", "write", ":", "function", "(", "val", ",", "encoding", ",", "cb", ")", "{", "return", "encoder", ".", "write", "(", "val", ",", "encoding", ",", "cb", ")", ";", "}", "}", ")", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "encoder", ".", "end", "(", ")", ";", "}", ")", ";", "}" ]
Store Avro values into an Avro-container blob. The returned stream will emit a single value, the blob, when ended.
[ "Store", "Avro", "values", "into", "an", "Avro", "-", "container", "blob", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/etc/browser/avsc.js#L79-L105
12,754
mtth/avsc
lib/containers.js
BlockData
function BlockData(index, buf, cb, count) { this.index = index; this.buf = buf; this.cb = cb; this.count = count | 0; }
javascript
function BlockData(index, buf, cb, count) { this.index = index; this.buf = buf; this.cb = cb; this.count = count | 0; }
[ "function", "BlockData", "(", "index", ",", "buf", ",", "cb", ",", "count", ")", "{", "this", ".", "index", "=", "index", ";", "this", ".", "buf", "=", "buf", ";", "this", ".", "cb", "=", "cb", ";", "this", ".", "count", "=", "count", "|", "0", ";", "}" ]
Helpers. An indexed block. This can be used to preserve block order since compression and decompression can cause some some blocks to be returned out of order.
[ "Helpers", ".", "An", "indexed", "block", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/containers.js#L559-L564
12,755
mtth/avsc
lib/containers.js
tryReadBlock
function tryReadBlock(tap) { var pos = tap.pos; var block = BLOCK_TYPE._read(tap); if (!tap.isValid()) { tap.pos = pos; return null; } return block; }
javascript
function tryReadBlock(tap) { var pos = tap.pos; var block = BLOCK_TYPE._read(tap); if (!tap.isValid()) { tap.pos = pos; return null; } return block; }
[ "function", "tryReadBlock", "(", "tap", ")", "{", "var", "pos", "=", "tap", ".", "pos", ";", "var", "block", "=", "BLOCK_TYPE", ".", "_read", "(", "tap", ")", ";", "if", "(", "!", "tap", ".", "isValid", "(", ")", ")", "{", "tap", ".", "pos", "=", "pos", ";", "return", "null", ";", "}", "return", "block", ";", "}" ]
Maybe get a block.
[ "Maybe", "get", "a", "block", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/containers.js#L567-L575
12,756
mtth/avsc
lib/containers.js
copyBuffer
function copyBuffer(buf, pos, len) { var copy = utils.newBuffer(len); buf.copy(copy, 0, pos, pos + len); return copy; }
javascript
function copyBuffer(buf, pos, len) { var copy = utils.newBuffer(len); buf.copy(copy, 0, pos, pos + len); return copy; }
[ "function", "copyBuffer", "(", "buf", ",", "pos", ",", "len", ")", "{", "var", "copy", "=", "utils", ".", "newBuffer", "(", "len", ")", ";", "buf", ".", "copy", "(", "copy", ",", "0", ",", "pos", ",", "pos", "+", "len", ")", ";", "return", "copy", ";", "}" ]
Copy a buffer. This avoids creating a slice of the original buffer.
[ "Copy", "a", "buffer", ".", "This", "avoids", "creating", "a", "slice", "of", "the", "original", "buffer", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/containers.js#L596-L600
12,757
mtth/avsc
lib/services.js
Message
function Message(name, reqType, errType, resType, oneWay, doc) { this.name = name; if (!Type.isType(reqType, 'record')) { throw new Error('invalid request type'); } this.requestType = reqType; if ( !Type.isType(errType, 'union') || !Type.isType(errType.getTypes()[0], 'string') ) { throw new Error('invalid error type'); } this.errorType = errType; if (oneWay) { if (!Type.isType(resType, 'null') || errType.getTypes().length > 1) { throw new Error('inapplicable one-way parameter'); } } this.responseType = resType; this.oneWay = !!oneWay; this.doc = doc !== undefined ? '' + doc : undefined; Object.freeze(this); }
javascript
function Message(name, reqType, errType, resType, oneWay, doc) { this.name = name; if (!Type.isType(reqType, 'record')) { throw new Error('invalid request type'); } this.requestType = reqType; if ( !Type.isType(errType, 'union') || !Type.isType(errType.getTypes()[0], 'string') ) { throw new Error('invalid error type'); } this.errorType = errType; if (oneWay) { if (!Type.isType(resType, 'null') || errType.getTypes().length > 1) { throw new Error('inapplicable one-way parameter'); } } this.responseType = resType; this.oneWay = !!oneWay; this.doc = doc !== undefined ? '' + doc : undefined; Object.freeze(this); }
[ "function", "Message", "(", "name", ",", "reqType", ",", "errType", ",", "resType", ",", "oneWay", ",", "doc", ")", "{", "this", ".", "name", "=", "name", ";", "if", "(", "!", "Type", ".", "isType", "(", "reqType", ",", "'record'", ")", ")", "{", "throw", "new", "Error", "(", "'invalid request type'", ")", ";", "}", "this", ".", "requestType", "=", "reqType", ";", "if", "(", "!", "Type", ".", "isType", "(", "errType", ",", "'union'", ")", "||", "!", "Type", ".", "isType", "(", "errType", ".", "getTypes", "(", ")", "[", "0", "]", ",", "'string'", ")", ")", "{", "throw", "new", "Error", "(", "'invalid error type'", ")", ";", "}", "this", ".", "errorType", "=", "errType", ";", "if", "(", "oneWay", ")", "{", "if", "(", "!", "Type", ".", "isType", "(", "resType", ",", "'null'", ")", "||", "errType", ".", "getTypes", "(", ")", ".", "length", ">", "1", ")", "{", "throw", "new", "Error", "(", "'inapplicable one-way parameter'", ")", ";", "}", "}", "this", ".", "responseType", "=", "resType", ";", "this", ".", "oneWay", "=", "!", "!", "oneWay", ";", "this", ".", "doc", "=", "doc", "!==", "undefined", "?", "''", "+", "doc", ":", "undefined", ";", "Object", ".", "freeze", "(", "this", ")", ";", "}" ]
An Avro message, containing its request, response, etc.
[ "An", "Avro", "message", "containing", "its", "request", "response", "etc", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L83-L105
12,758
mtth/avsc
lib/services.js
Service
function Service(name, messages, types, ptcl, server) { if (typeof name != 'string') { // Let's be helpful in case this class is instantiated directly. return Service.forProtocol(name, messages); } this.name = name; this._messagesByName = messages || {}; this.messages = Object.freeze(utils.objectValues(this._messagesByName)); this._typesByName = types || {}; this.types = Object.freeze(utils.objectValues(this._typesByName)); this.protocol = ptcl; // We cache a string rather than a buffer to not retain an entire slab. this._hashStr = utils.getHash(JSON.stringify(ptcl)).toString('binary'); this.doc = ptcl.doc ? '' + ptcl.doc : undefined; // We add a server to each protocol for backwards-compatibility (to allow the // use of `protocol.on`). This covers all cases except the use of the // `strictErrors` option, which requires moving to the new API. this._server = server || this.createServer({silent: true}); Object.freeze(this); }
javascript
function Service(name, messages, types, ptcl, server) { if (typeof name != 'string') { // Let's be helpful in case this class is instantiated directly. return Service.forProtocol(name, messages); } this.name = name; this._messagesByName = messages || {}; this.messages = Object.freeze(utils.objectValues(this._messagesByName)); this._typesByName = types || {}; this.types = Object.freeze(utils.objectValues(this._typesByName)); this.protocol = ptcl; // We cache a string rather than a buffer to not retain an entire slab. this._hashStr = utils.getHash(JSON.stringify(ptcl)).toString('binary'); this.doc = ptcl.doc ? '' + ptcl.doc : undefined; // We add a server to each protocol for backwards-compatibility (to allow the // use of `protocol.on`). This covers all cases except the use of the // `strictErrors` option, which requires moving to the new API. this._server = server || this.createServer({silent: true}); Object.freeze(this); }
[ "function", "Service", "(", "name", ",", "messages", ",", "types", ",", "ptcl", ",", "server", ")", "{", "if", "(", "typeof", "name", "!=", "'string'", ")", "{", "// Let's be helpful in case this class is instantiated directly.", "return", "Service", ".", "forProtocol", "(", "name", ",", "messages", ")", ";", "}", "this", ".", "name", "=", "name", ";", "this", ".", "_messagesByName", "=", "messages", "||", "{", "}", ";", "this", ".", "messages", "=", "Object", ".", "freeze", "(", "utils", ".", "objectValues", "(", "this", ".", "_messagesByName", ")", ")", ";", "this", ".", "_typesByName", "=", "types", "||", "{", "}", ";", "this", ".", "types", "=", "Object", ".", "freeze", "(", "utils", ".", "objectValues", "(", "this", ".", "_typesByName", ")", ")", ";", "this", ".", "protocol", "=", "ptcl", ";", "// We cache a string rather than a buffer to not retain an entire slab.", "this", ".", "_hashStr", "=", "utils", ".", "getHash", "(", "JSON", ".", "stringify", "(", "ptcl", ")", ")", ".", "toString", "(", "'binary'", ")", ";", "this", ".", "doc", "=", "ptcl", ".", "doc", "?", "''", "+", "ptcl", ".", "doc", ":", "undefined", ";", "// We add a server to each protocol for backwards-compatibility (to allow the", "// use of `protocol.on`). This covers all cases except the use of the", "// `strictErrors` option, which requires moving to the new API.", "this", ".", "_server", "=", "server", "||", "this", ".", "createServer", "(", "{", "silent", ":", "true", "}", ")", ";", "Object", ".", "freeze", "(", "this", ")", ";", "}" ]
An Avro RPC service. This constructor shouldn't be called directly, but via the `Service.forProtocol` method. This function performs little logic to better support efficient copy.
[ "An", "Avro", "RPC", "service", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L179-L202
12,759
mtth/avsc
lib/services.js
discoverProtocol
function discoverProtocol(transport, opts, cb) { if (cb === undefined && typeof opts == 'function') { cb = opts; opts = undefined; } var svc = new Service({protocol: 'Empty'}, OPTS); var ptclStr; svc.createClient({timeout: opts && opts.timeout}) .createChannel(transport, { scope: opts && opts.scope, endWritable: typeof transport == 'function' // Stateless transports only. }).once('handshake', function (hreq, hres) { ptclStr = hres.serverProtocol; this.destroy(true); }) .once('eot', function (pending, err) { // Stateless transports will throw an interrupted error when the // channel is destroyed, we ignore it here. if (err && !/interrupted/.test(err)) { cb(err); // Likely timeout. } else { cb(null, JSON.parse(ptclStr)); } }); }
javascript
function discoverProtocol(transport, opts, cb) { if (cb === undefined && typeof opts == 'function') { cb = opts; opts = undefined; } var svc = new Service({protocol: 'Empty'}, OPTS); var ptclStr; svc.createClient({timeout: opts && opts.timeout}) .createChannel(transport, { scope: opts && opts.scope, endWritable: typeof transport == 'function' // Stateless transports only. }).once('handshake', function (hreq, hres) { ptclStr = hres.serverProtocol; this.destroy(true); }) .once('eot', function (pending, err) { // Stateless transports will throw an interrupted error when the // channel is destroyed, we ignore it here. if (err && !/interrupted/.test(err)) { cb(err); // Likely timeout. } else { cb(null, JSON.parse(ptclStr)); } }); }
[ "function", "discoverProtocol", "(", "transport", ",", "opts", ",", "cb", ")", "{", "if", "(", "cb", "===", "undefined", "&&", "typeof", "opts", "==", "'function'", ")", "{", "cb", "=", "opts", ";", "opts", "=", "undefined", ";", "}", "var", "svc", "=", "new", "Service", "(", "{", "protocol", ":", "'Empty'", "}", ",", "OPTS", ")", ";", "var", "ptclStr", ";", "svc", ".", "createClient", "(", "{", "timeout", ":", "opts", "&&", "opts", ".", "timeout", "}", ")", ".", "createChannel", "(", "transport", ",", "{", "scope", ":", "opts", "&&", "opts", ".", "scope", ",", "endWritable", ":", "typeof", "transport", "==", "'function'", "// Stateless transports only.", "}", ")", ".", "once", "(", "'handshake'", ",", "function", "(", "hreq", ",", "hres", ")", "{", "ptclStr", "=", "hres", ".", "serverProtocol", ";", "this", ".", "destroy", "(", "true", ")", ";", "}", ")", ".", "once", "(", "'eot'", ",", "function", "(", "pending", ",", "err", ")", "{", "// Stateless transports will throw an interrupted error when the", "// channel is destroyed, we ignore it here.", "if", "(", "err", "&&", "!", "/", "interrupted", "/", ".", "test", "(", "err", ")", ")", "{", "cb", "(", "err", ")", ";", "// Likely timeout.", "}", "else", "{", "cb", "(", "null", ",", "JSON", ".", "parse", "(", "ptclStr", ")", ")", ";", "}", "}", ")", ";", "}" ]
Function to retrieve a remote service's protocol.
[ "Function", "to", "retrieve", "a", "remote", "service", "s", "protocol", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L429-L454
12,760
mtth/avsc
lib/services.js
Client
function Client(svc, opts) { opts = opts || {}; events.EventEmitter.call(this); // We have to suffix all client properties to be safe, since the message // names aren't prefixed with clients (unlike servers). this._svc$ = svc; this._channels$ = []; // Active channels. this._fns$ = []; // Middleware functions. this._buffering$ = !!opts.buffering; this._cache$ = opts.cache || {}; // For backwards compatibility. this._policy$ = opts.channelPolicy; this._strict$ = !!opts.strictTypes; this._timeout$ = utils.getOption(opts, 'timeout', 10000); if (opts.remoteProtocols) { insertRemoteProtocols(this._cache$, opts.remoteProtocols, svc, true); } this._svc$.messages.forEach(function (msg) { this[msg.name] = this._createMessageHandler$(msg); }, this); }
javascript
function Client(svc, opts) { opts = opts || {}; events.EventEmitter.call(this); // We have to suffix all client properties to be safe, since the message // names aren't prefixed with clients (unlike servers). this._svc$ = svc; this._channels$ = []; // Active channels. this._fns$ = []; // Middleware functions. this._buffering$ = !!opts.buffering; this._cache$ = opts.cache || {}; // For backwards compatibility. this._policy$ = opts.channelPolicy; this._strict$ = !!opts.strictTypes; this._timeout$ = utils.getOption(opts, 'timeout', 10000); if (opts.remoteProtocols) { insertRemoteProtocols(this._cache$, opts.remoteProtocols, svc, true); } this._svc$.messages.forEach(function (msg) { this[msg.name] = this._createMessageHandler$(msg); }, this); }
[ "function", "Client", "(", "svc", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "// We have to suffix all client properties to be safe, since the message", "// names aren't prefixed with clients (unlike servers).", "this", ".", "_svc$", "=", "svc", ";", "this", ".", "_channels$", "=", "[", "]", ";", "// Active channels.", "this", ".", "_fns$", "=", "[", "]", ";", "// Middleware functions.", "this", ".", "_buffering$", "=", "!", "!", "opts", ".", "buffering", ";", "this", ".", "_cache$", "=", "opts", ".", "cache", "||", "{", "}", ";", "// For backwards compatibility.", "this", ".", "_policy$", "=", "opts", ".", "channelPolicy", ";", "this", ".", "_strict$", "=", "!", "!", "opts", ".", "strictTypes", ";", "this", ".", "_timeout$", "=", "utils", ".", "getOption", "(", "opts", ",", "'timeout'", ",", "10000", ")", ";", "if", "(", "opts", ".", "remoteProtocols", ")", "{", "insertRemoteProtocols", "(", "this", ".", "_cache$", ",", "opts", ".", "remoteProtocols", ",", "svc", ",", "true", ")", ";", "}", "this", ".", "_svc$", ".", "messages", ".", "forEach", "(", "function", "(", "msg", ")", "{", "this", "[", "msg", ".", "name", "]", "=", "this", ".", "_createMessageHandler$", "(", "msg", ")", ";", "}", ",", "this", ")", ";", "}" ]
Load-balanced message sender.
[ "Load", "-", "balanced", "message", "sender", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L457-L480
12,761
mtth/avsc
lib/services.js
Server
function Server(svc, opts) { opts = opts || {}; events.EventEmitter.call(this); this.service = svc; this._handlers = {}; this._fns = []; // Middleware functions. this._channels = {}; // Active channels. this._nextChannelId = 1; this._cache = opts.cache || {}; // Deprecated. this._defaultHandler = opts.defaultHandler; this._sysErrFormatter = opts.systemErrorFormatter; this._silent = !!opts.silent; this._strict = !!opts.strictTypes; if (opts.remoteProtocols) { insertRemoteProtocols(this._cache, opts.remoteProtocols, svc, false); } svc.messages.forEach(function (msg) { var name = msg.name; if (!opts.noCapitalize) { name = utils.capitalize(name); } this['on' + name] = this._createMessageHandler(msg); }, this); }
javascript
function Server(svc, opts) { opts = opts || {}; events.EventEmitter.call(this); this.service = svc; this._handlers = {}; this._fns = []; // Middleware functions. this._channels = {}; // Active channels. this._nextChannelId = 1; this._cache = opts.cache || {}; // Deprecated. this._defaultHandler = opts.defaultHandler; this._sysErrFormatter = opts.systemErrorFormatter; this._silent = !!opts.silent; this._strict = !!opts.strictTypes; if (opts.remoteProtocols) { insertRemoteProtocols(this._cache, opts.remoteProtocols, svc, false); } svc.messages.forEach(function (msg) { var name = msg.name; if (!opts.noCapitalize) { name = utils.capitalize(name); } this['on' + name] = this._createMessageHandler(msg); }, this); }
[ "function", "Server", "(", "svc", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "service", "=", "svc", ";", "this", ".", "_handlers", "=", "{", "}", ";", "this", ".", "_fns", "=", "[", "]", ";", "// Middleware functions.", "this", ".", "_channels", "=", "{", "}", ";", "// Active channels.", "this", ".", "_nextChannelId", "=", "1", ";", "this", ".", "_cache", "=", "opts", ".", "cache", "||", "{", "}", ";", "// Deprecated.", "this", ".", "_defaultHandler", "=", "opts", ".", "defaultHandler", ";", "this", ".", "_sysErrFormatter", "=", "opts", ".", "systemErrorFormatter", ";", "this", ".", "_silent", "=", "!", "!", "opts", ".", "silent", ";", "this", ".", "_strict", "=", "!", "!", "opts", ".", "strictTypes", ";", "if", "(", "opts", ".", "remoteProtocols", ")", "{", "insertRemoteProtocols", "(", "this", ".", "_cache", ",", "opts", ".", "remoteProtocols", ",", "svc", ",", "false", ")", ";", "}", "svc", ".", "messages", ".", "forEach", "(", "function", "(", "msg", ")", "{", "var", "name", "=", "msg", ".", "name", ";", "if", "(", "!", "opts", ".", "noCapitalize", ")", "{", "name", "=", "utils", ".", "capitalize", "(", "name", ")", ";", "}", "this", "[", "'on'", "+", "name", "]", "=", "this", ".", "_createMessageHandler", "(", "msg", ")", ";", "}", ",", "this", ")", ";", "}" ]
Message receiver.
[ "Message", "receiver", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L710-L737
12,762
mtth/avsc
lib/services.js
ClientChannel
function ClientChannel(client, opts) { opts = opts || {}; events.EventEmitter.call(this); this.client = client; this.timeout = utils.getOption(opts, 'timeout', client._timeout$); this._endWritable = !!utils.getOption(opts, 'endWritable', true); this._prefix = normalizedPrefix(opts.scope); var cache = client._cache$; var clientSvc = client._svc$; var hash = opts.serverHash; if (!hash) { hash = clientSvc.hash; } var adapter = cache[hash]; if (!adapter) { // This might happen even if the server hash option was set if the cache // doesn't contain the corresponding adapter. In this case we fall back to // the client's protocol (as mandated by the spec). hash = clientSvc.hash; adapter = cache[hash] = new Adapter(clientSvc, clientSvc, hash); } this._adapter = adapter; this._registry = new Registry(this, PREFIX_LENGTH); this.pending = 0; this.destroyed = false; this.draining = false; this.once('_eot', function (pending, err) { // Since this listener is only run once, we will only forward an error if // it is present during the initial `destroy` call, which is OK. debug('client channel EOT'); this.destroyed = true; this.emit('eot', pending, err); }); }
javascript
function ClientChannel(client, opts) { opts = opts || {}; events.EventEmitter.call(this); this.client = client; this.timeout = utils.getOption(opts, 'timeout', client._timeout$); this._endWritable = !!utils.getOption(opts, 'endWritable', true); this._prefix = normalizedPrefix(opts.scope); var cache = client._cache$; var clientSvc = client._svc$; var hash = opts.serverHash; if (!hash) { hash = clientSvc.hash; } var adapter = cache[hash]; if (!adapter) { // This might happen even if the server hash option was set if the cache // doesn't contain the corresponding adapter. In this case we fall back to // the client's protocol (as mandated by the spec). hash = clientSvc.hash; adapter = cache[hash] = new Adapter(clientSvc, clientSvc, hash); } this._adapter = adapter; this._registry = new Registry(this, PREFIX_LENGTH); this.pending = 0; this.destroyed = false; this.draining = false; this.once('_eot', function (pending, err) { // Since this listener is only run once, we will only forward an error if // it is present during the initial `destroy` call, which is OK. debug('client channel EOT'); this.destroyed = true; this.emit('eot', pending, err); }); }
[ "function", "ClientChannel", "(", "client", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "client", "=", "client", ";", "this", ".", "timeout", "=", "utils", ".", "getOption", "(", "opts", ",", "'timeout'", ",", "client", ".", "_timeout$", ")", ";", "this", ".", "_endWritable", "=", "!", "!", "utils", ".", "getOption", "(", "opts", ",", "'endWritable'", ",", "true", ")", ";", "this", ".", "_prefix", "=", "normalizedPrefix", "(", "opts", ".", "scope", ")", ";", "var", "cache", "=", "client", ".", "_cache$", ";", "var", "clientSvc", "=", "client", ".", "_svc$", ";", "var", "hash", "=", "opts", ".", "serverHash", ";", "if", "(", "!", "hash", ")", "{", "hash", "=", "clientSvc", ".", "hash", ";", "}", "var", "adapter", "=", "cache", "[", "hash", "]", ";", "if", "(", "!", "adapter", ")", "{", "// This might happen even if the server hash option was set if the cache", "// doesn't contain the corresponding adapter. In this case we fall back to", "// the client's protocol (as mandated by the spec).", "hash", "=", "clientSvc", ".", "hash", ";", "adapter", "=", "cache", "[", "hash", "]", "=", "new", "Adapter", "(", "clientSvc", ",", "clientSvc", ",", "hash", ")", ";", "}", "this", ".", "_adapter", "=", "adapter", ";", "this", ".", "_registry", "=", "new", "Registry", "(", "this", ",", "PREFIX_LENGTH", ")", ";", "this", ".", "pending", "=", "0", ";", "this", ".", "destroyed", "=", "false", ";", "this", ".", "draining", "=", "false", ";", "this", ".", "once", "(", "'_eot'", ",", "function", "(", "pending", ",", "err", ")", "{", "// Since this listener is only run once, we will only forward an error if", "// it is present during the initial `destroy` call, which is OK.", "debug", "(", "'client channel EOT'", ")", ";", "this", ".", "destroyed", "=", "true", ";", "this", ".", "emit", "(", "'eot'", ",", "pending", ",", "err", ")", ";", "}", ")", ";", "}" ]
Base message emitter class. See below for the two available variants.
[ "Base", "message", "emitter", "class", ".", "See", "below", "for", "the", "two", "available", "variants", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L864-L900
12,763
mtth/avsc
lib/services.js
StatelessClientChannel
function StatelessClientChannel(client, writableFactory, opts) { ClientChannel.call(this, client, opts); this._writableFactory = writableFactory; if (!opts || !opts.noPing) { // Ping the server to check whether the remote protocol is compatible. // If not, this will throw an error on the channel. debug('emitting ping request'); this.ping(); } }
javascript
function StatelessClientChannel(client, writableFactory, opts) { ClientChannel.call(this, client, opts); this._writableFactory = writableFactory; if (!opts || !opts.noPing) { // Ping the server to check whether the remote protocol is compatible. // If not, this will throw an error on the channel. debug('emitting ping request'); this.ping(); } }
[ "function", "StatelessClientChannel", "(", "client", ",", "writableFactory", ",", "opts", ")", "{", "ClientChannel", ".", "call", "(", "this", ",", "client", ",", "opts", ")", ";", "this", ".", "_writableFactory", "=", "writableFactory", ";", "if", "(", "!", "opts", "||", "!", "opts", ".", "noPing", ")", "{", "// Ping the server to check whether the remote protocol is compatible.", "// If not, this will throw an error on the channel.", "debug", "(", "'emitting ping request'", ")", ";", "this", ".", "ping", "(", ")", ";", "}", "}" ]
Factory-based client channel. This channel doesn't keep a persistent connection to the server and requires prepending a handshake to each message emitted. Usage examples include talking to an HTTP server (where the factory returns an HTTP request). Since each message will use its own writable/readable stream pair, the advantage of this channel is that it is able to keep track of which response corresponds to each request without relying on transport ordering. In particular, this means these channels are compatible with any server implementation.
[ "Factory", "-", "based", "client", "channel", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L1090-L1100
12,764
mtth/avsc
lib/services.js
onMessage
function onMessage(obj) { var id = obj.id; if (!self._matchesPrefix(id)) { debug('discarding unscoped message %s', id); return; } var cb = self._registry.get(id); if (cb) { process.nextTick(function () { debug('received message %s', id); // Ensure that the initial callback gets called asynchronously, even // for completely synchronous transports (otherwise the number of // pending requests will sometimes be inconsistent between stateful and // stateless transports). cb(null, Buffer.concat(obj.payload), self._adapter); }); } }
javascript
function onMessage(obj) { var id = obj.id; if (!self._matchesPrefix(id)) { debug('discarding unscoped message %s', id); return; } var cb = self._registry.get(id); if (cb) { process.nextTick(function () { debug('received message %s', id); // Ensure that the initial callback gets called asynchronously, even // for completely synchronous transports (otherwise the number of // pending requests will sometimes be inconsistent between stateful and // stateless transports). cb(null, Buffer.concat(obj.payload), self._adapter); }); } }
[ "function", "onMessage", "(", "obj", ")", "{", "var", "id", "=", "obj", ".", "id", ";", "if", "(", "!", "self", ".", "_matchesPrefix", "(", "id", ")", ")", "{", "debug", "(", "'discarding unscoped message %s'", ",", "id", ")", ";", "return", ";", "}", "var", "cb", "=", "self", ".", "_registry", ".", "get", "(", "id", ")", ";", "if", "(", "cb", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "debug", "(", "'received message %s'", ",", "id", ")", ";", "// Ensure that the initial callback gets called asynchronously, even", "// for completely synchronous transports (otherwise the number of", "// pending requests will sometimes be inconsistent between stateful and", "// stateless transports).", "cb", "(", "null", ",", "Buffer", ".", "concat", "(", "obj", ".", "payload", ")", ",", "self", ".", "_adapter", ")", ";", "}", ")", ";", "}", "}" ]
Callback used after a connection has been established.
[ "Callback", "used", "after", "a", "connection", "has", "been", "established", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L1267-L1284
12,765
mtth/avsc
lib/services.js
StatelessServerChannel
function StatelessServerChannel(server, readableFactory, opts) { ServerChannel.call(this, server, opts); this._writable = undefined; var self = this; var readable; process.nextTick(function () { // Delay listening to allow handlers to be attached even if the factory is // purely synchronous. readable = readableFactory.call(self, function (err, writable) { process.nextTick(function () { // We delay once more here in case this call is synchronous, to allow // the readable to always be populated first. if (err) { onFinish(err); return; } self._writable = writable.on('finish', onFinish); self.emit('_writable'); }); }).on('data', onRequest).on('end', onEnd); }); function onRequest(obj) { var id = obj.id; var buf = Buffer.concat(obj.payload); var err; try { var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf); var hreq = parts.head; var adapter = self._getAdapter(hreq); } catch (cause) { err = toRpcError('INVALID_HANDSHAKE_REQUEST', cause); } var hres = self._createHandshakeResponse(err, hreq); self.emit('handshake', hreq, hres); if (err) { done(self._encodeSystemError(err)); } else { self._receive(parts.tail, adapter, done); } function done(resBuf) { if (!self.destroyed) { if (!self._writable) { self.once('_writable', function () { done(resBuf); }); return; } self._writable.write({ id: id, payload: [HANDSHAKE_RESPONSE_TYPE.toBuffer(hres), resBuf] }); } if (self._writable && self._endWritable) { self._writable.end(); } } } function onEnd() { self.destroy(); } function onFinish(err) { readable .removeListener('data', onRequest) .removeListener('end', onEnd); self.destroy(err || true); } }
javascript
function StatelessServerChannel(server, readableFactory, opts) { ServerChannel.call(this, server, opts); this._writable = undefined; var self = this; var readable; process.nextTick(function () { // Delay listening to allow handlers to be attached even if the factory is // purely synchronous. readable = readableFactory.call(self, function (err, writable) { process.nextTick(function () { // We delay once more here in case this call is synchronous, to allow // the readable to always be populated first. if (err) { onFinish(err); return; } self._writable = writable.on('finish', onFinish); self.emit('_writable'); }); }).on('data', onRequest).on('end', onEnd); }); function onRequest(obj) { var id = obj.id; var buf = Buffer.concat(obj.payload); var err; try { var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf); var hreq = parts.head; var adapter = self._getAdapter(hreq); } catch (cause) { err = toRpcError('INVALID_HANDSHAKE_REQUEST', cause); } var hres = self._createHandshakeResponse(err, hreq); self.emit('handshake', hreq, hres); if (err) { done(self._encodeSystemError(err)); } else { self._receive(parts.tail, adapter, done); } function done(resBuf) { if (!self.destroyed) { if (!self._writable) { self.once('_writable', function () { done(resBuf); }); return; } self._writable.write({ id: id, payload: [HANDSHAKE_RESPONSE_TYPE.toBuffer(hres), resBuf] }); } if (self._writable && self._endWritable) { self._writable.end(); } } } function onEnd() { self.destroy(); } function onFinish(err) { readable .removeListener('data', onRequest) .removeListener('end', onEnd); self.destroy(err || true); } }
[ "function", "StatelessServerChannel", "(", "server", ",", "readableFactory", ",", "opts", ")", "{", "ServerChannel", ".", "call", "(", "this", ",", "server", ",", "opts", ")", ";", "this", ".", "_writable", "=", "undefined", ";", "var", "self", "=", "this", ";", "var", "readable", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "// Delay listening to allow handlers to be attached even if the factory is", "// purely synchronous.", "readable", "=", "readableFactory", ".", "call", "(", "self", ",", "function", "(", "err", ",", "writable", ")", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "// We delay once more here in case this call is synchronous, to allow", "// the readable to always be populated first.", "if", "(", "err", ")", "{", "onFinish", "(", "err", ")", ";", "return", ";", "}", "self", ".", "_writable", "=", "writable", ".", "on", "(", "'finish'", ",", "onFinish", ")", ";", "self", ".", "emit", "(", "'_writable'", ")", ";", "}", ")", ";", "}", ")", ".", "on", "(", "'data'", ",", "onRequest", ")", ".", "on", "(", "'end'", ",", "onEnd", ")", ";", "}", ")", ";", "function", "onRequest", "(", "obj", ")", "{", "var", "id", "=", "obj", ".", "id", ";", "var", "buf", "=", "Buffer", ".", "concat", "(", "obj", ".", "payload", ")", ";", "var", "err", ";", "try", "{", "var", "parts", "=", "readHead", "(", "HANDSHAKE_REQUEST_TYPE", ",", "buf", ")", ";", "var", "hreq", "=", "parts", ".", "head", ";", "var", "adapter", "=", "self", ".", "_getAdapter", "(", "hreq", ")", ";", "}", "catch", "(", "cause", ")", "{", "err", "=", "toRpcError", "(", "'INVALID_HANDSHAKE_REQUEST'", ",", "cause", ")", ";", "}", "var", "hres", "=", "self", ".", "_createHandshakeResponse", "(", "err", ",", "hreq", ")", ";", "self", ".", "emit", "(", "'handshake'", ",", "hreq", ",", "hres", ")", ";", "if", "(", "err", ")", "{", "done", "(", "self", ".", "_encodeSystemError", "(", "err", ")", ")", ";", "}", "else", "{", "self", ".", "_receive", "(", "parts", ".", "tail", ",", "adapter", ",", "done", ")", ";", "}", "function", "done", "(", "resBuf", ")", "{", "if", "(", "!", "self", ".", "destroyed", ")", "{", "if", "(", "!", "self", ".", "_writable", ")", "{", "self", ".", "once", "(", "'_writable'", ",", "function", "(", ")", "{", "done", "(", "resBuf", ")", ";", "}", ")", ";", "return", ";", "}", "self", ".", "_writable", ".", "write", "(", "{", "id", ":", "id", ",", "payload", ":", "[", "HANDSHAKE_RESPONSE_TYPE", ".", "toBuffer", "(", "hres", ")", ",", "resBuf", "]", "}", ")", ";", "}", "if", "(", "self", ".", "_writable", "&&", "self", ".", "_endWritable", ")", "{", "self", ".", "_writable", ".", "end", "(", ")", ";", "}", "}", "}", "function", "onEnd", "(", ")", "{", "self", ".", "destroy", "(", ")", ";", "}", "function", "onFinish", "(", "err", ")", "{", "readable", ".", "removeListener", "(", "'data'", ",", "onRequest", ")", ".", "removeListener", "(", "'end'", ",", "onEnd", ")", ";", "self", ".", "destroy", "(", "err", "||", "true", ")", ";", "}", "}" ]
Server channel for stateless transport. This channel expect a handshake to precede each message.
[ "Server", "channel", "for", "stateless", "transport", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L1605-L1675
12,766
mtth/avsc
lib/services.js
WrappedRequest
function WrappedRequest(msg, hdrs, req) { this._msg = msg; this.headers = hdrs || {}; this.request = req || {}; }
javascript
function WrappedRequest(msg, hdrs, req) { this._msg = msg; this.headers = hdrs || {}; this.request = req || {}; }
[ "function", "WrappedRequest", "(", "msg", ",", "hdrs", ",", "req", ")", "{", "this", ".", "_msg", "=", "msg", ";", "this", ".", "headers", "=", "hdrs", "||", "{", "}", ";", "this", ".", "request", "=", "req", "||", "{", "}", ";", "}" ]
Helpers. Enhanced request, used inside forward middleware functions.
[ "Helpers", ".", "Enhanced", "request", "used", "inside", "forward", "middleware", "functions", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L1769-L1773
12,767
mtth/avsc
lib/services.js
WrappedResponse
function WrappedResponse(msg, hdr, err, res) { this._msg = msg; this.headers = hdr; this.error = err; this.response = res; }
javascript
function WrappedResponse(msg, hdr, err, res) { this._msg = msg; this.headers = hdr; this.error = err; this.response = res; }
[ "function", "WrappedResponse", "(", "msg", ",", "hdr", ",", "err", ",", "res", ")", "{", "this", ".", "_msg", "=", "msg", ";", "this", ".", "headers", "=", "hdr", ";", "this", ".", "error", "=", "err", ";", "this", ".", "response", "=", "res", ";", "}" ]
Enhanced response, used inside forward middleware functions.
[ "Enhanced", "response", "used", "inside", "forward", "middleware", "functions", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L1785-L1790
12,768
mtth/avsc
lib/services.js
CallContext
function CallContext(msg, channel) { this.channel = channel; this.locals = {}; this.message = msg; Object.freeze(this); }
javascript
function CallContext(msg, channel) { this.channel = channel; this.locals = {}; this.message = msg; Object.freeze(this); }
[ "function", "CallContext", "(", "msg", ",", "channel", ")", "{", "this", ".", "channel", "=", "channel", ";", "this", ".", "locals", "=", "{", "}", ";", "this", ".", "message", "=", "msg", ";", "Object", ".", "freeze", "(", "this", ")", ";", "}" ]
Context for all middleware and handlers. It exposes a `locals` object which can be used to pass information between each other during a given call.
[ "Context", "for", "all", "middleware", "and", "handlers", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L1810-L1815
12,769
mtth/avsc
lib/services.js
Registry
function Registry(ctx, prefixLength) { this._ctx = ctx; // Context for all callbacks. this._mask = ~0 >>> (prefixLength | 0); // 16 bits by default. this._id = 0; // Unique integer ID for each call. this._n = 0; // Number of pending calls. this._cbs = {}; }
javascript
function Registry(ctx, prefixLength) { this._ctx = ctx; // Context for all callbacks. this._mask = ~0 >>> (prefixLength | 0); // 16 bits by default. this._id = 0; // Unique integer ID for each call. this._n = 0; // Number of pending calls. this._cbs = {}; }
[ "function", "Registry", "(", "ctx", ",", "prefixLength", ")", "{", "this", ".", "_ctx", "=", "ctx", ";", "// Context for all callbacks.", "this", ".", "_mask", "=", "~", "0", ">>>", "(", "prefixLength", "|", "0", ")", ";", "// 16 bits by default.", "this", ".", "_id", "=", "0", ";", "// Unique integer ID for each call.", "this", ".", "_n", "=", "0", ";", "// Number of pending calls.", "this", ".", "_cbs", "=", "{", "}", ";", "}" ]
Callback registry. Callbacks added must accept an error as first argument. This is used by client channels to store pending calls. This class isn't exposed by the public API.
[ "Callback", "registry", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L1824-L1830
12,770
mtth/avsc
lib/services.js
Adapter
function Adapter(clientSvc, serverSvc, hash, isRemote) { this._clientSvc = clientSvc; this._serverSvc = serverSvc; this._hash = hash; // Convenience to access it when creating handshakes. this._isRemote = !!isRemote; this._readers = createReaders(clientSvc, serverSvc); }
javascript
function Adapter(clientSvc, serverSvc, hash, isRemote) { this._clientSvc = clientSvc; this._serverSvc = serverSvc; this._hash = hash; // Convenience to access it when creating handshakes. this._isRemote = !!isRemote; this._readers = createReaders(clientSvc, serverSvc); }
[ "function", "Adapter", "(", "clientSvc", ",", "serverSvc", ",", "hash", ",", "isRemote", ")", "{", "this", ".", "_clientSvc", "=", "clientSvc", ";", "this", ".", "_serverSvc", "=", "serverSvc", ";", "this", ".", "_hash", "=", "hash", ";", "// Convenience to access it when creating handshakes.", "this", ".", "_isRemote", "=", "!", "!", "isRemote", ";", "this", ".", "_readers", "=", "createReaders", "(", "clientSvc", ",", "serverSvc", ")", ";", "}" ]
Service resolution helper. It is used both by client and server channels, to respectively decode errors and responses, or requests.
[ "Service", "resolution", "helper", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L1874-L1880
12,771
mtth/avsc
lib/services.js
FrameDecoder
function FrameDecoder() { stream.Transform.call(this, {readableObjectMode: true}); this._id = undefined; this._buf = utils.newBuffer(0); this._bufs = []; this.on('finish', function () { this.push(null); }); }
javascript
function FrameDecoder() { stream.Transform.call(this, {readableObjectMode: true}); this._id = undefined; this._buf = utils.newBuffer(0); this._bufs = []; this.on('finish', function () { this.push(null); }); }
[ "function", "FrameDecoder", "(", ")", "{", "stream", ".", "Transform", ".", "call", "(", "this", ",", "{", "readableObjectMode", ":", "true", "}", ")", ";", "this", ".", "_id", "=", "undefined", ";", "this", ".", "_buf", "=", "utils", ".", "newBuffer", "(", "0", ")", ";", "this", ".", "_bufs", "=", "[", "]", ";", "this", ".", "on", "(", "'finish'", ",", "function", "(", ")", "{", "this", ".", "push", "(", "null", ")", ";", "}", ")", ";", "}" ]
Standard "un-framing" stream.
[ "Standard", "un", "-", "framing", "stream", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L1921-L1928
12,772
mtth/avsc
lib/services.js
readHead
function readHead(type, buf) { var tap = new Tap(buf); var head = type._read(tap); if (!tap.isValid()) { throw new Error(f('truncated %j', type.schema())); } return {head: head, tail: tap.buf.slice(tap.pos)}; }
javascript
function readHead(type, buf) { var tap = new Tap(buf); var head = type._read(tap); if (!tap.isValid()) { throw new Error(f('truncated %j', type.schema())); } return {head: head, tail: tap.buf.slice(tap.pos)}; }
[ "function", "readHead", "(", "type", ",", "buf", ")", "{", "var", "tap", "=", "new", "Tap", "(", "buf", ")", ";", "var", "head", "=", "type", ".", "_read", "(", "tap", ")", ";", "if", "(", "!", "tap", ".", "isValid", "(", ")", ")", "{", "throw", "new", "Error", "(", "f", "(", "'truncated %j'", ",", "type", ".", "schema", "(", ")", ")", ")", ";", "}", "return", "{", "head", ":", "head", ",", "tail", ":", "tap", ".", "buf", ".", "slice", "(", "tap", ".", "pos", ")", "}", ";", "}" ]
Decode a type used as prefix inside a buffer. @param type {Type} The type of the prefix. @param buf {Buffer} Encoded bytes. This function will return an object `{head, tail}` where head contains the decoded value and tail the rest of the buffer. An error will be thrown if the prefix cannot be decoded.
[ "Decode", "a", "type", "used", "as", "prefix", "inside", "a", "buffer", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2082-L2089
12,773
mtth/avsc
lib/services.js
createReader
function createReader(rtype, wtype) { return rtype.equals(wtype) ? rtype : rtype.createResolver(wtype); }
javascript
function createReader(rtype, wtype) { return rtype.equals(wtype) ? rtype : rtype.createResolver(wtype); }
[ "function", "createReader", "(", "rtype", ",", "wtype", ")", "{", "return", "rtype", ".", "equals", "(", "wtype", ")", "?", "rtype", ":", "rtype", ".", "createResolver", "(", "wtype", ")", ";", "}" ]
Generate a decoder, optimizing the case where reader and writer are equal. @param rtype {Type} Reader's type. @param wtype {Type} Writer's type.
[ "Generate", "a", "decoder", "optimizing", "the", "case", "where", "reader", "and", "writer", "are", "equal", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2097-L2099
12,774
mtth/avsc
lib/services.js
createReaders
function createReaders(clientSvc, serverSvc) { var obj = {}; clientSvc.messages.forEach(function (c) { var n = c.name; var s = serverSvc.message(n); try { if (!s) { throw new Error(f('missing server message: %s', n)); } if (s.oneWay !== c.oneWay) { throw new Error(f('inconsistent one-way message: %s', n)); } obj[n + '?'] = createReader(s.requestType, c.requestType); obj[n + '*'] = createReader(c.errorType, s.errorType); obj[n + '!'] = createReader(c.responseType, s.responseType); } catch (cause) { throw toRpcError('INCOMPATIBLE_PROTOCOL', cause); } }); return obj; }
javascript
function createReaders(clientSvc, serverSvc) { var obj = {}; clientSvc.messages.forEach(function (c) { var n = c.name; var s = serverSvc.message(n); try { if (!s) { throw new Error(f('missing server message: %s', n)); } if (s.oneWay !== c.oneWay) { throw new Error(f('inconsistent one-way message: %s', n)); } obj[n + '?'] = createReader(s.requestType, c.requestType); obj[n + '*'] = createReader(c.errorType, s.errorType); obj[n + '!'] = createReader(c.responseType, s.responseType); } catch (cause) { throw toRpcError('INCOMPATIBLE_PROTOCOL', cause); } }); return obj; }
[ "function", "createReaders", "(", "clientSvc", ",", "serverSvc", ")", "{", "var", "obj", "=", "{", "}", ";", "clientSvc", ".", "messages", ".", "forEach", "(", "function", "(", "c", ")", "{", "var", "n", "=", "c", ".", "name", ";", "var", "s", "=", "serverSvc", ".", "message", "(", "n", ")", ";", "try", "{", "if", "(", "!", "s", ")", "{", "throw", "new", "Error", "(", "f", "(", "'missing server message: %s'", ",", "n", ")", ")", ";", "}", "if", "(", "s", ".", "oneWay", "!==", "c", ".", "oneWay", ")", "{", "throw", "new", "Error", "(", "f", "(", "'inconsistent one-way message: %s'", ",", "n", ")", ")", ";", "}", "obj", "[", "n", "+", "'?'", "]", "=", "createReader", "(", "s", ".", "requestType", ",", "c", ".", "requestType", ")", ";", "obj", "[", "n", "+", "'*'", "]", "=", "createReader", "(", "c", ".", "errorType", ",", "s", ".", "errorType", ")", ";", "obj", "[", "n", "+", "'!'", "]", "=", "createReader", "(", "c", ".", "responseType", ",", "s", ".", "responseType", ")", ";", "}", "catch", "(", "cause", ")", "{", "throw", "toRpcError", "(", "'INCOMPATIBLE_PROTOCOL'", ",", "cause", ")", ";", "}", "}", ")", ";", "return", "obj", ";", "}" ]
Generate all readers for a given protocol combination. @param clientSvc {Service} Client service. @param serverSvc {Service} Client service.
[ "Generate", "all", "readers", "for", "a", "given", "protocol", "combination", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2107-L2127
12,775
mtth/avsc
lib/services.js
insertRemoteProtocols
function insertRemoteProtocols(cache, ptcls, svc, isClient) { Object.keys(ptcls).forEach(function (hash) { var ptcl = ptcls[hash]; var clientSvc, serverSvc; if (isClient) { clientSvc = svc; serverSvc = Service.forProtocol(ptcl); } else { clientSvc = Service.forProtocol(ptcl); serverSvc = svc; } cache[hash] = new Adapter(clientSvc, serverSvc, hash, true); }); }
javascript
function insertRemoteProtocols(cache, ptcls, svc, isClient) { Object.keys(ptcls).forEach(function (hash) { var ptcl = ptcls[hash]; var clientSvc, serverSvc; if (isClient) { clientSvc = svc; serverSvc = Service.forProtocol(ptcl); } else { clientSvc = Service.forProtocol(ptcl); serverSvc = svc; } cache[hash] = new Adapter(clientSvc, serverSvc, hash, true); }); }
[ "function", "insertRemoteProtocols", "(", "cache", ",", "ptcls", ",", "svc", ",", "isClient", ")", "{", "Object", ".", "keys", "(", "ptcls", ")", ".", "forEach", "(", "function", "(", "hash", ")", "{", "var", "ptcl", "=", "ptcls", "[", "hash", "]", ";", "var", "clientSvc", ",", "serverSvc", ";", "if", "(", "isClient", ")", "{", "clientSvc", "=", "svc", ";", "serverSvc", "=", "Service", ".", "forProtocol", "(", "ptcl", ")", ";", "}", "else", "{", "clientSvc", "=", "Service", ".", "forProtocol", "(", "ptcl", ")", ";", "serverSvc", "=", "svc", ";", "}", "cache", "[", "hash", "]", "=", "new", "Adapter", "(", "clientSvc", ",", "serverSvc", ",", "hash", ",", "true", ")", ";", "}", ")", ";", "}" ]
Populate a cache from a list of protocols. @param cache {Object} Cache of adapters. @param svc {Service} The local service (either client or server). @param ptcls {Array} Array of protocols to insert. @param isClient {Boolean} Whether the local service is a client's or server's.
[ "Populate", "a", "cache", "from", "a", "list", "of", "protocols", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2138-L2151
12,776
mtth/avsc
lib/services.js
getRemoteProtocols
function getRemoteProtocols(cache, isClient) { var ptcls = {}; Object.keys(cache).forEach(function (hs) { var adapter = cache[hs]; if (adapter._isRemote) { var svc = isClient ? adapter._serverSvc : adapter._clientSvc; ptcls[hs] = svc.protocol; } }); return ptcls; }
javascript
function getRemoteProtocols(cache, isClient) { var ptcls = {}; Object.keys(cache).forEach(function (hs) { var adapter = cache[hs]; if (adapter._isRemote) { var svc = isClient ? adapter._serverSvc : adapter._clientSvc; ptcls[hs] = svc.protocol; } }); return ptcls; }
[ "function", "getRemoteProtocols", "(", "cache", ",", "isClient", ")", "{", "var", "ptcls", "=", "{", "}", ";", "Object", ".", "keys", "(", "cache", ")", ".", "forEach", "(", "function", "(", "hs", ")", "{", "var", "adapter", "=", "cache", "[", "hs", "]", ";", "if", "(", "adapter", ".", "_isRemote", ")", "{", "var", "svc", "=", "isClient", "?", "adapter", ".", "_serverSvc", ":", "adapter", ".", "_clientSvc", ";", "ptcls", "[", "hs", "]", "=", "svc", ".", "protocol", ";", "}", "}", ")", ";", "return", "ptcls", ";", "}" ]
Extract remote protocols from a cache @param cache {Object} Cache of adapters. @param isClient {Boolean} Whether the remote protocols extracted should be the servers' or clients'.
[ "Extract", "remote", "protocols", "from", "a", "cache" ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2160-L2170
12,777
mtth/avsc
lib/services.js
forwardErrors
function forwardErrors(src, dst) { return src.on('error', function (err) { dst.emit('error', err, src); }); }
javascript
function forwardErrors(src, dst) { return src.on('error', function (err) { dst.emit('error', err, src); }); }
[ "function", "forwardErrors", "(", "src", ",", "dst", ")", "{", "return", "src", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "dst", ".", "emit", "(", "'error'", ",", "err", ",", "src", ")", ";", "}", ")", ";", "}" ]
Forward any errors emitted on the source to the destination. @param src {EventEmitter} The initial source of error events. @param dst {EventEmitter} The new target of the source's error events. The original source will be provided as second argument (the error being the first). As a convenience, the source will be returned.
[ "Forward", "any", "errors", "emitted", "on", "the", "source", "to", "the", "destination", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2192-L2196
12,778
mtth/avsc
lib/services.js
toError
function toError(msg, cause) { var err = new Error(msg); err.cause = cause; return err; }
javascript
function toError(msg, cause) { var err = new Error(msg); err.cause = cause; return err; }
[ "function", "toError", "(", "msg", ",", "cause", ")", "{", "var", "err", "=", "new", "Error", "(", "msg", ")", ";", "err", ".", "cause", "=", "cause", ";", "return", "err", ";", "}" ]
Create an error. @param msg {String} Error message. @param cause {Error} The cause of the error. It is available as `cause` field on the outer error.
[ "Create", "an", "error", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2205-L2209
12,779
mtth/avsc
lib/services.js
toRpcError
function toRpcError(rpcCode, cause) { var err = toError(rpcCode.toLowerCase().replace(/_/g, ' '), cause); err.rpcCode = (cause && cause.rpcCode) ? cause.rpcCode : rpcCode; return err; }
javascript
function toRpcError(rpcCode, cause) { var err = toError(rpcCode.toLowerCase().replace(/_/g, ' '), cause); err.rpcCode = (cause && cause.rpcCode) ? cause.rpcCode : rpcCode; return err; }
[ "function", "toRpcError", "(", "rpcCode", ",", "cause", ")", "{", "var", "err", "=", "toError", "(", "rpcCode", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "_", "/", "g", ",", "' '", ")", ",", "cause", ")", ";", "err", ".", "rpcCode", "=", "(", "cause", "&&", "cause", ".", "rpcCode", ")", "?", "cause", ".", "rpcCode", ":", "rpcCode", ";", "return", "err", ";", "}" ]
Mark an error. @param rpcCode {String} Code representing the failure. @param cause {Error} The cause of the error. It is available as `cause` field on the outer error. This is used to keep the argument of channels' `'error'` event errors.
[ "Mark", "an", "error", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2220-L2224
12,780
mtth/avsc
lib/services.js
serializationError
function serializationError(msg, obj, fields) { var details = []; var i, l, field; for (i = 0, l = fields.length; i < l; i++) { field = fields[i]; field.type.isValid(obj[field.name], {errorHook: errorHook}); } var detailsStr = details .map(function (obj) { return f('%s = %j but expected %s', obj.path, obj.value, obj.type); }) .join(', '); var err = new Error(f('%s (%s)', msg, detailsStr)); err.details = details; return err; function errorHook(parts, any, type) { var strs = []; var i, l, part; for (i = 0, l = parts.length; i < l; i++) { part = parts[i]; if (isNaN(part)) { strs.push('.' + part); } else { strs.push('[' + part + ']'); } } details.push({ path: field.name + strs.join(''), value: any, type: type }); } }
javascript
function serializationError(msg, obj, fields) { var details = []; var i, l, field; for (i = 0, l = fields.length; i < l; i++) { field = fields[i]; field.type.isValid(obj[field.name], {errorHook: errorHook}); } var detailsStr = details .map(function (obj) { return f('%s = %j but expected %s', obj.path, obj.value, obj.type); }) .join(', '); var err = new Error(f('%s (%s)', msg, detailsStr)); err.details = details; return err; function errorHook(parts, any, type) { var strs = []; var i, l, part; for (i = 0, l = parts.length; i < l; i++) { part = parts[i]; if (isNaN(part)) { strs.push('.' + part); } else { strs.push('[' + part + ']'); } } details.push({ path: field.name + strs.join(''), value: any, type: type }); } }
[ "function", "serializationError", "(", "msg", ",", "obj", ",", "fields", ")", "{", "var", "details", "=", "[", "]", ";", "var", "i", ",", "l", ",", "field", ";", "for", "(", "i", "=", "0", ",", "l", "=", "fields", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "field", "=", "fields", "[", "i", "]", ";", "field", ".", "type", ".", "isValid", "(", "obj", "[", "field", ".", "name", "]", ",", "{", "errorHook", ":", "errorHook", "}", ")", ";", "}", "var", "detailsStr", "=", "details", ".", "map", "(", "function", "(", "obj", ")", "{", "return", "f", "(", "'%s = %j but expected %s'", ",", "obj", ".", "path", ",", "obj", ".", "value", ",", "obj", ".", "type", ")", ";", "}", ")", ".", "join", "(", "', '", ")", ";", "var", "err", "=", "new", "Error", "(", "f", "(", "'%s (%s)'", ",", "msg", ",", "detailsStr", ")", ")", ";", "err", ".", "details", "=", "details", ";", "return", "err", ";", "function", "errorHook", "(", "parts", ",", "any", ",", "type", ")", "{", "var", "strs", "=", "[", "]", ";", "var", "i", ",", "l", ",", "part", ";", "for", "(", "i", "=", "0", ",", "l", "=", "parts", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "part", "=", "parts", "[", "i", "]", ";", "if", "(", "isNaN", "(", "part", ")", ")", "{", "strs", ".", "push", "(", "'.'", "+", "part", ")", ";", "}", "else", "{", "strs", ".", "push", "(", "'['", "+", "part", "+", "']'", ")", ";", "}", "}", "details", ".", "push", "(", "{", "path", ":", "field", ".", "name", "+", "strs", ".", "join", "(", "''", ")", ",", "value", ":", "any", ",", "type", ":", "type", "}", ")", ";", "}", "}" ]
Provide a helpful error to identify why serialization failed. @param err {Error} The error to decorate. @param obj {...} The object containing fields to validated. @param fields {Array} Information about the fields to validate.
[ "Provide", "a", "helpful", "error", "to", "identify", "why", "serialization", "failed", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2233-L2266
12,781
mtth/avsc
lib/services.js
getExistingMessage
function getExistingMessage(svc, name) { var msg = svc.message(name); if (!msg) { throw new Error(f('unknown message: %s', name)); } return msg; }
javascript
function getExistingMessage(svc, name) { var msg = svc.message(name); if (!msg) { throw new Error(f('unknown message: %s', name)); } return msg; }
[ "function", "getExistingMessage", "(", "svc", ",", "name", ")", "{", "var", "msg", "=", "svc", ".", "message", "(", "name", ")", ";", "if", "(", "!", "msg", ")", "{", "throw", "new", "Error", "(", "f", "(", "'unknown message: %s'", ",", "name", ")", ")", ";", "}", "return", "msg", ";", "}" ]
Get a message, asserting that it exists. @param svc {Service} The protocol to look into. @param name {String} The message's name.
[ "Get", "a", "message", "asserting", "that", "it", "exists", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2308-L2314
12,782
mtth/avsc
lib/services.js
chainMiddleware
function chainMiddleware(params) { var args = [params.wreq, params.wres]; var cbs = []; var cause; // Backpropagated error. forward(0); function forward(pos) { var isDone = false; if (pos < params.fns.length) { params.fns[pos].apply(params.ctx, args.concat(function (err, cb) { if (isDone) { params.onError(toError('duplicate forward middleware call', err)); return; } isDone = true; if ( err || ( params.wres && ( // Non one-way messages. params.wres.error !== undefined || params.wres.response !== undefined ) ) ) { // Stop the forward phase, bypass the handler, and start the backward // phase. Note that we ignore any callback argument in this case. cause = err; backward(); return; } if (cb) { cbs.push(cb); } forward(++pos); })); } else { // Done with the middleware forward functions, call the handler. params.onTransition.apply(params.ctx, args.concat(function (err) { if (isDone) { params.onError(toError('duplicate handler call', err)); return; } isDone = true; cause = err; process.nextTick(backward); })); } } function backward() { var cb = cbs.pop(); if (cb) { var isDone = false; cb.call(params.ctx, cause, function (err) { if (isDone) { params.onError(toError('duplicate backward middleware call', err)); return; } // Substitute the error. cause = err; isDone = true; backward(); }); } else { // Done with all middleware calls. params.onCompletion.call(params.ctx, cause); } } }
javascript
function chainMiddleware(params) { var args = [params.wreq, params.wres]; var cbs = []; var cause; // Backpropagated error. forward(0); function forward(pos) { var isDone = false; if (pos < params.fns.length) { params.fns[pos].apply(params.ctx, args.concat(function (err, cb) { if (isDone) { params.onError(toError('duplicate forward middleware call', err)); return; } isDone = true; if ( err || ( params.wres && ( // Non one-way messages. params.wres.error !== undefined || params.wres.response !== undefined ) ) ) { // Stop the forward phase, bypass the handler, and start the backward // phase. Note that we ignore any callback argument in this case. cause = err; backward(); return; } if (cb) { cbs.push(cb); } forward(++pos); })); } else { // Done with the middleware forward functions, call the handler. params.onTransition.apply(params.ctx, args.concat(function (err) { if (isDone) { params.onError(toError('duplicate handler call', err)); return; } isDone = true; cause = err; process.nextTick(backward); })); } } function backward() { var cb = cbs.pop(); if (cb) { var isDone = false; cb.call(params.ctx, cause, function (err) { if (isDone) { params.onError(toError('duplicate backward middleware call', err)); return; } // Substitute the error. cause = err; isDone = true; backward(); }); } else { // Done with all middleware calls. params.onCompletion.call(params.ctx, cause); } } }
[ "function", "chainMiddleware", "(", "params", ")", "{", "var", "args", "=", "[", "params", ".", "wreq", ",", "params", ".", "wres", "]", ";", "var", "cbs", "=", "[", "]", ";", "var", "cause", ";", "// Backpropagated error.", "forward", "(", "0", ")", ";", "function", "forward", "(", "pos", ")", "{", "var", "isDone", "=", "false", ";", "if", "(", "pos", "<", "params", ".", "fns", ".", "length", ")", "{", "params", ".", "fns", "[", "pos", "]", ".", "apply", "(", "params", ".", "ctx", ",", "args", ".", "concat", "(", "function", "(", "err", ",", "cb", ")", "{", "if", "(", "isDone", ")", "{", "params", ".", "onError", "(", "toError", "(", "'duplicate forward middleware call'", ",", "err", ")", ")", ";", "return", ";", "}", "isDone", "=", "true", ";", "if", "(", "err", "||", "(", "params", ".", "wres", "&&", "(", "// Non one-way messages.", "params", ".", "wres", ".", "error", "!==", "undefined", "||", "params", ".", "wres", ".", "response", "!==", "undefined", ")", ")", ")", "{", "// Stop the forward phase, bypass the handler, and start the backward", "// phase. Note that we ignore any callback argument in this case.", "cause", "=", "err", ";", "backward", "(", ")", ";", "return", ";", "}", "if", "(", "cb", ")", "{", "cbs", ".", "push", "(", "cb", ")", ";", "}", "forward", "(", "++", "pos", ")", ";", "}", ")", ")", ";", "}", "else", "{", "// Done with the middleware forward functions, call the handler.", "params", ".", "onTransition", ".", "apply", "(", "params", ".", "ctx", ",", "args", ".", "concat", "(", "function", "(", "err", ")", "{", "if", "(", "isDone", ")", "{", "params", ".", "onError", "(", "toError", "(", "'duplicate handler call'", ",", "err", ")", ")", ";", "return", ";", "}", "isDone", "=", "true", ";", "cause", "=", "err", ";", "process", ".", "nextTick", "(", "backward", ")", ";", "}", ")", ")", ";", "}", "}", "function", "backward", "(", ")", "{", "var", "cb", "=", "cbs", ".", "pop", "(", ")", ";", "if", "(", "cb", ")", "{", "var", "isDone", "=", "false", ";", "cb", ".", "call", "(", "params", ".", "ctx", ",", "cause", ",", "function", "(", "err", ")", "{", "if", "(", "isDone", ")", "{", "params", ".", "onError", "(", "toError", "(", "'duplicate backward middleware call'", ",", "err", ")", ")", ";", "return", ";", "}", "// Substitute the error.", "cause", "=", "err", ";", "isDone", "=", "true", ";", "backward", "(", ")", ";", "}", ")", ";", "}", "else", "{", "// Done with all middleware calls.", "params", ".", "onCompletion", ".", "call", "(", "params", ".", "ctx", ",", "cause", ")", ";", "}", "}", "}" ]
Middleware logic. This is used both in clients and servers to intercept call handling (e.g. to populate headers, do access control). @param params {Object} The following parameters: + fns {Array} Array of middleware functions. + ctx {Object} Context used to call the middleware functions, onTransition, and onCompletion. + wreq {WrappedRequest} + wres {WrappedResponse} + onTransition {Function} End of forward phase callback. It accepts an eventual error as single argument. This will be used for the backward phase. This function is guaranteed to be called at most once. + onCompletion {Function} Final handler, it takes an error as unique argument. This function is guaranteed to be only at most once. + onError {Function} Error handler, called if an intermediate callback is called multiple times.
[ "Middleware", "logic", "." ]
d4e62f360b8f27c4b95372cac58c95157f87865a
https://github.com/mtth/avsc/blob/d4e62f360b8f27c4b95372cac58c95157f87865a/lib/services.js#L2336-L2403
12,783
joshswan/react-native-globalize
lib/globalize.js
getAvailableLocales
function getAvailableLocales() { if (Cldr._raw && Cldr._raw.main) { return Object.keys(Cldr._raw.main); } return []; }
javascript
function getAvailableLocales() { if (Cldr._raw && Cldr._raw.main) { return Object.keys(Cldr._raw.main); } return []; }
[ "function", "getAvailableLocales", "(", ")", "{", "if", "(", "Cldr", ".", "_raw", "&&", "Cldr", ".", "_raw", ".", "main", ")", "{", "return", "Object", ".", "keys", "(", "Cldr", ".", "_raw", ".", "main", ")", ";", "}", "return", "[", "]", ";", "}" ]
Get array of available locales
[ "Get", "array", "of", "available", "locales" ]
a753910a0b0c498085ba9c3f71db8f21fa9dc81b
https://github.com/joshswan/react-native-globalize/blob/a753910a0b0c498085ba9c3f71db8f21fa9dc81b/lib/globalize.js#L29-L35
12,784
joshswan/react-native-globalize
lib/globalize.js
findFallbackLocale
function findFallbackLocale(locale) { const locales = getAvailableLocales(); for (let i = locale.length - 1; i > 1; i -= 1) { const key = locale.substring(0, i); if (locales.includes(key)) { return key; } } return null; }
javascript
function findFallbackLocale(locale) { const locales = getAvailableLocales(); for (let i = locale.length - 1; i > 1; i -= 1) { const key = locale.substring(0, i); if (locales.includes(key)) { return key; } } return null; }
[ "function", "findFallbackLocale", "(", "locale", ")", "{", "const", "locales", "=", "getAvailableLocales", "(", ")", ";", "for", "(", "let", "i", "=", "locale", ".", "length", "-", "1", ";", "i", ">", "1", ";", "i", "-=", "1", ")", "{", "const", "key", "=", "locale", ".", "substring", "(", "0", ",", "i", ")", ";", "if", "(", "locales", ".", "includes", "(", "key", ")", ")", "{", "return", "key", ";", "}", "}", "return", "null", ";", "}" ]
Find a fallback locale
[ "Find", "a", "fallback", "locale" ]
a753910a0b0c498085ba9c3f71db8f21fa9dc81b
https://github.com/joshswan/react-native-globalize/blob/a753910a0b0c498085ba9c3f71db8f21fa9dc81b/lib/globalize.js#L38-L50
12,785
joshswan/react-native-globalize
lib/globalize.js
localeIsLoaded
function localeIsLoaded(locale) { return !!(Cldr._raw && Cldr._raw.main && Cldr._raw.main[getLocaleKey(locale)]); }
javascript
function localeIsLoaded(locale) { return !!(Cldr._raw && Cldr._raw.main && Cldr._raw.main[getLocaleKey(locale)]); }
[ "function", "localeIsLoaded", "(", "locale", ")", "{", "return", "!", "!", "(", "Cldr", ".", "_raw", "&&", "Cldr", ".", "_raw", ".", "main", "&&", "Cldr", ".", "_raw", ".", "main", "[", "getLocaleKey", "(", "locale", ")", "]", ")", ";", "}" ]
Check if CLDR data loaded for a given locale
[ "Check", "if", "CLDR", "data", "loaded", "for", "a", "given", "locale" ]
a753910a0b0c498085ba9c3f71db8f21fa9dc81b
https://github.com/joshswan/react-native-globalize/blob/a753910a0b0c498085ba9c3f71db8f21fa9dc81b/lib/globalize.js#L59-L61
12,786
joshswan/react-native-globalize
lib/globalize.js
getCurrencySymbol
function getCurrencySymbol(locale, currencyCode, altNarrow) { // Check whether the locale has been loaded if (!localeIsLoaded(locale)) { return null; } const { currencies } = Cldr._raw.main[locale].numbers; // Check whether the given currency code exists within the CLDR file for the given locale if (!Object.keys(currencies).includes(currencyCode)) { return null; } // Return the right currency symbol, either the normal one or the alt-narrow one if desired return altNarrow ? currencies[currencyCode]['symbol-alt-narrow'] : currencies[currencyCode].symbol; }
javascript
function getCurrencySymbol(locale, currencyCode, altNarrow) { // Check whether the locale has been loaded if (!localeIsLoaded(locale)) { return null; } const { currencies } = Cldr._raw.main[locale].numbers; // Check whether the given currency code exists within the CLDR file for the given locale if (!Object.keys(currencies).includes(currencyCode)) { return null; } // Return the right currency symbol, either the normal one or the alt-narrow one if desired return altNarrow ? currencies[currencyCode]['symbol-alt-narrow'] : currencies[currencyCode].symbol; }
[ "function", "getCurrencySymbol", "(", "locale", ",", "currencyCode", ",", "altNarrow", ")", "{", "// Check whether the locale has been loaded", "if", "(", "!", "localeIsLoaded", "(", "locale", ")", ")", "{", "return", "null", ";", "}", "const", "{", "currencies", "}", "=", "Cldr", ".", "_raw", ".", "main", "[", "locale", "]", ".", "numbers", ";", "// Check whether the given currency code exists within the CLDR file for the given locale", "if", "(", "!", "Object", ".", "keys", "(", "currencies", ")", ".", "includes", "(", "currencyCode", ")", ")", "{", "return", "null", ";", "}", "// Return the right currency symbol, either the normal one or the alt-narrow one if desired", "return", "altNarrow", "?", "currencies", "[", "currencyCode", "]", "[", "'symbol-alt-narrow'", "]", ":", "currencies", "[", "currencyCode", "]", ".", "symbol", ";", "}" ]
Returns only the currency symbol from the CLDR file
[ "Returns", "only", "the", "currency", "symbol", "from", "the", "CLDR", "file" ]
a753910a0b0c498085ba9c3f71db8f21fa9dc81b
https://github.com/joshswan/react-native-globalize/blob/a753910a0b0c498085ba9c3f71db8f21fa9dc81b/lib/globalize.js#L64-L79
12,787
troybetz/react-youtube
src/YouTube.js
shouldUpdateVideo
function shouldUpdateVideo(prevProps, props) { // A changing video should always trigger an update if (prevProps.videoId !== props.videoId) { return true; } // Otherwise, a change in the start/end time playerVars also requires a player // update. const prevVars = prevProps.opts.playerVars || {}; const vars = props.opts.playerVars || {}; return prevVars.start !== vars.start || prevVars.end !== vars.end; }
javascript
function shouldUpdateVideo(prevProps, props) { // A changing video should always trigger an update if (prevProps.videoId !== props.videoId) { return true; } // Otherwise, a change in the start/end time playerVars also requires a player // update. const prevVars = prevProps.opts.playerVars || {}; const vars = props.opts.playerVars || {}; return prevVars.start !== vars.start || prevVars.end !== vars.end; }
[ "function", "shouldUpdateVideo", "(", "prevProps", ",", "props", ")", "{", "// A changing video should always trigger an update", "if", "(", "prevProps", ".", "videoId", "!==", "props", ".", "videoId", ")", "{", "return", "true", ";", "}", "// Otherwise, a change in the start/end time playerVars also requires a player", "// update.", "const", "prevVars", "=", "prevProps", ".", "opts", ".", "playerVars", "||", "{", "}", ";", "const", "vars", "=", "props", ".", "opts", ".", "playerVars", "||", "{", "}", ";", "return", "prevVars", ".", "start", "!==", "vars", ".", "start", "||", "prevVars", ".", "end", "!==", "vars", ".", "end", ";", "}" ]
Check whether a `props` change should result in the video being updated. @param {Object} prevProps @param {Object} props
[ "Check", "whether", "a", "props", "change", "should", "result", "in", "the", "video", "being", "updated", "." ]
7062aefc145c04d9eea100ebe5b03c1f2c30ed62
https://github.com/troybetz/react-youtube/blob/7062aefc145c04d9eea100ebe5b03c1f2c30ed62/src/YouTube.js#L12-L24
12,788
troybetz/react-youtube
src/YouTube.js
shouldResetPlayer
function shouldResetPlayer(prevProps, props) { return !isEqual( filterResetOptions(prevProps.opts), filterResetOptions(props.opts), ); }
javascript
function shouldResetPlayer(prevProps, props) { return !isEqual( filterResetOptions(prevProps.opts), filterResetOptions(props.opts), ); }
[ "function", "shouldResetPlayer", "(", "prevProps", ",", "props", ")", "{", "return", "!", "isEqual", "(", "filterResetOptions", "(", "prevProps", ".", "opts", ")", ",", "filterResetOptions", "(", "props", ".", "opts", ")", ",", ")", ";", "}" ]
Check whether a `props` change should result in the player being reset. The player is reset when the `props.opts` change, except if the only change is in the `start` and `end` playerVars, because a video update can deal with those. @param {Object} prevProps @param {Object} props
[ "Check", "whether", "a", "props", "change", "should", "result", "in", "the", "player", "being", "reset", ".", "The", "player", "is", "reset", "when", "the", "props", ".", "opts", "change", "except", "if", "the", "only", "change", "is", "in", "the", "start", "and", "end", "playerVars", "because", "a", "video", "update", "can", "deal", "with", "those", "." ]
7062aefc145c04d9eea100ebe5b03c1f2c30ed62
https://github.com/troybetz/react-youtube/blob/7062aefc145c04d9eea100ebe5b03c1f2c30ed62/src/YouTube.js#L54-L59
12,789
troybetz/react-youtube
src/YouTube.js
shouldUpdatePlayer
function shouldUpdatePlayer(prevProps, props) { return ( prevProps.id !== props.id || prevProps.className !== props.className ); }
javascript
function shouldUpdatePlayer(prevProps, props) { return ( prevProps.id !== props.id || prevProps.className !== props.className ); }
[ "function", "shouldUpdatePlayer", "(", "prevProps", ",", "props", ")", "{", "return", "(", "prevProps", ".", "id", "!==", "props", ".", "id", "||", "prevProps", ".", "className", "!==", "props", ".", "className", ")", ";", "}" ]
Check whether a props change should result in an id or className update. @param {Object} prevProps @param {Object} props
[ "Check", "whether", "a", "props", "change", "should", "result", "in", "an", "id", "or", "className", "update", "." ]
7062aefc145c04d9eea100ebe5b03c1f2c30ed62
https://github.com/troybetz/react-youtube/blob/7062aefc145c04d9eea100ebe5b03c1f2c30ed62/src/YouTube.js#L67-L71
12,790
eggjs/egg-sequelize
lib/loader.js
loadDatabase
function loadDatabase(config = {}) { if (typeof config.ignore === 'string' || Array.isArray(config.ignore)) { app.deprecate(`[egg-sequelize] if you want to exclude ${config.ignore} when load models, please set to config.sequelize.exclude instead of config.sequelize.ignore`); config.exclude = config.ignore; delete config.ignore; } const sequelize = new app.Sequelize(config.database, config.username, config.password, config); const delegate = config.delegate.split('.'); const len = delegate.length; let model = app; let context = app.context; for (let i = 0; i < len - 1; i++) { model = model[delegate[i]] = model[delegate[i]] || {}; context = context[delegate[i]] = context[delegate[i]] || {}; } if (model[delegate[len - 1]]) { throw new Error(`[egg-sequelize] app[${config.delegate}] is already defined`); } Object.defineProperty(model, delegate[len - 1], { value: sequelize, writable: false, configurable: true, }); const DELEGATE = Symbol(`context#sequelize_${config.delegate}`); Object.defineProperty(context, delegate[len - 1], { get() { // context.model is different with app.model // so we can change the properties of ctx.model.xxx if (!this[DELEGATE]) this[DELEGATE] = Object.create(model[delegate[len - 1]]); return this[DELEGATE]; }, configurable: true, }); const modelDir = path.join(app.baseDir, 'app', config.baseDir); const models = []; const target = Symbol(config.delegate); app.loader.loadToApp(modelDir, target, { caseStyle: 'upper', ignore: config.exclude, filter(model) { if (!model || !model.sequelize) return false; models.push(model); return true; }, initializer(factory) { if (typeof factory === 'function') { return factory(app, sequelize); } }, }); Object.assign(model[delegate[len - 1]], app[target]); models.forEach(model => { typeof model.associate === 'function' && model.associate(); }); return model[delegate[len - 1]]; }
javascript
function loadDatabase(config = {}) { if (typeof config.ignore === 'string' || Array.isArray(config.ignore)) { app.deprecate(`[egg-sequelize] if you want to exclude ${config.ignore} when load models, please set to config.sequelize.exclude instead of config.sequelize.ignore`); config.exclude = config.ignore; delete config.ignore; } const sequelize = new app.Sequelize(config.database, config.username, config.password, config); const delegate = config.delegate.split('.'); const len = delegate.length; let model = app; let context = app.context; for (let i = 0; i < len - 1; i++) { model = model[delegate[i]] = model[delegate[i]] || {}; context = context[delegate[i]] = context[delegate[i]] || {}; } if (model[delegate[len - 1]]) { throw new Error(`[egg-sequelize] app[${config.delegate}] is already defined`); } Object.defineProperty(model, delegate[len - 1], { value: sequelize, writable: false, configurable: true, }); const DELEGATE = Symbol(`context#sequelize_${config.delegate}`); Object.defineProperty(context, delegate[len - 1], { get() { // context.model is different with app.model // so we can change the properties of ctx.model.xxx if (!this[DELEGATE]) this[DELEGATE] = Object.create(model[delegate[len - 1]]); return this[DELEGATE]; }, configurable: true, }); const modelDir = path.join(app.baseDir, 'app', config.baseDir); const models = []; const target = Symbol(config.delegate); app.loader.loadToApp(modelDir, target, { caseStyle: 'upper', ignore: config.exclude, filter(model) { if (!model || !model.sequelize) return false; models.push(model); return true; }, initializer(factory) { if (typeof factory === 'function') { return factory(app, sequelize); } }, }); Object.assign(model[delegate[len - 1]], app[target]); models.forEach(model => { typeof model.associate === 'function' && model.associate(); }); return model[delegate[len - 1]]; }
[ "function", "loadDatabase", "(", "config", "=", "{", "}", ")", "{", "if", "(", "typeof", "config", ".", "ignore", "===", "'string'", "||", "Array", ".", "isArray", "(", "config", ".", "ignore", ")", ")", "{", "app", ".", "deprecate", "(", "`", "${", "config", ".", "ignore", "}", "`", ")", ";", "config", ".", "exclude", "=", "config", ".", "ignore", ";", "delete", "config", ".", "ignore", ";", "}", "const", "sequelize", "=", "new", "app", ".", "Sequelize", "(", "config", ".", "database", ",", "config", ".", "username", ",", "config", ".", "password", ",", "config", ")", ";", "const", "delegate", "=", "config", ".", "delegate", ".", "split", "(", "'.'", ")", ";", "const", "len", "=", "delegate", ".", "length", ";", "let", "model", "=", "app", ";", "let", "context", "=", "app", ".", "context", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "len", "-", "1", ";", "i", "++", ")", "{", "model", "=", "model", "[", "delegate", "[", "i", "]", "]", "=", "model", "[", "delegate", "[", "i", "]", "]", "||", "{", "}", ";", "context", "=", "context", "[", "delegate", "[", "i", "]", "]", "=", "context", "[", "delegate", "[", "i", "]", "]", "||", "{", "}", ";", "}", "if", "(", "model", "[", "delegate", "[", "len", "-", "1", "]", "]", ")", "{", "throw", "new", "Error", "(", "`", "${", "config", ".", "delegate", "}", "`", ")", ";", "}", "Object", ".", "defineProperty", "(", "model", ",", "delegate", "[", "len", "-", "1", "]", ",", "{", "value", ":", "sequelize", ",", "writable", ":", "false", ",", "configurable", ":", "true", ",", "}", ")", ";", "const", "DELEGATE", "=", "Symbol", "(", "`", "${", "config", ".", "delegate", "}", "`", ")", ";", "Object", ".", "defineProperty", "(", "context", ",", "delegate", "[", "len", "-", "1", "]", ",", "{", "get", "(", ")", "{", "// context.model is different with app.model", "// so we can change the properties of ctx.model.xxx", "if", "(", "!", "this", "[", "DELEGATE", "]", ")", "this", "[", "DELEGATE", "]", "=", "Object", ".", "create", "(", "model", "[", "delegate", "[", "len", "-", "1", "]", "]", ")", ";", "return", "this", "[", "DELEGATE", "]", ";", "}", ",", "configurable", ":", "true", ",", "}", ")", ";", "const", "modelDir", "=", "path", ".", "join", "(", "app", ".", "baseDir", ",", "'app'", ",", "config", ".", "baseDir", ")", ";", "const", "models", "=", "[", "]", ";", "const", "target", "=", "Symbol", "(", "config", ".", "delegate", ")", ";", "app", ".", "loader", ".", "loadToApp", "(", "modelDir", ",", "target", ",", "{", "caseStyle", ":", "'upper'", ",", "ignore", ":", "config", ".", "exclude", ",", "filter", "(", "model", ")", "{", "if", "(", "!", "model", "||", "!", "model", ".", "sequelize", ")", "return", "false", ";", "models", ".", "push", "(", "model", ")", ";", "return", "true", ";", "}", ",", "initializer", "(", "factory", ")", "{", "if", "(", "typeof", "factory", "===", "'function'", ")", "{", "return", "factory", "(", "app", ",", "sequelize", ")", ";", "}", "}", ",", "}", ")", ";", "Object", ".", "assign", "(", "model", "[", "delegate", "[", "len", "-", "1", "]", "]", ",", "app", "[", "target", "]", ")", ";", "models", ".", "forEach", "(", "model", "=>", "{", "typeof", "model", ".", "associate", "===", "'function'", "&&", "model", ".", "associate", "(", ")", ";", "}", ")", ";", "return", "model", "[", "delegate", "[", "len", "-", "1", "]", "]", ";", "}" ]
load databse to app[config.delegate @param {Object} config config for load - delegate: load model to app[delegate] - baeDir: where model located - other sequelize configures(databasem username, password, etc...) @return {Object} sequelize instance
[ "load", "databse", "to", "app", "[", "config", ".", "delegate" ]
04c9e72ffb1b19dbfcc42275e68fe5113eb5e2fc
https://github.com/eggjs/egg-sequelize/blob/04c9e72ffb1b19dbfcc42275e68fe5113eb5e2fc/lib/loader.js#L51-L117
12,791
eggjs/egg-sequelize
lib/loader.js
authenticate
async function authenticate(database) { database[AUTH_RETRIES] = database[AUTH_RETRIES] || 0; try { await database.authenticate(); } catch (e) { if (e.name !== 'SequelizeConnectionRefusedError') throw e; if (app.model[AUTH_RETRIES] >= 3) throw e; // sleep 2s to retry, max 3 times database[AUTH_RETRIES] += 1; app.logger.warn(`Sequelize Error: ${e.message}, sleep 2 seconds to retry...`); await sleep(2000); await authenticate(database); } }
javascript
async function authenticate(database) { database[AUTH_RETRIES] = database[AUTH_RETRIES] || 0; try { await database.authenticate(); } catch (e) { if (e.name !== 'SequelizeConnectionRefusedError') throw e; if (app.model[AUTH_RETRIES] >= 3) throw e; // sleep 2s to retry, max 3 times database[AUTH_RETRIES] += 1; app.logger.warn(`Sequelize Error: ${e.message}, sleep 2 seconds to retry...`); await sleep(2000); await authenticate(database); } }
[ "async", "function", "authenticate", "(", "database", ")", "{", "database", "[", "AUTH_RETRIES", "]", "=", "database", "[", "AUTH_RETRIES", "]", "||", "0", ";", "try", "{", "await", "database", ".", "authenticate", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ".", "name", "!==", "'SequelizeConnectionRefusedError'", ")", "throw", "e", ";", "if", "(", "app", ".", "model", "[", "AUTH_RETRIES", "]", ">=", "3", ")", "throw", "e", ";", "// sleep 2s to retry, max 3 times", "database", "[", "AUTH_RETRIES", "]", "+=", "1", ";", "app", ".", "logger", ".", "warn", "(", "`", "${", "e", ".", "message", "}", "`", ")", ";", "await", "sleep", "(", "2000", ")", ";", "await", "authenticate", "(", "database", ")", ";", "}", "}" ]
Authenticate to test Database connection. This method will retry 3 times when database connect fail in temporary, to avoid Egg start failed. @param {Application} database instance of sequelize
[ "Authenticate", "to", "test", "Database", "connection", "." ]
04c9e72ffb1b19dbfcc42275e68fe5113eb5e2fc
https://github.com/eggjs/egg-sequelize/blob/04c9e72ffb1b19dbfcc42275e68fe5113eb5e2fc/lib/loader.js#L125-L140
12,792
elix/elix
src/calendar.js
copyTimeFromDateToDate
function copyTimeFromDateToDate(date1, date2) { date2.setHours(date1.getHours()); date2.setMinutes(date1.getMinutes()); date2.setSeconds(date1.getSeconds()); date2.setMilliseconds(date1.getMilliseconds()); }
javascript
function copyTimeFromDateToDate(date1, date2) { date2.setHours(date1.getHours()); date2.setMinutes(date1.getMinutes()); date2.setSeconds(date1.getSeconds()); date2.setMilliseconds(date1.getMilliseconds()); }
[ "function", "copyTimeFromDateToDate", "(", "date1", ",", "date2", ")", "{", "date2", ".", "setHours", "(", "date1", ".", "getHours", "(", ")", ")", ";", "date2", ".", "setMinutes", "(", "date1", ".", "getMinutes", "(", ")", ")", ";", "date2", ".", "setSeconds", "(", "date1", ".", "getSeconds", "(", ")", ")", ";", "date2", ".", "setMilliseconds", "(", "date1", ".", "getMilliseconds", "(", ")", ")", ";", "}" ]
Update the time on date2 to match date1.
[ "Update", "the", "time", "on", "date2", "to", "match", "date1", "." ]
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/calendar.js#L403-L408
12,793
elix/elix
src/CalendarDays.js
updateDays
function updateDays(state, forceCreation) { const { dayCount, dayRole, locale, showCompleteWeeks, startDate } = state; const workingStartDate = showCompleteWeeks ? calendar.firstDateOfWeek(startDate, locale) : calendar.midnightOnDate(startDate); let workingDayCount; if (showCompleteWeeks) { const endDate = calendar.offsetDateByDays(startDate, dayCount - 1); const workingEndDate = calendar.lastDateOfWeek(endDate, locale); workingDayCount = calendar.daysBetweenDates(workingStartDate, workingEndDate) + 1; } else { workingDayCount = dayCount; } let days = state.days ? state.days.slice() : []; let date = workingStartDate; for (let i = 0; i < workingDayCount; i++) { const createNewElement = forceCreation || i >= days.length; const day = createNewElement ? template.createElement(dayRole) : days[i]; day.date = new Date(date.getTime()); day.locale = locale; day.style.gridColumnStart = ''; if (createNewElement) { days[i] = day; } date = calendar.offsetDateByDays(date, 1); } if (workingDayCount < days.length) { // Trim days which are no longer needed. days = days.slice(0, workingDayCount); } const firstDay = days[0]; if (firstDay && !showCompleteWeeks) { // Set the grid-column on the first day. This will cause all the subsequent // days to line up in the calendar grid. const dayOfWeek = calendar.daysSinceFirstDayOfWeek(firstDay.date, state.locale); firstDay.style.gridColumnStart = dayOfWeek + 1; } Object.freeze(days); return days; }
javascript
function updateDays(state, forceCreation) { const { dayCount, dayRole, locale, showCompleteWeeks, startDate } = state; const workingStartDate = showCompleteWeeks ? calendar.firstDateOfWeek(startDate, locale) : calendar.midnightOnDate(startDate); let workingDayCount; if (showCompleteWeeks) { const endDate = calendar.offsetDateByDays(startDate, dayCount - 1); const workingEndDate = calendar.lastDateOfWeek(endDate, locale); workingDayCount = calendar.daysBetweenDates(workingStartDate, workingEndDate) + 1; } else { workingDayCount = dayCount; } let days = state.days ? state.days.slice() : []; let date = workingStartDate; for (let i = 0; i < workingDayCount; i++) { const createNewElement = forceCreation || i >= days.length; const day = createNewElement ? template.createElement(dayRole) : days[i]; day.date = new Date(date.getTime()); day.locale = locale; day.style.gridColumnStart = ''; if (createNewElement) { days[i] = day; } date = calendar.offsetDateByDays(date, 1); } if (workingDayCount < days.length) { // Trim days which are no longer needed. days = days.slice(0, workingDayCount); } const firstDay = days[0]; if (firstDay && !showCompleteWeeks) { // Set the grid-column on the first day. This will cause all the subsequent // days to line up in the calendar grid. const dayOfWeek = calendar.daysSinceFirstDayOfWeek(firstDay.date, state.locale); firstDay.style.gridColumnStart = dayOfWeek + 1; } Object.freeze(days); return days; }
[ "function", "updateDays", "(", "state", ",", "forceCreation", ")", "{", "const", "{", "dayCount", ",", "dayRole", ",", "locale", ",", "showCompleteWeeks", ",", "startDate", "}", "=", "state", ";", "const", "workingStartDate", "=", "showCompleteWeeks", "?", "calendar", ".", "firstDateOfWeek", "(", "startDate", ",", "locale", ")", ":", "calendar", ".", "midnightOnDate", "(", "startDate", ")", ";", "let", "workingDayCount", ";", "if", "(", "showCompleteWeeks", ")", "{", "const", "endDate", "=", "calendar", ".", "offsetDateByDays", "(", "startDate", ",", "dayCount", "-", "1", ")", ";", "const", "workingEndDate", "=", "calendar", ".", "lastDateOfWeek", "(", "endDate", ",", "locale", ")", ";", "workingDayCount", "=", "calendar", ".", "daysBetweenDates", "(", "workingStartDate", ",", "workingEndDate", ")", "+", "1", ";", "}", "else", "{", "workingDayCount", "=", "dayCount", ";", "}", "let", "days", "=", "state", ".", "days", "?", "state", ".", "days", ".", "slice", "(", ")", ":", "[", "]", ";", "let", "date", "=", "workingStartDate", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "workingDayCount", ";", "i", "++", ")", "{", "const", "createNewElement", "=", "forceCreation", "||", "i", ">=", "days", ".", "length", ";", "const", "day", "=", "createNewElement", "?", "template", ".", "createElement", "(", "dayRole", ")", ":", "days", "[", "i", "]", ";", "day", ".", "date", "=", "new", "Date", "(", "date", ".", "getTime", "(", ")", ")", ";", "day", ".", "locale", "=", "locale", ";", "day", ".", "style", ".", "gridColumnStart", "=", "''", ";", "if", "(", "createNewElement", ")", "{", "days", "[", "i", "]", "=", "day", ";", "}", "date", "=", "calendar", ".", "offsetDateByDays", "(", "date", ",", "1", ")", ";", "}", "if", "(", "workingDayCount", "<", "days", ".", "length", ")", "{", "// Trim days which are no longer needed.", "days", "=", "days", ".", "slice", "(", "0", ",", "workingDayCount", ")", ";", "}", "const", "firstDay", "=", "days", "[", "0", "]", ";", "if", "(", "firstDay", "&&", "!", "showCompleteWeeks", ")", "{", "// Set the grid-column on the first day. This will cause all the subsequent", "// days to line up in the calendar grid.", "const", "dayOfWeek", "=", "calendar", ".", "daysSinceFirstDayOfWeek", "(", "firstDay", ".", "date", ",", "state", ".", "locale", ")", ";", "firstDay", ".", "style", ".", "gridColumnStart", "=", "dayOfWeek", "+", "1", ";", "}", "Object", ".", "freeze", "(", "days", ")", ";", "return", "days", ";", "}" ]
Create days as necessary for the given state. Reuse existing day elements to the degree possible.
[ "Create", "days", "as", "necessary", "for", "the", "given", "state", ".", "Reuse", "existing", "day", "elements", "to", "the", "degree", "possible", "." ]
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/CalendarDays.js#L188-L234
12,794
elix/elix
src/ShadowTemplateMixin.js
prepareTemplate
function prepareTemplate(element) { let template = element[symbols.template]; if (!template) { /* eslint-disable no-console */ console.warn(`ShadowTemplateMixin expects ${element.constructor.name} to define a property called [symbols.template].\nSee https://elix.org/documentation/ShadowTemplateMixin.`); return; } if (!(template instanceof HTMLTemplateElement)) { throw `Warning: the [symbols.template] property for ${element.constructor.name} must return an HTMLTemplateElement.`; } // @ts-ignore if (window.ShadyCSS && !window.ShadyCSS.nativeShadow) { // Let the CSS polyfill do its own initialization. const tag = element.localName; // @ts-ignore window.ShadyCSS.prepareTemplate(template, tag); } return template; }
javascript
function prepareTemplate(element) { let template = element[symbols.template]; if (!template) { /* eslint-disable no-console */ console.warn(`ShadowTemplateMixin expects ${element.constructor.name} to define a property called [symbols.template].\nSee https://elix.org/documentation/ShadowTemplateMixin.`); return; } if (!(template instanceof HTMLTemplateElement)) { throw `Warning: the [symbols.template] property for ${element.constructor.name} must return an HTMLTemplateElement.`; } // @ts-ignore if (window.ShadyCSS && !window.ShadyCSS.nativeShadow) { // Let the CSS polyfill do its own initialization. const tag = element.localName; // @ts-ignore window.ShadyCSS.prepareTemplate(template, tag); } return template; }
[ "function", "prepareTemplate", "(", "element", ")", "{", "let", "template", "=", "element", "[", "symbols", ".", "template", "]", ";", "if", "(", "!", "template", ")", "{", "/* eslint-disable no-console */", "console", ".", "warn", "(", "`", "${", "element", ".", "constructor", ".", "name", "}", "\\n", "`", ")", ";", "return", ";", "}", "if", "(", "!", "(", "template", "instanceof", "HTMLTemplateElement", ")", ")", "{", "throw", "`", "${", "element", ".", "constructor", ".", "name", "}", "`", ";", "}", "// @ts-ignore", "if", "(", "window", ".", "ShadyCSS", "&&", "!", "window", ".", "ShadyCSS", ".", "nativeShadow", ")", "{", "// Let the CSS polyfill do its own initialization.", "const", "tag", "=", "element", ".", "localName", ";", "// @ts-ignore", "window", ".", "ShadyCSS", ".", "prepareTemplate", "(", "template", ",", "tag", ")", ";", "}", "return", "template", ";", "}" ]
Retrieve an element's template and prepare it for use.
[ "Retrieve", "an", "element", "s", "template", "and", "prepare", "it", "for", "use", "." ]
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/ShadowTemplateMixin.js#L129-L152
12,795
elix/elix
src/PopupSource.js
measurePopup
function measurePopup(element) { const windowHeight = window.innerHeight; const windowWidth = window.innerWidth; const popupRect = element.$.popup.getBoundingClientRect(); const popupHeight = popupRect.height; const popupWidth = popupRect.width; const sourceRect = element.getBoundingClientRect(); const roomAbove = sourceRect.top; const roomBelow = Math.ceil(windowHeight - sourceRect.bottom); const roomLeft = sourceRect.right; const roomRight = Math.ceil(windowWidth - sourceRect.left); const popupMeasured = true; element.setState({ popupHeight, popupMeasured, popupWidth, roomAbove, roomBelow, roomLeft, roomRight, windowHeight, windowWidth }); }
javascript
function measurePopup(element) { const windowHeight = window.innerHeight; const windowWidth = window.innerWidth; const popupRect = element.$.popup.getBoundingClientRect(); const popupHeight = popupRect.height; const popupWidth = popupRect.width; const sourceRect = element.getBoundingClientRect(); const roomAbove = sourceRect.top; const roomBelow = Math.ceil(windowHeight - sourceRect.bottom); const roomLeft = sourceRect.right; const roomRight = Math.ceil(windowWidth - sourceRect.left); const popupMeasured = true; element.setState({ popupHeight, popupMeasured, popupWidth, roomAbove, roomBelow, roomLeft, roomRight, windowHeight, windowWidth }); }
[ "function", "measurePopup", "(", "element", ")", "{", "const", "windowHeight", "=", "window", ".", "innerHeight", ";", "const", "windowWidth", "=", "window", ".", "innerWidth", ";", "const", "popupRect", "=", "element", ".", "$", ".", "popup", ".", "getBoundingClientRect", "(", ")", ";", "const", "popupHeight", "=", "popupRect", ".", "height", ";", "const", "popupWidth", "=", "popupRect", ".", "width", ";", "const", "sourceRect", "=", "element", ".", "getBoundingClientRect", "(", ")", ";", "const", "roomAbove", "=", "sourceRect", ".", "top", ";", "const", "roomBelow", "=", "Math", ".", "ceil", "(", "windowHeight", "-", "sourceRect", ".", "bottom", ")", ";", "const", "roomLeft", "=", "sourceRect", ".", "right", ";", "const", "roomRight", "=", "Math", ".", "ceil", "(", "windowWidth", "-", "sourceRect", ".", "left", ")", ";", "const", "popupMeasured", "=", "true", ";", "element", ".", "setState", "(", "{", "popupHeight", ",", "popupMeasured", ",", "popupWidth", ",", "roomAbove", ",", "roomBelow", ",", "roomLeft", ",", "roomRight", ",", "windowHeight", ",", "windowWidth", "}", ")", ";", "}" ]
If we haven't already measured the popup since it was opened, measure its dimensions and the relevant distances in which the popup might be opened.
[ "If", "we", "haven", "t", "already", "measured", "the", "popup", "since", "it", "was", "opened", "measure", "its", "dimensions", "and", "the", "relevant", "distances", "in", "which", "the", "popup", "might", "be", "opened", "." ]
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/PopupSource.js#L454-L482
12,796
elix/elix
demos/src/LocaleSelector.js
getLocaleOptions
function getLocaleOptions() { if (!localeOptions) { localeOptions = Object.keys(locales).map(locale => { const option = document.createElement('option'); option.value = locale; option.disabled = !localeSupported(locale); option.textContent = locales[locale]; return option; }); Object.freeze(localeOptions); } return localeOptions; }
javascript
function getLocaleOptions() { if (!localeOptions) { localeOptions = Object.keys(locales).map(locale => { const option = document.createElement('option'); option.value = locale; option.disabled = !localeSupported(locale); option.textContent = locales[locale]; return option; }); Object.freeze(localeOptions); } return localeOptions; }
[ "function", "getLocaleOptions", "(", ")", "{", "if", "(", "!", "localeOptions", ")", "{", "localeOptions", "=", "Object", ".", "keys", "(", "locales", ")", ".", "map", "(", "locale", "=>", "{", "const", "option", "=", "document", ".", "createElement", "(", "'option'", ")", ";", "option", ".", "value", "=", "locale", ";", "option", ".", "disabled", "=", "!", "localeSupported", "(", "locale", ")", ";", "option", ".", "textContent", "=", "locales", "[", "locale", "]", ";", "return", "option", ";", "}", ")", ";", "Object", ".", "freeze", "(", "localeOptions", ")", ";", "}", "return", "localeOptions", ";", "}" ]
Create options for all locales and cache the result.
[ "Create", "options", "for", "all", "locales", "and", "cache", "the", "result", "." ]
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/demos/src/LocaleSelector.js#L361-L373
12,797
elix/elix
demos/src/LocaleSelector.js
localeSupported
function localeSupported(locale) { const language = locale.split('-')[0]; if (language === 'en') { // Assume all flavors of English are supported. return true; } // Try formatting a Tuesday date, and if we get the English result "Tue", // the browser probably doesn't support the locale, and used the default // locale instead. const date = new Date('10 March 2015'); // A Tuesday const formatter = new Intl.DateTimeFormat(locale, { weekday: 'short' }) const result = formatter.format(date); return result !== 'Tue'; }
javascript
function localeSupported(locale) { const language = locale.split('-')[0]; if (language === 'en') { // Assume all flavors of English are supported. return true; } // Try formatting a Tuesday date, and if we get the English result "Tue", // the browser probably doesn't support the locale, and used the default // locale instead. const date = new Date('10 March 2015'); // A Tuesday const formatter = new Intl.DateTimeFormat(locale, { weekday: 'short' }) const result = formatter.format(date); return result !== 'Tue'; }
[ "function", "localeSupported", "(", "locale", ")", "{", "const", "language", "=", "locale", ".", "split", "(", "'-'", ")", "[", "0", "]", ";", "if", "(", "language", "===", "'en'", ")", "{", "// Assume all flavors of English are supported.", "return", "true", ";", "}", "// Try formatting a Tuesday date, and if we get the English result \"Tue\",", "// the browser probably doesn't support the locale, and used the default", "// locale instead.", "const", "date", "=", "new", "Date", "(", "'10 March 2015'", ")", ";", "// A Tuesday", "const", "formatter", "=", "new", "Intl", ".", "DateTimeFormat", "(", "locale", ",", "{", "weekday", ":", "'short'", "}", ")", "const", "result", "=", "formatter", ".", "format", "(", "date", ")", ";", "return", "result", "!==", "'Tue'", ";", "}" ]
Heuristic that returns true if the given locale is supported.
[ "Heuristic", "that", "returns", "true", "if", "the", "given", "locale", "is", "supported", "." ]
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/demos/src/LocaleSelector.js#L377-L390
12,798
elix/elix
src/DialogModalityMixin.js
disableDocumentScrolling
function disableDocumentScrolling(element) { if (!document.documentElement) { return; } const documentWidth = document.documentElement.clientWidth; const scrollBarWidth = window.innerWidth - documentWidth; element[previousBodyOverflowKey] = document.body.style.overflow; element[previousDocumentMarginRightKey] = scrollBarWidth > 0 ? document.documentElement.style.marginRight : null; document.body.style.overflow = 'hidden'; if (scrollBarWidth > 0) { document.documentElement.style.marginRight = `${scrollBarWidth}px`; } }
javascript
function disableDocumentScrolling(element) { if (!document.documentElement) { return; } const documentWidth = document.documentElement.clientWidth; const scrollBarWidth = window.innerWidth - documentWidth; element[previousBodyOverflowKey] = document.body.style.overflow; element[previousDocumentMarginRightKey] = scrollBarWidth > 0 ? document.documentElement.style.marginRight : null; document.body.style.overflow = 'hidden'; if (scrollBarWidth > 0) { document.documentElement.style.marginRight = `${scrollBarWidth}px`; } }
[ "function", "disableDocumentScrolling", "(", "element", ")", "{", "if", "(", "!", "document", ".", "documentElement", ")", "{", "return", ";", "}", "const", "documentWidth", "=", "document", ".", "documentElement", ".", "clientWidth", ";", "const", "scrollBarWidth", "=", "window", ".", "innerWidth", "-", "documentWidth", ";", "element", "[", "previousBodyOverflowKey", "]", "=", "document", ".", "body", ".", "style", ".", "overflow", ";", "element", "[", "previousDocumentMarginRightKey", "]", "=", "scrollBarWidth", ">", "0", "?", "document", ".", "documentElement", ".", "style", ".", "marginRight", ":", "null", ";", "document", ".", "body", ".", "style", ".", "overflow", "=", "'hidden'", ";", "if", "(", "scrollBarWidth", ">", "0", ")", "{", "document", ".", "documentElement", ".", "style", ".", "marginRight", "=", "`", "${", "scrollBarWidth", "}", "`", ";", "}", "}" ]
Mark body as non-scrollable, to absorb space bar keypresses and other means of scrolling the top-level document.
[ "Mark", "body", "as", "non", "-", "scrollable", "to", "absorb", "space", "bar", "keypresses", "and", "other", "means", "of", "scrolling", "the", "top", "-", "level", "document", "." ]
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/DialogModalityMixin.js#L88-L102
12,799
elix/elix
src/OverlayMixin.js
openedChanged
function openedChanged(element) { if (element.state.autoFocus) { if (element.state.opened) { // Opened if (!element[restoreFocusToElementKey] && document.activeElement !== document.body) { // Remember which element had the focus before we were opened. element[restoreFocusToElementKey] = document.activeElement; } // Focus on the element itself (if it's focusable), or the first focusable // element inside it. // TODO: We'd prefer to require that overlays (like the Overlay base // class) make use of delegatesFocus via DelegateFocusMixin, which would // let us drop the need for this mixin here to do anything special with // focus. However, an initial trial of this revealed an issue in // MenuButton, where invoking the menu did not put the focus on the first // menu item as expected. Needs more investigation. const focusElement = firstFocusableElement(element); if (focusElement) { focusElement.focus(); } } else { // Closed if (element[restoreFocusToElementKey]) { // Restore focus to the element that had the focus before the overlay was // opened. element[restoreFocusToElementKey].focus(); element[restoreFocusToElementKey] = null; } } } }
javascript
function openedChanged(element) { if (element.state.autoFocus) { if (element.state.opened) { // Opened if (!element[restoreFocusToElementKey] && document.activeElement !== document.body) { // Remember which element had the focus before we were opened. element[restoreFocusToElementKey] = document.activeElement; } // Focus on the element itself (if it's focusable), or the first focusable // element inside it. // TODO: We'd prefer to require that overlays (like the Overlay base // class) make use of delegatesFocus via DelegateFocusMixin, which would // let us drop the need for this mixin here to do anything special with // focus. However, an initial trial of this revealed an issue in // MenuButton, where invoking the menu did not put the focus on the first // menu item as expected. Needs more investigation. const focusElement = firstFocusableElement(element); if (focusElement) { focusElement.focus(); } } else { // Closed if (element[restoreFocusToElementKey]) { // Restore focus to the element that had the focus before the overlay was // opened. element[restoreFocusToElementKey].focus(); element[restoreFocusToElementKey] = null; } } } }
[ "function", "openedChanged", "(", "element", ")", "{", "if", "(", "element", ".", "state", ".", "autoFocus", ")", "{", "if", "(", "element", ".", "state", ".", "opened", ")", "{", "// Opened", "if", "(", "!", "element", "[", "restoreFocusToElementKey", "]", "&&", "document", ".", "activeElement", "!==", "document", ".", "body", ")", "{", "// Remember which element had the focus before we were opened.", "element", "[", "restoreFocusToElementKey", "]", "=", "document", ".", "activeElement", ";", "}", "// Focus on the element itself (if it's focusable), or the first focusable", "// element inside it.", "// TODO: We'd prefer to require that overlays (like the Overlay base", "// class) make use of delegatesFocus via DelegateFocusMixin, which would", "// let us drop the need for this mixin here to do anything special with", "// focus. However, an initial trial of this revealed an issue in", "// MenuButton, where invoking the menu did not put the focus on the first", "// menu item as expected. Needs more investigation.", "const", "focusElement", "=", "firstFocusableElement", "(", "element", ")", ";", "if", "(", "focusElement", ")", "{", "focusElement", ".", "focus", "(", ")", ";", "}", "}", "else", "{", "// Closed", "if", "(", "element", "[", "restoreFocusToElementKey", "]", ")", "{", "// Restore focus to the element that had the focus before the overlay was", "// opened.", "element", "[", "restoreFocusToElementKey", "]", ".", "focus", "(", ")", ";", "element", "[", "restoreFocusToElementKey", "]", "=", "null", ";", "}", "}", "}", "}" ]
Update the overlay following a change in opened state.
[ "Update", "the", "overlay", "following", "a", "change", "in", "opened", "state", "." ]
2e5fde9777b2e6e4b9453c32d7b7007948d5892d
https://github.com/elix/elix/blob/2e5fde9777b2e6e4b9453c32d7b7007948d5892d/src/OverlayMixin.js#L151-L181