code
stringlengths
24
2.07M
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
92
language
stringclasses
1 value
repo
stringlengths
5
64
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } }
Determines whether an object can have data
fixCloneNodeIssues
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; }
Retrieve the actual display of a element @param {String} name nodeName of the element @param {Object} doc Document object
actualDisplay
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; }
Try to determine the default display value of an element @param {String} nodeName
defaultDisplay
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; }
Try to determine the default display value of an element @param {String} nodeName
addGetHookIf
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function computeStyleTests() { var container, div, body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Test fired too early or in an unsupported environment, exit. return; } container = document.createElement( "div" ); div = document.createElement( "div" ); container.style.cssText = containerStyles; body.appendChild( container ).appendChild( div ); div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" + "position:absolute;display:block;padding:1px;border:1px;width:4px;" + "margin-top:1%;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { boxSizingVal = div.offsetWidth === 4; }); // Will be changed later if needed. boxSizingReliableVal = true; pixelPositionVal = false; reliableMarginRightVal = true; // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; } body.removeChild( container ); // Null elements to avoid leaks in IE. div = body = null; }
Try to determine the default display value of an element @param {String} nodeName
computeStyleTests
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; }
Try to determine the default display value of an element @param {String} nodeName
vendorPropName
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; }
Try to determine the default display value of an element @param {String} nodeName
showHide
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; }
Try to determine the default display value of an element @param {String} nodeName
setPositiveNumber
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; }
Try to determine the default display value of an element @param {String} nodeName
augmentWidthOrHeight
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; }
Try to determine the default display value of an element @param {String} nodeName
getWidthOrHeight
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); }
Try to determine the default display value of an element @param {String} nodeName
Tween
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); }
Try to determine the default display value of an element @param {String} nodeName
createFxNow
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; }
Try to determine the default display value of an element @param {String} nodeName
genFx
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } }
Try to determine the default display value of an element @param {String} nodeName
createTween
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, dDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); dDisplay = defaultDisplay( elem.nodeName ); if ( display === "none" ) { display = dDisplay; } if ( display === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || dDisplay === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !support.shrinkWrapBlocks() ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } }
Try to determine the default display value of an element @param {String} nodeName
defaultPrefilter
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } }
Try to determine the default display value of an element @param {String} nodeName
propFilter
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); }
Try to determine the default display value of an element @param {String} nodeName
Animation
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }
Try to determine the default display value of an element @param {String} nodeName
tick
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }
Try to determine the default display value of an element @param {String} nodeName
doAnimation
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }
Try to determine the default display value of an element @param {String} nodeName
stopQueue
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType.charAt( 0 ) === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; }
Try to determine the default display value of an element @param {String} nodeName
addToPrefiltersOrTransports
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); }
Try to determine the default display value of an element @param {String} nodeName
inspectPrefiltersOrTransports
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; }
Try to determine the default display value of an element @param {String} nodeName
inspect
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; }
Try to determine the default display value of an element @param {String} nodeName
ajaxExtend
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } }
Try to determine the default display value of an element @param {String} nodeName
ajaxHandleResponses
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; }
Try to determine the default display value of an element @param {String} nodeName
ajaxConvert
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } }
Try to determine the default display value of an element @param {String} nodeName
done
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } }
Try to determine the default display value of an element @param {String} nodeName
buildParams
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }
Try to determine the default display value of an element @param {String} nodeName
add
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} }
Try to determine the default display value of an element @param {String} nodeName
createStandardXHR
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} }
Try to determine the default display value of an element @param {String} nodeName
createActiveXHR
javascript
documentcloud/visualsearch
vendor/jquery-1.11.0.js
https://github.com/documentcloud/visualsearch/blob/master/vendor/jquery-1.11.0.js
MIT
constructor(request, response, jobs, config) { const tokens = Object.keys(jobs); this.config = config; this.plugins = config.plugins; this.error = null; this.statusCode = 200; // An object that all of the contexts will inherit from... one per instance. this.baseContext = { request, response, batchMeta: {}, }; // An object that will be passed into the context for batch-level methods, but not for job-level // methods. this.batchContext = { tokens, jobs, }; // A map of token => JobContext, where JobContext is an object of data that is per-job, // and will be passed into plugins and used for the final result. this.jobContexts = tokens.reduce((obj, token) => { const { name, data, metadata } = jobs[token]; /* eslint no-param-reassign: 1 */ obj[token] = { name, token, props: data, metadata, statusCode: 200, duration: null, html: null, returnMeta: {}, }; return obj; }, {}); // Each plugin receives it's own little key-value data store that is scoped privately // to the plugin for the life time of the request. This is achieved simply through lexical // closure. this.pluginContexts = new Map(); this.plugins.forEach((plugin) => { this.pluginContexts.set(plugin, { data: new Map() }); }); }
The BatchManager is a class that is instantiated once per batch, and holds a lot of the key data needed throughout the life of the request. This ends up cleaning up some of the management needed for plugin lifecycle, and the handling of rendering multiple jobs in a batch. @param {express.Request} req @param {express.Response} res @param {Object} jobs - a map of token => Job @param {Object} config @constructor
constructor
javascript
airbnb/hypernova
src/utils/BatchManager.js
https://github.com/airbnb/hypernova/blob/master/src/utils/BatchManager.js
MIT
getRequestContext(plugin, token) { return { ...this.baseContext, ...this.jobContexts[token], ...this.pluginContexts.get(plugin), }; }
Returns a context object scoped to a specific plugin and job (based on the plugin and job token passed in).
getRequestContext
javascript
airbnb/hypernova
src/utils/BatchManager.js
https://github.com/airbnb/hypernova/blob/master/src/utils/BatchManager.js
MIT
getBatchContext(plugin) { return { ...this.baseContext, ...this.batchContext, ...this.pluginContexts.get(plugin), }; }
Returns a context object scoped to a specific plugin and batch.
getBatchContext
javascript
airbnb/hypernova
src/utils/BatchManager.js
https://github.com/airbnb/hypernova/blob/master/src/utils/BatchManager.js
MIT
contextFor(plugin, token) { return token ? this.getRequestContext(plugin, token) : this.getBatchContext(plugin); }
Returns a context object scoped to a specific plugin and batch.
contextFor
javascript
airbnb/hypernova
src/utils/BatchManager.js
https://github.com/airbnb/hypernova/blob/master/src/utils/BatchManager.js
MIT
render(token) { const start = now(); const context = this.jobContexts[token]; const { name } = context; const { getComponent } = this.config; const result = getComponent(name, context); return Promise.resolve(result).then((renderFn) => { // ensure that we have this component registered if (!renderFn || typeof renderFn !== 'function') { // component not registered context.statusCode = 404; return Promise.reject(notFound(name)); } return renderFn(context.props); }).then((html) => { // eslint-disable-line consistent-return if (!html) { return Promise.reject(noHTMLError); } context.html = html; context.duration = msSince(start); }).catch((err) => { context.duration = msSince(start); return Promise.reject(err); }); }
Renders a specific job (from a job token). The end result is applied to the corresponding job context. Additionally, duration is calculated.
render
javascript
airbnb/hypernova
src/utils/BatchManager.js
https://github.com/airbnb/hypernova/blob/master/src/utils/BatchManager.js
MIT
recordError(error, token) { if (token && this.jobContexts[token]) { const context = this.jobContexts[token]; context.statusCode = context.statusCode === 200 ? 500 : context.statusCode; context.error = error; } else { this.error = error; this.statusCode = 500; } }
Renders a specific job (from a job token). The end result is applied to the corresponding job context. Additionally, duration is calculated.
recordError
javascript
airbnb/hypernova
src/utils/BatchManager.js
https://github.com/airbnb/hypernova/blob/master/src/utils/BatchManager.js
MIT
getResult(token) { const context = this.jobContexts[token]; return { name: context.name, html: context.html, meta: context.returnMeta, duration: context.duration, statusCode: context.statusCode, success: context.html !== null, error: context.error ? errorToSerializable(context.error) : null, }; }
Renders a specific job (from a job token). The end result is applied to the corresponding job context. Additionally, duration is calculated.
getResult
javascript
airbnb/hypernova
src/utils/BatchManager.js
https://github.com/airbnb/hypernova/blob/master/src/utils/BatchManager.js
MIT
getResults() { return { success: this.error === null, error: this.error, results: Object.keys(this.jobContexts).reduce((result, token) => { /* eslint no-param-reassign: 1 */ result[token] = this.getResult(token); return result; }, {}), }; }
Renders a specific job (from a job token). The end result is applied to the corresponding job context. Additionally, duration is calculated.
getResults
javascript
airbnb/hypernova
src/utils/BatchManager.js
https://github.com/airbnb/hypernova/blob/master/src/utils/BatchManager.js
MIT
function hasMethod(name) { return (obj) => typeof obj[name] === 'function'; }
Returns a predicate function to filter objects based on whether a method of the provided name is present. @param {String} name - the method name to find @returns {Function} - the resulting predicate function
hasMethod
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function raceTo(promise, ms, msg) { let timeout; return Promise.race([ promise, new Promise((resolve) => { timeout = setTimeout(() => resolve(PROMISE_TIMEOUT), ms); }), ]).then((res) => { if (res === PROMISE_TIMEOUT) logger.info(msg, { timeout: ms }); if (timeout) clearTimeout(timeout); return res; }).catch((err) => { if (timeout) clearTimeout(timeout); return Promise.reject(err); }); }
Creates a promise that resolves at the specified number of ms. @param ms @returns {Promise}
raceTo
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function runAppLifecycle(lifecycle, plugins, config, error, ...args) { try { const promise = Promise.all( plugins.filter(hasMethod(lifecycle)).map((plugin) => plugin[lifecycle](config, error, ...args)), ); return raceTo( promise, MAX_LIFECYCLE_EXECUTION_TIME_IN_MS, `App lifecycle method ${lifecycle} took too long.`, ); } catch (err) { return Promise.reject(err); } }
Iterates through the plugins and calls the specified asynchronous lifecycle event, returning a promise that resolves when they all are completed, or rejects if one of them fails. The third `config` param gets passed into the lifecycle methods as the first argument. In this case, the app lifecycle events expect the config instance to be passed in. This function is currently used for the lifecycle events `initialize` and `shutdown`. @param {String} lifecycle @param {Array<HypernovaPlugin>} plugins @param {Config} config @returns {Promise} @param err {Error}
runAppLifecycle
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function runLifecycle(lifecycle, plugins, manager, token) { try { const promise = Promise.all( plugins .filter(hasMethod(lifecycle)) .map((plugin) => plugin[lifecycle](manager.contextFor(plugin, token))), ); return raceTo( promise, MAX_LIFECYCLE_EXECUTION_TIME_IN_MS, `Lifecycle method ${lifecycle} took too long.`, ); } catch (err) { return Promise.reject(err); } }
Iterates through the plugins and calls the specified asynchronous lifecycle event, returning a promise that resolves when they are all completed, or rejects if one of them fails. This is meant to be used on lifecycle events both at the batch level and the job level. The passed in BatchManager is used to get the corresponding context object for the plugin/job and is passed in as the first argument to the plugin's method. This function is currently used for `batchStart/End` and `jobStart/End`. @param {String} lifecycle @param {Array<HypernovaPlugin>} plugins @param {BatchManager} manager @param {String} [token] - If provided, the job token to use to get the context @returns {Promise}
runLifecycle
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function runLifecycleSync(lifecycle, plugins, manager, token) { plugins .filter(hasMethod(lifecycle)) .forEach((plugin) => plugin[lifecycle](manager.contextFor(plugin, token))); }
Iterates through the plugins and calls the specified synchronous lifecycle event (when present). Passes in the appropriate context object for the plugin/job. This function is currently being used for `afterRender` and `beforeRender`. @param {String} lifecycle @param {Array<HypernovaPlugin>} plugins @param {BatchManager} manager @param {String} [token]
runLifecycleSync
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function errorSync(err, plugins, manager, token) { plugins .filter(hasMethod('onError')) .forEach((plugin) => plugin.onError(manager.contextFor(plugin, token), err)); }
Iterates through the plugins and calls the specified synchronous `onError` handler (when present). Passes in the appropriate context object, as well as the error. @param {Error} err @param {Array<HypernovaPlugin>} plugins @param {BatchManager} manager @param {String} [token]
errorSync
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function processJob(token, plugins, manager) { return ( // jobStart runLifecycle('jobStart', plugins, manager, token) .then(() => { // beforeRender runLifecycleSync('beforeRender', plugins, manager, token); // render return manager.render(token); }) // jobEnd .then(() => { // afterRender runLifecycleSync('afterRender', plugins, manager, token); return runLifecycle('jobEnd', plugins, manager, token); }) .catch((err) => { manager.recordError(err, token); errorSync(err, plugins, manager, token); }) ); }
Runs through the job-level lifecycle events of the job based on the provided token. This includes the actual rendering of the job. Returns a promise resolving when the job completes. @param {String} token @param {Array<HypernovaPlugin>} plugins @param {BatchManager} manager @returns {Promise}
processJob
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function processJobsSerially(jobs, plugins, manager) { return Object.keys(jobs).reduce( (chain, token) => chain.then(() => processJob(token, plugins, manager)), Promise.resolve(), ); }
Runs through the job-level lifecycle events of the job based on the provided token. This includes the actual rendering of the job. Returns a promise resolving when the job completes. @param {String} token @param {Array<HypernovaPlugin>} plugins @param {BatchManager} manager @returns {Promise}
processJobsSerially
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function processJobsConcurrently(jobs, plugins, manager) { return Promise.all( Object.keys(jobs).map((token) => processJob(token, plugins, manager)), ); }
Runs through the job-level lifecycle events of the job based on the provided token. This includes the actual rendering of the job. Returns a promise resolving when the job completes. @param {String} token @param {Array<HypernovaPlugin>} plugins @param {BatchManager} manager @returns {Promise}
processJobsConcurrently
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function processBatch(jobs, plugins, manager, concurrent) { return ( // batchStart runLifecycle('batchStart', plugins, manager) // for each job, processJob .then(() => { if (concurrent) { return processJobsConcurrently(jobs, plugins, manager); } return processJobsSerially(jobs, plugins, manager); }) // batchEnd .then(() => runLifecycle('batchEnd', plugins, manager)) .catch((err) => { manager.recordError(err); errorSync(err, plugins, manager); }) ); }
Runs through the batch-level lifecycle events of a batch. This includes the processing of each individual job. Returns a promise resolving when all jobs in the batch complete. @param jobs @param {Array<HypernovaPlugin>} plugins @param {BatchManager} manager @returns {Promise}
processBatch
javascript
airbnb/hypernova
src/utils/lifecycle.js
https://github.com/airbnb/hypernova/blob/master/src/utils/lifecycle.js
MIT
function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module.exports) { module.exports = {}; module.client = module.component = true; module.call(this, module.exports, require.relative(resolved), module); } return module.exports; }
Require the given path. @param {String} path @return {Object} exports @api public
require
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
copyArray = function(dest, doffset, src, soffset, length) { if('function' === typeof src.copy) { // Buffer src.copy(dest, doffset, soffset, soffset + length); } else { // Uint8Array for(var index=0; index<length; index++){ dest[doffset++] = src[soffset++]; } } }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
copyArray
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
msgHasId = function(type) { return type === Message.TYPE_REQUEST || type === Message.TYPE_RESPONSE; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
msgHasId
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
msgHasRoute = function(type) { return type === Message.TYPE_REQUEST || type === Message.TYPE_NOTIFY || type === Message.TYPE_PUSH; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
msgHasRoute
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
caculateMsgIdBytes = function(id) { var len = 0; do { len += 1; id >>= 7; } while(id > 0); return len; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
caculateMsgIdBytes
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
encodeMsgFlag = function(type, compressRoute, buffer, offset) { if(type !== Message.TYPE_REQUEST && type !== Message.TYPE_NOTIFY && type !== Message.TYPE_RESPONSE && type !== Message.TYPE_PUSH) { throw new Error('unkonw message type: ' + type); } buffer[offset] = (type << 1) | (compressRoute ? 1 : 0); return offset + MSG_FLAG_BYTES; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
encodeMsgFlag
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
encodeMsgId = function(id, idBytes, buffer, offset) { var index = offset + idBytes - 1; buffer[index--] = id & 0x7f; while(index >= offset) { id >>= 7; buffer[index--] = id & 0x7f | 0x80; } return offset + idBytes; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
encodeMsgId
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
encodeMsgRoute = function(compressRoute, route, buffer, offset) { if (compressRoute) { if(route > MSG_ROUTE_CODE_MAX){ throw new Error('route number is overflow'); } buffer[offset++] = (route >> 8) & 0xff; buffer[offset++] = route & 0xff; } else { if(route) { buffer[offset++] = route.length & 0xff; copyArray(buffer, offset, route, 0, route.length); offset += route.length; } else { buffer[offset++] = 0; } } return offset; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
encodeMsgRoute
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
encodeMsgBody = function(msg, buffer, offset) { copyArray(buffer, offset, msg, 0, msg.length); return offset + msg.length; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
encodeMsgBody
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function checkMsg(msg, protos){ if(!protos){ return false; } for(var name in protos){ var proto = protos[name]; //All required element must exist switch(proto.option){ case 'required' : if(typeof(msg[name]) === 'undefined'){ return false; } case 'optional' : if(typeof(msg[name]) !== 'undefined'){ if(!!protos.__messages[proto.type]){ checkMsg(msg[name], protos.__messages[proto.type]); } } break; case 'repeated' : //Check nest message in repeated elements if(!!msg[name] && !!protos.__messages[proto.type]){ for(var i = 0; i < msg[name].length; i++){ if(!checkMsg(msg[name][i], protos.__messages[proto.type])){ return false; } } } break; } } return true; }
Check if the msg follow the defination in the protos
checkMsg
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function encodeMsg(buffer, offset, protos, msg){ for(var name in msg){ if(!!protos[name]){ var proto = protos[name]; switch(proto.option){ case 'required' : case 'optional' : offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); offset = encodeProp(msg[name], proto.type, offset, buffer, protos); break; case 'repeated' : if(msg[name].length > 0){ offset = encodeArray(msg[name], proto, offset, buffer, protos); } break; } } } return offset; }
Check if the msg follow the defination in the protos
encodeMsg
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function encodeProp(value, type, offset, buffer, protos){ switch(type){ case 'uInt32': offset = writeBytes(buffer, offset, codec.encodeUInt32(value)); break; case 'int32' : case 'sInt32': offset = writeBytes(buffer, offset, codec.encodeSInt32(value)); break; case 'float': writeBytes(buffer, offset, codec.encodeFloat(value)); offset += 4; break; case 'double': writeBytes(buffer, offset, codec.encodeDouble(value)); offset += 8; break; case 'string': var length = codec.byteLength(value); //Encode length offset = writeBytes(buffer, offset, codec.encodeUInt32(length)); //write string codec.encodeStr(buffer, offset, value); offset += length; break; default : if(!!protos.__messages[type]){ //Use a tmp buffer to build an internal msg var tmpBuffer = new ArrayBuffer(codec.byteLength(JSON.stringify(value))); var length = 0; length = encodeMsg(tmpBuffer, length, protos.__messages[type], value); //Encode length offset = writeBytes(buffer, offset, codec.encodeUInt32(length)); //contact the object for(var i = 0; i < length; i++){ buffer[offset] = tmpBuffer[i]; offset++; } } break; } return offset; }
Check if the msg follow the defination in the protos
encodeProp
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function encodeArray(array, proto, offset, buffer, protos){ var i = 0; if(util.isSimpleType(proto.type)){ offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); offset = writeBytes(buffer, offset, codec.encodeUInt32(array.length)); for(i = 0; i < array.length; i++){ offset = encodeProp(array[i], proto.type, offset, buffer); } }else{ for(i = 0; i < array.length; i++){ offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); offset = encodeProp(array[i], proto.type, offset, buffer, protos); } } return offset; }
Encode reapeated properties, simple msg and object are decode differented
encodeArray
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function writeBytes(buffer, offset, bytes){ for(var i = 0; i < bytes.length; i++, offset++){ buffer[offset] = bytes[i]; } return offset; }
Encode reapeated properties, simple msg and object are decode differented
writeBytes
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function encodeTag(type, tag){ var value = constant.TYPES[type]||2; return codec.encodeUInt32((tag<<3)|value); }
Encode reapeated properties, simple msg and object are decode differented
encodeTag
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function isFinish(msg, protos){ return (!protos.__tags[peekHead().tag]); }
Test if the given msg is finished
isFinish
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function peekHead(){ var tag = codec.decodeUInt32(peekBytes()); return { type : tag&0x7, tag : tag>>3 }; }
Get tag head without move the offset
peekHead
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function decodeProp(type, protos){ switch(type){ case 'uInt32': return codec.decodeUInt32(getBytes()); case 'int32' : case 'sInt32' : return codec.decodeSInt32(getBytes()); case 'float' : var float = codec.decodeFloat(buffer, offset); offset += 4; return float; case 'double' : var double = codec.decodeDouble(buffer, offset); offset += 8; return double; case 'string' : var length = codec.decodeUInt32(getBytes()); var str = codec.decodeStr(buffer, offset, length); offset += length; return str; default : if(!!protos && !!protos.__messages[type]){ var length = codec.decodeUInt32(getBytes()); var msg = {}; decodeMsg(msg, protos.__messages[type], offset+length); return msg; } break; } }
Get tag head without move the offset
decodeProp
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function decodeArray(array, type, protos){ if(util.isSimpleType(type)){ var length = codec.decodeUInt32(getBytes()); for(var i = 0; i < length; i++){ array.push(decodeProp(type)); } }else{ array.push(decodeProp(type, protos)); } }
Get tag head without move the offset
decodeArray
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function getBytes(flag){ var bytes = []; var pos = offset; flag = flag || false; var b; do{ b = buffer[pos]; bytes.push(b); pos++; }while(b >= 128); if(!flag){ offset = pos; } return bytes; }
Get tag head without move the offset
getBytes
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function peekBytes(){ return getBytes(true); }
Get tag head without move the offset
peekBytes
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
initWebSocket = function(url,cb) { console.log('connect to ' + url); var onopen = function(event){ var obj = Package.encode(Package.TYPE_HANDSHAKE, Protocol.strencode(JSON.stringify(handshakeBuffer))); send(obj); }; var onmessage = function(event) { processPackage(Package.decode(event.data), cb); // new package arrived, update the heartbeat timeout if(heartbeatTimeout) { nextHeartbeatTimeout = Date.now() + heartbeatTimeout; } }; var onerror = function(event) { pinus.emit('io-error', event); console.error('socket error: ', event); }; var onclose = function(event){ pinus.emit('close',event); console.error('socket close: ', event); }; socket = new WebSocket(url); socket.binaryType = 'arraybuffer'; socket.onopen = onopen; socket.onmessage = onmessage; socket.onerror = onerror; socket.onclose = onclose; }
Get tag head without move the offset
initWebSocket
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
onopen = function(event){ var obj = Package.encode(Package.TYPE_HANDSHAKE, Protocol.strencode(JSON.stringify(handshakeBuffer))); send(obj); }
Get tag head without move the offset
onopen
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
onmessage = function(event) { processPackage(Package.decode(event.data), cb); // new package arrived, update the heartbeat timeout if(heartbeatTimeout) { nextHeartbeatTimeout = Date.now() + heartbeatTimeout; } }
Get tag head without move the offset
onmessage
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
onerror = function(event) { pinus.emit('io-error', event); console.error('socket error: ', event); }
Get tag head without move the offset
onerror
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
onclose = function(event){ pinus.emit('close',event); console.error('socket close: ', event); }
Get tag head without move the offset
onclose
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
sendMessage = function(reqId, route, msg) { var type = reqId ? Message.TYPE_REQUEST : Message.TYPE_NOTIFY; //compress message by protobuf var protos = !!pinus.data.protos?pinus.data.protos.client:{}; if(!!protos[route]){ msg = protobuf.encode(route, msg); }else{ msg = Protocol.strencode(JSON.stringify(msg)); } var compressRoute = 0; if(pinus.dict && pinus.dict[route]){ route = pinus.dict[route]; compressRoute = 1; } msg = Message.encode(reqId, type, compressRoute, route, msg); var packet = Package.encode(Package.TYPE_DATA, msg); send(packet); }
Get tag head without move the offset
sendMessage
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
heartbeat = function(data) { if(!heartbeatInterval) { // no heartbeat return; } var obj = Package.encode(Package.TYPE_HEARTBEAT); if(heartbeatTimeoutId) { clearTimeout(heartbeatTimeoutId); heartbeatTimeoutId = null; } if(heartbeatId) { // already in a heartbeat interval return; } heartbeatId = setTimeout(function() { heartbeatId = null; send(obj); nextHeartbeatTimeout = Date.now() + heartbeatTimeout; heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, heartbeatTimeout); }, heartbeatInterval); }
Get tag head without move the offset
heartbeat
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
heartbeatTimeoutCb = function() { var gap = nextHeartbeatTimeout - Date.now(); if(gap > gapThreshold) { heartbeatTimeoutId = setTimeout(heartbeatTimeoutCb, gap); } else { console.error('server heartbeat timeout'); pinus.emit('heartbeat timeout'); pinus.disconnect(); } }
Get tag head without move the offset
heartbeatTimeoutCb
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
handshake = function(data){ data = JSON.parse(Protocol.strdecode(data)); if(data.code === RES_OLD_CLIENT) { pinus.emit('error', 'client version not fullfill'); return; } if(data.code !== RES_OK) { pinus.emit('error', 'handshake fail'); return; } handshakeInit(data); var obj = Package.encode(Package.TYPE_HANDSHAKE_ACK); send(obj); if(initCallback) { initCallback(socket); initCallback = null; } }
Get tag head without move the offset
handshake
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
onData = function(data){ //probuff decode var msg = Message.decode(data); if(msg.id > 0){ msg.route = routeMap[msg.id]; delete routeMap[msg.id]; if(!msg.route){ return; } } msg.body = deCompose(msg); processMessage(pinus, msg); }
Get tag head without move the offset
onData
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
processMessage = function(pinus, msg) { if(!msg.id) { // server push message pinus.emit(msg.route, msg.body); return; } //if have a id then find the callback function with the request var cb = callbacks[msg.id]; delete callbacks[msg.id]; if(typeof cb !== 'function') { return; } cb(msg.body); return; }
Get tag head without move the offset
processMessage
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
processMessageBatch = function(pinus, msgs) { for(var i=0, l=msgs.length; i<l; i++) { processMessage(pinus, msgs[i]); } }
Get tag head without move the offset
processMessageBatch
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
deCompose = function(msg){ var protos = !!pinus.data.protos?pinus.data.protos.server:{}; var abbrs = pinus.data.abbrs; var route = msg.route; //Decompose route from dict if(msg.compressRoute) { if(!abbrs[route]){ return {}; } route = msg.route = abbrs[route]; } if(!!protos[route]){ return protobuf.decode(route, msg.body); }else{ return JSON.parse(Protocol.strdecode(msg.body)); } return msg; }
Get tag head without move the offset
deCompose
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
handshakeInit = function(data){ if(data.sys && data.sys.heartbeat) { heartbeatInterval = data.sys.heartbeat * 1000; // heartbeat interval heartbeatTimeout = heartbeatInterval * 2; // max heartbeat timeout } else { heartbeatInterval = 0; heartbeatTimeout = 0; } initData(data); if(typeof handshakeCallback === 'function') { handshakeCallback(data.user); } }
Get tag head without move the offset
handshakeInit
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
initData = function(data){ if(!data || !data.sys) { return; } pinus.data = pinus.data || {}; var dict = data.sys.dict; var protos = data.sys.protos; //Init compress dict if(dict){ pinus.data.dict = dict; pinus.data.abbrs = {}; for(var route in dict){ pinus.data.abbrs[dict[route]] = route; } } //Init protobuf protos if(protos){ pinus.data.protos = { server : protos.server || {}, client : protos.client || {} }; if(!!protobuf){ protobuf.init({encoderProtos: protos.client, decoderProtos: protos.server}); } } }
Get tag head without move the offset
initData
javascript
node-pinus/pinus
examples/simple-example/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/simple-example/web-server/public/js/lib/build/build.js
MIT
function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module.exports) { module.exports = {}; module.client = module.component = true; module.call(this, module.exports, require.relative(resolved), module); } return module.exports; }
Require the given path. @param {String} path @return {Object} exports @api public
require
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
copyArray = function(dest, doffset, src, soffset, length) { if('function' === typeof src.copy) { // Buffer src.copy(dest, doffset, soffset, soffset + length); } else { // Uint8Array for(var index=0; index<length; index++){ dest[doffset++] = src[soffset++]; } } }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
copyArray
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
msgHasId = function(type) { return type === Message.TYPE_REQUEST || type === Message.TYPE_RESPONSE; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
msgHasId
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
msgHasRoute = function(type) { return type === Message.TYPE_REQUEST || type === Message.TYPE_NOTIFY || type === Message.TYPE_PUSH; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
msgHasRoute
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
caculateMsgIdBytes = function(id) { var len = 0; do { len += 1; id >>= 7; } while(id > 0); return len; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
caculateMsgIdBytes
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
encodeMsgFlag = function(type, compressRoute, buffer, offset) { if(type !== Message.TYPE_REQUEST && type !== Message.TYPE_NOTIFY && type !== Message.TYPE_RESPONSE && type !== Message.TYPE_PUSH) { throw new Error('unkonw message type: ' + type); } buffer[offset] = (type << 1) | (compressRoute ? 1 : 0); return offset + MSG_FLAG_BYTES; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
encodeMsgFlag
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
encodeMsgId = function(id, idBytes, buffer, offset) { var index = offset + idBytes - 1; buffer[index--] = id & 0x7f; while(index >= offset) { id >>= 7; buffer[index--] = id & 0x7f | 0x80; } return offset + idBytes; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
encodeMsgId
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
encodeMsgRoute = function(compressRoute, route, buffer, offset) { if (compressRoute) { if(route > MSG_ROUTE_CODE_MAX){ throw new Error('route number is overflow'); } buffer[offset++] = (route >> 8) & 0xff; buffer[offset++] = route & 0xff; } else { if(route) { buffer[offset++] = route.length & 0xff; copyArray(buffer, offset, route, 0, route.length); offset += route.length; } else { buffer[offset++] = 0; } } return offset; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
encodeMsgRoute
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
encodeMsgBody = function(msg, buffer, offset) { copyArray(buffer, offset, msg, 0, msg.length); return offset + msg.length; }
Message protocol decode. @param {Buffer|Uint8Array} buffer message bytes @return {Object} message object
encodeMsgBody
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
function checkMsg(msg, protos){ if(!protos){ return false; } for(var name in protos){ var proto = protos[name]; //All required element must exist switch(proto.option){ case 'required' : if(typeof(msg[name]) === 'undefined'){ return false; } case 'optional' : if(typeof(msg[name]) !== 'undefined'){ if(!!protos.__messages[proto.type]){ checkMsg(msg[name], protos.__messages[proto.type]); } } break; case 'repeated' : //Check nest message in repeated elements if(!!msg[name] && !!protos.__messages[proto.type]){ for(var i = 0; i < msg[name].length; i++){ if(!checkMsg(msg[name][i], protos.__messages[proto.type])){ return false; } } } break; } } return true; }
Check if the msg follow the defination in the protos
checkMsg
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
function encodeMsg(buffer, offset, protos, msg){ for(var name in msg){ if(!!protos[name]){ var proto = protos[name]; switch(proto.option){ case 'required' : case 'optional' : offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); offset = encodeProp(msg[name], proto.type, offset, buffer, protos); break; case 'repeated' : if(msg[name].length > 0){ offset = encodeArray(msg[name], proto, offset, buffer, protos); } break; } } } return offset; }
Check if the msg follow the defination in the protos
encodeMsg
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
function encodeProp(value, type, offset, buffer, protos){ switch(type){ case 'uInt32': offset = writeBytes(buffer, offset, codec.encodeUInt32(value)); break; case 'int32' : case 'sInt32': offset = writeBytes(buffer, offset, codec.encodeSInt32(value)); break; case 'float': writeBytes(buffer, offset, codec.encodeFloat(value)); offset += 4; break; case 'double': writeBytes(buffer, offset, codec.encodeDouble(value)); offset += 8; break; case 'string': var length = codec.byteLength(value); //Encode length offset = writeBytes(buffer, offset, codec.encodeUInt32(length)); //write string codec.encodeStr(buffer, offset, value); offset += length; break; default : if(!!protos.__messages[type]){ //Use a tmp buffer to build an internal msg var tmpBuffer = new ArrayBuffer(codec.byteLength(JSON.stringify(value))); var length = 0; length = encodeMsg(tmpBuffer, length, protos.__messages[type], value); //Encode length offset = writeBytes(buffer, offset, codec.encodeUInt32(length)); //contact the object for(var i = 0; i < length; i++){ buffer[offset] = tmpBuffer[i]; offset++; } } break; } return offset; }
Check if the msg follow the defination in the protos
encodeProp
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
function encodeArray(array, proto, offset, buffer, protos){ var i = 0; if(util.isSimpleType(proto.type)){ offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); offset = writeBytes(buffer, offset, codec.encodeUInt32(array.length)); for(i = 0; i < array.length; i++){ offset = encodeProp(array[i], proto.type, offset, buffer); } }else{ for(i = 0; i < array.length; i++){ offset = writeBytes(buffer, offset, encodeTag(proto.type, proto.tag)); offset = encodeProp(array[i], proto.type, offset, buffer, protos); } } return offset; }
Encode reapeated properties, simple msg and object are decode differented
encodeArray
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
function writeBytes(buffer, offset, bytes){ for(var i = 0; i < bytes.length; i++, offset++){ buffer[offset] = bytes[i]; } return offset; }
Encode reapeated properties, simple msg and object are decode differented
writeBytes
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT
function encodeTag(type, tag){ var value = constant.TYPES[type]||2; return codec.encodeUInt32((tag<<3)|value); }
Encode reapeated properties, simple msg and object are decode differented
encodeTag
javascript
node-pinus/pinus
examples/ssl-connector/web-server/public/js/lib/build/build.js
https://github.com/node-pinus/pinus/blob/master/examples/ssl-connector/web-server/public/js/lib/build/build.js
MIT