").append( jQuery.parseHTML( responseText ) ).find( selector ) :
+
+ // Otherwise use the full result
+ responseText );
+
+ }).complete( callback && function( jqXHR, status ) {
+ self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
+ });
+ }
+
+ return this;
+};
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
+ jQuery.fn[ type ] = function( fn ){
+ return this.on( type, fn );
+ };
+});
+
+jQuery.each( [ "get", "post" ], function( i, method ) {
+ jQuery[ method ] = function( url, data, callback, type ) {
+ // shift arguments if data argument was omitted
+ if ( jQuery.isFunction( data ) ) {
+ type = type || callback;
+ callback = data;
+ data = undefined;
+ }
+
+ return jQuery.ajax({
+ url: url,
+ type: method,
+ dataType: type,
+ data: data,
+ success: callback
+ });
+ };
+});
+
+jQuery.extend({
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+ etag: {},
+
+ ajaxSettings: {
+ url: ajaxLocation,
+ type: "GET",
+ isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
+ global: true,
+ processData: true,
+ async: true,
+ contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+ /*
+ timeout: 0,
+ data: null,
+ dataType: null,
+ username: null,
+ password: null,
+ cache: null,
+ throws: false,
+ traditional: false,
+ headers: {},
+ */
+
+ accepts: {
+ "*": allTypes,
+ text: "text/plain",
+ html: "text/html",
+ xml: "application/xml, text/xml",
+ json: "application/json, text/javascript"
+ },
+
+ contents: {
+ xml: /xml/,
+ html: /html/,
+ json: /json/
+ },
+
+ responseFields: {
+ xml: "responseXML",
+ text: "responseText"
+ },
+
+ // Data converters
+ // Keys separate source (or catchall "*") and destination types with a single space
+ converters: {
+
+ // Convert anything to text
+ "* text": window.String,
+
+ // Text to html (true = no transformation)
+ "text html": true,
+
+ // Evaluate text as a json expression
+ "text json": jQuery.parseJSON,
+
+ // Parse text as xml
+ "text xml": jQuery.parseXML
+ },
+
+ // For options that shouldn't be deep extended:
+ // you can add your own custom options here if
+ // and when you create one that shouldn't be
+ // deep extended (see ajaxExtend)
+ flatOptions: {
+ url: true,
+ context: true
+ }
+ },
+
+ // Creates a full fledged settings object into target
+ // with both ajaxSettings and settings fields.
+ // If target is omitted, writes into ajaxSettings.
+ ajaxSetup: function( target, settings ) {
+ return settings ?
+
+ // Building a settings object
+ ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
+
+ // Extending ajaxSettings
+ ajaxExtend( jQuery.ajaxSettings, target );
+ },
+
+ ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
+ ajaxTransport: addToPrefiltersOrTransports( transports ),
+
+ // Main method
+ ajax: function( url, options ) {
+
+ // If url is an object, simulate pre-1.5 signature
+ if ( typeof url === "object" ) {
+ options = url;
+ url = undefined;
+ }
+
+ // Force options to be an object
+ options = options || {};
+
+ var // Cross-domain detection vars
+ parts,
+ // Loop variable
+ i,
+ // URL without anti-cache param
+ cacheURL,
+ // Response headers as string
+ responseHeadersString,
+ // timeout handle
+ timeoutTimer,
+
+ // To know if global events are to be dispatched
+ fireGlobals,
+
+ transport,
+ // Response headers
+ responseHeaders,
+ // Create the final options object
+ s = jQuery.ajaxSetup( {}, options ),
+ // Callbacks context
+ callbackContext = s.context || s,
+ // Context for global events is callbackContext if it is a DOM node or jQuery collection
+ globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
+ jQuery( callbackContext ) :
+ jQuery.event,
+ // Deferreds
+ deferred = jQuery.Deferred(),
+ completeDeferred = jQuery.Callbacks("once memory"),
+ // Status-dependent callbacks
+ statusCode = s.statusCode || {},
+ // Headers (they are sent all at once)
+ requestHeaders = {},
+ requestHeadersNames = {},
+ // The jqXHR state
+ state = 0,
+ // Default abort message
+ strAbort = "canceled",
+ // Fake xhr
+ jqXHR = {
+ readyState: 0,
+
+ // Builds headers hashtable if needed
+ getResponseHeader: function( key ) {
+ var match;
+ if ( state === 2 ) {
+ if ( !responseHeaders ) {
+ responseHeaders = {};
+ while ( (match = rheaders.exec( responseHeadersString )) ) {
+ responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
+ }
+ }
+ match = responseHeaders[ key.toLowerCase() ];
+ }
+ return match == null ? null : match;
+ },
+
+ // Raw string
+ getAllResponseHeaders: function() {
+ return state === 2 ? responseHeadersString : null;
+ },
+
+ // Caches the header
+ setRequestHeader: function( name, value ) {
+ var lname = name.toLowerCase();
+ if ( !state ) {
+ name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
+ requestHeaders[ name ] = value;
+ }
+ return this;
+ },
+
+ // Overrides response content-type header
+ overrideMimeType: function( type ) {
+ if ( !state ) {
+ s.mimeType = type;
+ }
+ return this;
+ },
+
+ // Status-dependent callbacks
+ statusCode: function( map ) {
+ var code;
+ if ( map ) {
+ if ( state < 2 ) {
+ for ( code in map ) {
+ // Lazy-add the new callback in a way that preserves old ones
+ statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
+ }
+ } else {
+ // Execute the appropriate callbacks
+ jqXHR.always( map[ jqXHR.status ] );
+ }
+ }
+ return this;
+ },
+
+ // Cancel the request
+ abort: function( statusText ) {
+ var finalText = statusText || strAbort;
+ if ( transport ) {
+ transport.abort( finalText );
+ }
+ done( 0, finalText );
+ return this;
+ }
+ };
+
+ // Attach deferreds
+ deferred.promise( jqXHR ).complete = completeDeferred.add;
+ jqXHR.success = jqXHR.done;
+ jqXHR.error = jqXHR.fail;
+
+ // Remove hash character (#7531: and string promotion)
+ // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
+ // Handle falsy url in the settings object (#10093: consistency with old signature)
+ // We also use the url parameter if available
+ s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
+
+ // Alias method option to type as per ticket #12004
+ s.type = options.method || options.type || s.method || s.type;
+
+ // Extract dataTypes list
+ s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
+
+ // A cross-domain request is in order when we have a protocol:host:port mismatch
+ if ( s.crossDomain == null ) {
+ parts = rurl.exec( s.url.toLowerCase() );
+ s.crossDomain = !!( parts &&
+ ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
+ ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
+ ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
+ );
+ }
+
+ // Convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" ) {
+ s.data = jQuery.param( s.data, s.traditional );
+ }
+
+ // Apply prefilters
+ inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
+
+ // If request was aborted inside a prefilter, stop there
+ if ( state === 2 ) {
+ return jqXHR;
+ }
+
+ // We can fire global events as of now if asked to
+ fireGlobals = s.global;
+
+ // Watch for a new set of requests
+ if ( fireGlobals && jQuery.active++ === 0 ) {
+ jQuery.event.trigger("ajaxStart");
+ }
+
+ // Uppercase the type
+ s.type = s.type.toUpperCase();
+
+ // Determine if request has content
+ s.hasContent = !rnoContent.test( s.type );
+
+ // Save the URL in case we're toying with the If-Modified-Since
+ // and/or If-None-Match header later on
+ cacheURL = s.url;
+
+ // More options handling for requests with no content
+ if ( !s.hasContent ) {
+
+ // If data is available, append data to url
+ if ( s.data ) {
+ cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
+ // #9682: remove data so that it's not used in an eventual retry
+ delete s.data;
+ }
+
+ // Add anti-cache in url if needed
+ if ( s.cache === false ) {
+ s.url = rts.test( cacheURL ) ?
+
+ // If there is already a '_' parameter, set its value
+ cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
+
+ // Otherwise add one to the end
+ cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
+ }
+ }
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ if ( jQuery.lastModified[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
+ }
+ if ( jQuery.etag[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
+ }
+ }
+
+ // Set the correct header, if data is being sent
+ if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+ jqXHR.setRequestHeader( "Content-Type", s.contentType );
+ }
+
+ // Set the Accepts header for the server, depending on the dataType
+ jqXHR.setRequestHeader(
+ "Accept",
+ s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+ s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
+ s.accepts[ "*" ]
+ );
+
+ // Check for headers option
+ for ( i in s.headers ) {
+ jqXHR.setRequestHeader( i, s.headers[ i ] );
+ }
+
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
+ // Abort if not done already and return
+ return jqXHR.abort();
+ }
+
+ // aborting is no longer a cancellation
+ strAbort = "abort";
+
+ // Install callbacks on deferreds
+ for ( i in { success: 1, error: 1, complete: 1 } ) {
+ jqXHR[ i ]( s[ i ] );
+ }
+
+ // Get transport
+ transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
+
+ // If no transport, we auto-abort
+ if ( !transport ) {
+ done( -1, "No Transport" );
+ } else {
+ jqXHR.readyState = 1;
+
+ // Send global event
+ if ( fireGlobals ) {
+ globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
+ }
+ // Timeout
+ if ( s.async && s.timeout > 0 ) {
+ timeoutTimer = setTimeout(function() {
+ jqXHR.abort("timeout");
+ }, s.timeout );
+ }
+
+ try {
+ state = 1;
+ transport.send( requestHeaders, done );
+ } catch ( e ) {
+ // Propagate exception as error if not done
+ if ( state < 2 ) {
+ done( -1, e );
+ // Simply rethrow otherwise
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ // Callback for when everything is done
+ 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;
+
+ // Get response data
+ if ( responses ) {
+ response = ajaxHandleResponses( s, jqXHR, responses );
+ }
+
+ // If successful, handle type chaining
+ if ( status >= 200 && status < 300 || status === 304 ) {
+
+ // 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 ) {
+ isSuccess = true;
+ statusText = "nocontent";
+
+ // if not modified
+ } else if ( status === 304 ) {
+ isSuccess = true;
+ statusText = "notmodified";
+
+ // If we have data, let's convert it
+ } else {
+ isSuccess = ajaxConvert( s, response );
+ statusText = isSuccess.state;
+ success = isSuccess.data;
+ error = isSuccess.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");
+ }
+ }
+ }
+
+ return jqXHR;
+ },
+
+ getScript: function( url, callback ) {
+ return jQuery.get( url, undefined, callback, "script" );
+ },
+
+ getJSON: function( url, data, callback ) {
+ return jQuery.get( url, data, callback, "json" );
+ }
+});
+
+/* Handles responses to an ajax request:
+ * - sets all responseXXX fields accordingly
+ * - finds the right dataType (mediates between content-type and expected dataType)
+ * - returns the corresponding response
+ */
+function ajaxHandleResponses( s, jqXHR, responses ) {
+ var firstDataType, ct, finalDataType, type,
+ contents = s.contents,
+ dataTypes = s.dataTypes,
+ responseFields = s.responseFields;
+
+ // Fill responseXXX fields
+ for ( type in responseFields ) {
+ if ( type in responses ) {
+ jqXHR[ responseFields[type] ] = responses[ type ];
+ }
+ }
+
+ // 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 ];
+ }
+}
+
+// Chain conversions given the request and the original response
+function ajaxConvert( s, response ) {
+ var conv2, current, conv, tmp,
+ converters = {},
+ i = 0,
+ // Work with a copy of dataTypes in case we need to modify it for conversion
+ dataTypes = s.dataTypes.slice(),
+ prev = dataTypes[ 0 ];
+
+ // Apply the dataFilter if provided
+ if ( s.dataFilter ) {
+ response = s.dataFilter( response, s.dataType );
+ }
+
+ // Create converters map with lowercased keys
+ if ( dataTypes[ 1 ] ) {
+ for ( conv in s.converters ) {
+ converters[ conv.toLowerCase() ] = s.converters[ conv ];
+ }
+ }
+
+ // Convert to each sequential dataType, tolerating list modification
+ for ( ; (current = dataTypes[++i]); ) {
+
+ // There's only work to do if current dataType is non-auto
+ if ( current !== "*" ) {
+
+ // Convert response if prev dataType is non-auto and differs from current
+ 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.splice( i--, 0, current );
+ }
+
+ 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 };
+ }
+ }
+ }
+ }
+
+ // Update prev for next iteration
+ prev = current;
+ }
+ }
+
+ return { state: "success", data: response };
+}
+// Install script dataType
+jQuery.ajaxSetup({
+ accepts: {
+ script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
+ },
+ contents: {
+ script: /(?:java|ecma)script/
+ },
+ converters: {
+ "text script": function( text ) {
+ jQuery.globalEval( text );
+ return text;
+ }
+ }
+});
+
+// Handle cache's special case and global
+jQuery.ajaxPrefilter( "script", function( s ) {
+ if ( s.cache === undefined ) {
+ s.cache = false;
+ }
+ if ( s.crossDomain ) {
+ s.type = "GET";
+ s.global = false;
+ }
+});
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function(s) {
+
+ // This transport only deals with cross domain requests
+ if ( s.crossDomain ) {
+
+ var script,
+ head = document.head || jQuery("head")[0] || document.documentElement;
+
+ return {
+
+ send: function( _, callback ) {
+
+ script = document.createElement("script");
+
+ script.async = true;
+
+ if ( s.scriptCharset ) {
+ script.charset = s.scriptCharset;
+ }
+
+ script.src = s.url;
+
+ // Attach handlers for all browsers
+ script.onload = script.onreadystatechange = function( _, isAbort ) {
+
+ if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
+
+ // Handle memory leak in IE
+ script.onload = script.onreadystatechange = null;
+
+ // Remove the script
+ if ( script.parentNode ) {
+ script.parentNode.removeChild( script );
+ }
+
+ // Dereference the script
+ script = null;
+
+ // Callback if not abort
+ if ( !isAbort ) {
+ callback( 200, "success" );
+ }
+ }
+ };
+
+ // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
+ // Use native DOM manipulation to avoid our domManip AJAX trickery
+ head.insertBefore( script, head.firstChild );
+ },
+
+ abort: function() {
+ if ( script ) {
+ script.onload( undefined, true );
+ }
+ }
+ };
+ }
+});
+var oldCallbacks = [],
+ rjsonp = /(=)\?(?=&|$)|\?\?/;
+
+// Default jsonp settings
+jQuery.ajaxSetup({
+ jsonp: "callback",
+ jsonpCallback: function() {
+ var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
+ this[ callback ] = true;
+ return callback;
+ }
+});
+
+// Detect, normalize options and install callbacks for jsonp requests
+jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
+
+ var callbackName, overwritten, responseContainer,
+ jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
+ "url" :
+ typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
+ );
+
+ // Handle iff the expected data type is "jsonp" or we have a parameter to set
+ if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
+
+ // Get callback name, remembering preexisting value associated with it
+ callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
+ s.jsonpCallback() :
+ s.jsonpCallback;
+
+ // Insert callback into url or form data
+ if ( jsonProp ) {
+ s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
+ } else if ( s.jsonp !== false ) {
+ s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
+ }
+
+ // Use data converter to retrieve json after script execution
+ s.converters["script json"] = function() {
+ if ( !responseContainer ) {
+ jQuery.error( callbackName + " was not called" );
+ }
+ return responseContainer[ 0 ];
+ };
+
+ // force json dataType
+ s.dataTypes[ 0 ] = "json";
+
+ // Install callback
+ overwritten = window[ callbackName ];
+ window[ callbackName ] = function() {
+ responseContainer = arguments;
+ };
+
+ // Clean-up function (fires after converters)
+ jqXHR.always(function() {
+ // Restore preexisting value
+ window[ callbackName ] = overwritten;
+
+ // Save back as free
+ if ( s[ callbackName ] ) {
+ // make sure that re-using the options doesn't screw things around
+ s.jsonpCallback = originalSettings.jsonpCallback;
+
+ // save the callback name for future use
+ oldCallbacks.push( callbackName );
+ }
+
+ // Call if it was a function and we have a response
+ if ( responseContainer && jQuery.isFunction( overwritten ) ) {
+ overwritten( responseContainer[ 0 ] );
+ }
+
+ responseContainer = overwritten = undefined;
+ });
+
+ // Delegate to script
+ return "script";
+ }
+});
+var xhrCallbacks, xhrSupported,
+ xhrId = 0,
+ // #5280: Internet Explorer will keep connections alive if we don't abort on unload
+ xhrOnUnloadAbort = window.ActiveXObject && function() {
+ // Abort all pending requests
+ var key;
+ for ( key in xhrCallbacks ) {
+ xhrCallbacks[ key ]( undefined, true );
+ }
+ };
+
+// Functions to create xhrs
+function createStandardXHR() {
+ try {
+ return new window.XMLHttpRequest();
+ } catch( e ) {}
+}
+
+function createActiveXHR() {
+ try {
+ return new window.ActiveXObject("Microsoft.XMLHTTP");
+ } catch( e ) {}
+}
+
+// Create the request object
+// (This is still attached to ajaxSettings for backward compatibility)
+jQuery.ajaxSettings.xhr = window.ActiveXObject ?
+ /* Microsoft failed to properly
+ * implement the XMLHttpRequest in IE7 (can't request local files),
+ * so we use the ActiveXObject when it is available
+ * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
+ * we need a fallback.
+ */
+ function() {
+ return !this.isLocal && createStandardXHR() || createActiveXHR();
+ } :
+ // For all other browsers, use the standard XMLHttpRequest object
+ createStandardXHR;
+
+// Determine support properties
+xhrSupported = jQuery.ajaxSettings.xhr();
+jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
+xhrSupported = jQuery.support.ajax = !!xhrSupported;
+
+// Create transport if the browser can provide an xhr
+if ( xhrSupported ) {
+
+ jQuery.ajaxTransport(function( s ) {
+ // Cross domain only allowed if supported through XMLHttpRequest
+ if ( !s.crossDomain || jQuery.support.cors ) {
+
+ var callback;
+
+ return {
+ send: function( headers, complete ) {
+
+ // Get a new xhr
+ var handle, i,
+ xhr = s.xhr();
+
+ // Open the socket
+ // Passing null username, generates a login popup on Opera (#2865)
+ if ( s.username ) {
+ xhr.open( s.type, s.url, s.async, s.username, s.password );
+ } else {
+ xhr.open( s.type, s.url, s.async );
+ }
+
+ // Apply custom fields if provided
+ if ( s.xhrFields ) {
+ for ( i in s.xhrFields ) {
+ xhr[ i ] = s.xhrFields[ i ];
+ }
+ }
+
+ // Override mime type if needed
+ if ( s.mimeType && xhr.overrideMimeType ) {
+ xhr.overrideMimeType( s.mimeType );
+ }
+
+ // X-Requested-With header
+ // For cross-domain requests, seeing as conditions for a preflight are
+ // akin to a jigsaw puzzle, we simply never set it to be sure.
+ // (it can always be set on a per-request basis or even using ajaxSetup)
+ // For same-domain requests, won't change header if already provided.
+ if ( !s.crossDomain && !headers["X-Requested-With"] ) {
+ headers["X-Requested-With"] = "XMLHttpRequest";
+ }
+
+ // Need an extra try/catch for cross domain requests in Firefox 3
+ try {
+ for ( i in headers ) {
+ xhr.setRequestHeader( i, headers[ i ] );
+ }
+ } catch( err ) {}
+
+ // Do send the request
+ // This may raise an exception which is actually
+ // handled in jQuery.ajax (so no try/catch here)
+ xhr.send( ( s.hasContent && s.data ) || null );
+
+ // Listener
+ callback = function( _, isAbort ) {
+ var status, responseHeaders, statusText, responses;
+
+ // Firefox throws exceptions when accessing properties
+ // of an xhr when a network error occurred
+ // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
+ try {
+
+ // Was never called and is aborted or complete
+ if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
+
+ // Only called once
+ callback = undefined;
+
+ // Do not keep as active anymore
+ if ( handle ) {
+ xhr.onreadystatechange = jQuery.noop;
+ if ( xhrOnUnloadAbort ) {
+ delete xhrCallbacks[ handle ];
+ }
+ }
+
+ // If it's an abort
+ if ( isAbort ) {
+ // Abort it manually if needed
+ if ( xhr.readyState !== 4 ) {
+ xhr.abort();
+ }
+ } else {
+ responses = {};
+ status = xhr.status;
+ responseHeaders = xhr.getAllResponseHeaders();
+
+ // When requesting binary data, IE6-9 will throw an exception
+ // on any attempt to access responseText (#11426)
+ if ( typeof xhr.responseText === "string" ) {
+ responses.text = xhr.responseText;
+ }
+
+ // Firefox throws an exception when accessing
+ // statusText for faulty cross-domain requests
+ try {
+ statusText = xhr.statusText;
+ } catch( e ) {
+ // We normalize with Webkit giving an empty statusText
+ statusText = "";
+ }
+
+ // Filter status for non standard behaviors
+
+ // If the request is local and we have data: assume a success
+ // (success with no data won't get notified, that's the best we
+ // can do given current implementations)
+ if ( !status && s.isLocal && !s.crossDomain ) {
+ status = responses.text ? 200 : 404;
+ // IE - #1450: sometimes returns 1223 when it should be 204
+ } else if ( status === 1223 ) {
+ status = 204;
+ }
+ }
+ }
+ } catch( firefoxAccessException ) {
+ if ( !isAbort ) {
+ complete( -1, firefoxAccessException );
+ }
+ }
+
+ // Call complete if needed
+ if ( responses ) {
+ complete( status, statusText, responses, responseHeaders );
+ }
+ };
+
+ if ( !s.async ) {
+ // if we're in sync mode we fire the callback
+ callback();
+ } else if ( xhr.readyState === 4 ) {
+ // (IE6 & IE7) if it's in cache and has been
+ // retrieved directly we need to fire the callback
+ setTimeout( callback );
+ } else {
+ handle = ++xhrId;
+ if ( xhrOnUnloadAbort ) {
+ // Create the active xhrs callbacks list if needed
+ // and attach the unload handler
+ if ( !xhrCallbacks ) {
+ xhrCallbacks = {};
+ jQuery( window ).unload( xhrOnUnloadAbort );
+ }
+ // Add to list of active xhrs callbacks
+ xhrCallbacks[ handle ] = callback;
+ }
+ xhr.onreadystatechange = callback;
+ }
+ },
+
+ abort: function() {
+ if ( callback ) {
+ callback( undefined, true );
+ }
+ }
+ };
+ }
+ });
+}
+var fxNow, timerId,
+ rfxtypes = /^(?:toggle|show|hide)$/,
+ rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
+ rrun = /queueHooks$/,
+ animationPrefilters = [ defaultPrefilter ],
+ tweeners = {
+ "*": [function( prop, value ) {
+ var end, unit,
+ tween = this.createTween( prop, value ),
+ parts = rfxnum.exec( value ),
+ target = tween.cur(),
+ start = +target || 0,
+ scale = 1,
+ maxIterations = 20;
+
+ if ( parts ) {
+ end = +parts[2];
+ unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
+
+ // We need to compute starting value
+ if ( unit !== "px" && start ) {
+ // Iteratively approximate from a nonzero starting point
+ // Prefer the current property, because this process will be trivial if it uses the same units
+ // Fallback to end or a simple constant
+ start = jQuery.css( tween.elem, prop, true ) || end || 1;
+
+ do {
+ // If previous iteration zeroed out, double until we get *something*
+ // Use a string for doubling factor so we don't accidentally see scale as unchanged below
+ scale = scale || ".5";
+
+ // Adjust and apply
+ start = start / scale;
+ jQuery.style( tween.elem, prop, start + unit );
+
+ // Update scale, tolerating zero or NaN from tween.cur()
+ // And breaking the loop if scale is unchanged or perfect, or if we've just had enough
+ } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
+ }
+
+ tween.unit = unit;
+ tween.start = start;
+ // If a +=/-= token was provided, we're doing a relative animation
+ tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
+ }
+ return tween;
+ }]
+ };
+
+// Animations created synchronously will run synchronously
+function createFxNow() {
+ setTimeout(function() {
+ fxNow = undefined;
+ });
+ return ( fxNow = jQuery.now() );
+}
+
+function createTweens( animation, props ) {
+ jQuery.each( props, function( prop, value ) {
+ var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
+ index = 0,
+ length = collection.length;
+ for ( ; index < length; index++ ) {
+ if ( collection[ index ].call( animation, prop, value ) ) {
+
+ // we're done with this property
+ return;
+ }
+ }
+ });
+}
+
+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;
+ }
+ }
+
+ createTweens( animation, props );
+
+ 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 );
+}
+
+function propFilter( props, specialEasing ) {
+ var value, name, index, easing, 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;
+ }
+ }
+}
+
+jQuery.Animation = jQuery.extend( Animation, {
+
+ tweener: function( props, callback ) {
+ if ( jQuery.isFunction( props ) ) {
+ callback = props;
+ props = [ "*" ];
+ } else {
+ props = props.split(" ");
+ }
+
+ var prop,
+ index = 0,
+ length = props.length;
+
+ for ( ; index < length ; index++ ) {
+ prop = props[ index ];
+ tweeners[ prop ] = tweeners[ prop ] || [];
+ tweeners[ prop ].unshift( callback );
+ }
+ },
+
+ prefilter: function( callback, prepend ) {
+ if ( prepend ) {
+ animationPrefilters.unshift( callback );
+ } else {
+ animationPrefilters.push( callback );
+ }
+ }
+});
+
+function defaultPrefilter( elem, props, opts ) {
+ /*jshint validthis:true */
+ var prop, index, length,
+ value, dataShow, toggle,
+ tween, hooks, oldfire,
+ anim = this,
+ style = elem.style,
+ orig = {},
+ handled = [],
+ hidden = elem.nodeType && isHidden( elem );
+
+ // 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
+ if ( jQuery.css( elem, "display" ) === "inline" &&
+ jQuery.css( elem, "float" ) === "none" ) {
+
+ // inline-level elements accept inline-block;
+ // block-level elements need to be inline with layout
+ if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
+ style.display = "inline-block";
+
+ } else {
+ style.zoom = 1;
+ }
+ }
+ }
+
+ if ( opts.overflow ) {
+ style.overflow = "hidden";
+ if ( !jQuery.support.shrinkWrapBlocks ) {
+ anim.always(function() {
+ style.overflow = opts.overflow[ 0 ];
+ style.overflowX = opts.overflow[ 1 ];
+ style.overflowY = opts.overflow[ 2 ];
+ });
+ }
+ }
+
+
+ // show/hide pass
+ for ( index in props ) {
+ value = props[ index ];
+ if ( rfxtypes.exec( value ) ) {
+ delete props[ index ];
+ toggle = toggle || value === "toggle";
+ if ( value === ( hidden ? "hide" : "show" ) ) {
+ continue;
+ }
+ handled.push( index );
+ }
+ }
+
+ length = handled.length;
+ if ( length ) {
+ dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
+ if ( "hidden" in dataShow ) {
+ hidden = dataShow.hidden;
+ }
+
+ // 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 ( index = 0 ; index < length ; index++ ) {
+ prop = handled[ index ];
+ tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
+ orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
+
+ if ( !( prop in dataShow ) ) {
+ dataShow[ prop ] = tween.start;
+ if ( hidden ) {
+ tween.end = tween.start;
+ tween.start = prop === "width" || prop === "height" ? 1 : 0;
+ }
+ }
+ }
+ }
+}
+
+function Tween( elem, options, prop, end, easing ) {
+ return new Tween.prototype.init( elem, options, prop, end, easing );
+}
+jQuery.Tween = Tween;
+
+Tween.prototype = {
+ constructor: Tween,
+ init: function( elem, options, prop, end, easing, unit ) {
+ this.elem = elem;
+ this.prop = prop;
+ this.easing = easing || "swing";
+ this.options = options;
+ this.start = this.now = this.cur();
+ this.end = end;
+ this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
+ },
+ cur: function() {
+ var hooks = Tween.propHooks[ this.prop ];
+
+ return hooks && hooks.get ?
+ hooks.get( this ) :
+ Tween.propHooks._default.get( this );
+ },
+ run: function( percent ) {
+ var eased,
+ hooks = Tween.propHooks[ this.prop ];
+
+ if ( this.options.duration ) {
+ this.pos = eased = jQuery.easing[ this.easing ](
+ percent, this.options.duration * percent, 0, 1, this.options.duration
+ );
+ } else {
+ this.pos = eased = percent;
+ }
+ this.now = ( this.end - this.start ) * eased + this.start;
+
+ if ( this.options.step ) {
+ this.options.step.call( this.elem, this.now, this );
+ }
+
+ if ( hooks && hooks.set ) {
+ hooks.set( this );
+ } else {
+ Tween.propHooks._default.set( this );
+ }
+ return this;
+ }
+};
+
+Tween.prototype.init.prototype = Tween.prototype;
+
+Tween.propHooks = {
+ _default: {
+ get: function( tween ) {
+ var result;
+
+ if ( tween.elem[ tween.prop ] != null &&
+ (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
+ return tween.elem[ tween.prop ];
+ }
+
+ // passing an empty string as a 3rd parameter to .css will automatically
+ // attempt a parseFloat and fallback to a string if the parse fails
+ // so, simple values such as "10px" are parsed to Float.
+ // complex values such as "rotate(1rad)" are returned as is.
+ result = jQuery.css( tween.elem, tween.prop, "" );
+ // Empty strings, null, undefined and "auto" are converted to 0.
+ return !result || result === "auto" ? 0 : result;
+ },
+ set: function( tween ) {
+ // use step hook for back compat - use cssHook if its there - use .style if its
+ // available and use plain properties where available
+ if ( jQuery.fx.step[ tween.prop ] ) {
+ jQuery.fx.step[ tween.prop ]( tween );
+ } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
+ jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
+ } else {
+ tween.elem[ tween.prop ] = tween.now;
+ }
+ }
+ }
+};
+
+// Remove in 2.0 - this supports IE8's panic based approach
+// to setting things on disconnected nodes
+
+Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
+ set: function( tween ) {
+ if ( tween.elem.nodeType && tween.elem.parentNode ) {
+ tween.elem[ tween.prop ] = tween.now;
+ }
+ }
+};
+
+jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
+ var cssFn = jQuery.fn[ name ];
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return speed == null || typeof speed === "boolean" ?
+ cssFn.apply( this, arguments ) :
+ this.animate( genFx( name, true ), speed, easing, callback );
+ };
+});
+
+jQuery.fn.extend({
+ fadeTo: function( speed, to, easing, callback ) {
+
+ // show any hidden elements after setting opacity to 0
+ return this.filter( isHidden ).css( "opacity", 0 ).show()
+
+ // animate to the value specified
+ .end().animate({ opacity: to }, speed, easing, callback );
+ },
+ animate: function( prop, speed, easing, callback ) {
+ var empty = jQuery.isEmptyObject( prop ),
+ optall = jQuery.speed( speed, easing, callback ),
+ doAnimation = function() {
+ // Operate on a copy of prop so per-property easing won't be lost
+ var anim = Animation( this, jQuery.extend( {}, prop ), optall );
+ doAnimation.finish = function() {
+ anim.stop( true );
+ };
+ // Empty animations, or finishing resolves immediately
+ if ( empty || jQuery._data( this, "finish" ) ) {
+ anim.stop( true );
+ }
+ };
+ doAnimation.finish = doAnimation;
+
+ return empty || optall.queue === false ?
+ this.each( doAnimation ) :
+ this.queue( optall.queue, doAnimation );
+ },
+ stop: function( type, clearQueue, gotoEnd ) {
+ var stopQueue = function( hooks ) {
+ var stop = hooks.stop;
+ delete hooks.stop;
+ stop( gotoEnd );
+ };
+
+ if ( typeof type !== "string" ) {
+ gotoEnd = clearQueue;
+ clearQueue = type;
+ type = undefined;
+ }
+ if ( clearQueue && type !== false ) {
+ this.queue( type || "fx", [] );
+ }
+
+ return this.each(function() {
+ var dequeue = true,
+ index = type != null && type + "queueHooks",
+ timers = jQuery.timers,
+ data = jQuery._data( this );
+
+ if ( index ) {
+ if ( data[ index ] && data[ index ].stop ) {
+ stopQueue( data[ index ] );
+ }
+ } else {
+ for ( index in data ) {
+ if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
+ stopQueue( data[ index ] );
+ }
+ }
+ }
+
+ for ( index = timers.length; index--; ) {
+ if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
+ timers[ index ].anim.stop( gotoEnd );
+ dequeue = false;
+ timers.splice( index, 1 );
+ }
+ }
+
+ // start the next in the queue if the last step wasn't forced
+ // timers currently will call their complete callbacks, which will dequeue
+ // but only if they were gotoEnd
+ if ( dequeue || !gotoEnd ) {
+ jQuery.dequeue( this, type );
+ }
+ });
+ },
+ finish: function( type ) {
+ if ( type !== false ) {
+ type = type || "fx";
+ }
+ return this.each(function() {
+ var index,
+ data = jQuery._data( this ),
+ queue = data[ type + "queue" ],
+ hooks = data[ type + "queueHooks" ],
+ timers = jQuery.timers,
+ length = queue ? queue.length : 0;
+
+ // enable finishing flag on private data
+ data.finish = true;
+
+ // empty the queue first
+ jQuery.queue( this, type, [] );
+
+ if ( hooks && hooks.cur && hooks.cur.finish ) {
+ hooks.cur.finish.call( this );
+ }
+
+ // look for any active animations, and finish them
+ for ( index = timers.length; index--; ) {
+ if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
+ timers[ index ].anim.stop( true );
+ timers.splice( index, 1 );
+ }
+ }
+
+ // look for any animations in the old queue and finish them
+ for ( index = 0; index < length; index++ ) {
+ if ( queue[ index ] && queue[ index ].finish ) {
+ queue[ index ].finish.call( this );
+ }
+ }
+
+ // turn off finishing flag
+ delete data.finish;
+ });
+ }
+});
+
+// Generate parameters to create a standard animation
+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;
+}
+
+// Generate shortcuts for custom animations
+jQuery.each({
+ slideDown: genFx("show"),
+ slideUp: genFx("hide"),
+ slideToggle: genFx("toggle"),
+ fadeIn: { opacity: "show" },
+ fadeOut: { opacity: "hide" },
+ fadeToggle: { opacity: "toggle" }
+}, function( name, props ) {
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return this.animate( props, speed, easing, callback );
+ };
+});
+
+jQuery.speed = function( speed, easing, fn ) {
+ var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
+ complete: fn || !fn && easing ||
+ jQuery.isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
+ };
+
+ opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+ opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
+
+ // normalize opt.queue - true/undefined/null -> "fx"
+ if ( opt.queue == null || opt.queue === true ) {
+ opt.queue = "fx";
+ }
+
+ // Queueing
+ opt.old = opt.complete;
+
+ opt.complete = function() {
+ if ( jQuery.isFunction( opt.old ) ) {
+ opt.old.call( this );
+ }
+
+ if ( opt.queue ) {
+ jQuery.dequeue( this, opt.queue );
+ }
+ };
+
+ return opt;
+};
+
+jQuery.easing = {
+ linear: function( p ) {
+ return p;
+ },
+ swing: function( p ) {
+ return 0.5 - Math.cos( p*Math.PI ) / 2;
+ }
+};
+
+jQuery.timers = [];
+jQuery.fx = Tween.prototype.init;
+jQuery.fx.tick = function() {
+ var timer,
+ timers = jQuery.timers,
+ i = 0;
+
+ fxNow = jQuery.now();
+
+ for ( ; i < timers.length; i++ ) {
+ timer = timers[ i ];
+ // Checks the timer has not already been removed
+ if ( !timer() && timers[ i ] === timer ) {
+ timers.splice( i--, 1 );
+ }
+ }
+
+ if ( !timers.length ) {
+ jQuery.fx.stop();
+ }
+ fxNow = undefined;
+};
+
+jQuery.fx.timer = function( timer ) {
+ if ( timer() && jQuery.timers.push( timer ) ) {
+ jQuery.fx.start();
+ }
+};
+
+jQuery.fx.interval = 13;
+
+jQuery.fx.start = function() {
+ if ( !timerId ) {
+ timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
+ }
+};
+
+jQuery.fx.stop = function() {
+ clearInterval( timerId );
+ timerId = null;
+};
+
+jQuery.fx.speeds = {
+ slow: 600,
+ fast: 200,
+ // Default speed
+ _default: 400
+};
+
+// Back Compat <1.8 extension point
+jQuery.fx.step = {};
+
+if ( jQuery.expr && jQuery.expr.filters ) {
+ jQuery.expr.filters.animated = function( elem ) {
+ return jQuery.grep(jQuery.timers, function( fn ) {
+ return elem === fn.elem;
+ }).length;
+ };
+}
+jQuery.fn.offset = function( options ) {
+ if ( arguments.length ) {
+ return options === undefined ?
+ this :
+ this.each(function( i ) {
+ jQuery.offset.setOffset( this, options, i );
+ });
+ }
+
+ var docElem, win,
+ box = { top: 0, left: 0 },
+ elem = this[ 0 ],
+ doc = elem && elem.ownerDocument;
+
+ if ( !doc ) {
+ return;
+ }
+
+ docElem = doc.documentElement;
+
+ // Make sure it's not a disconnected DOM node
+ if ( !jQuery.contains( docElem, elem ) ) {
+ return box;
+ }
+
+ // If we don't have gBCR, just use 0,0 rather than error
+ // BlackBerry 5, iOS 3 (original iPhone)
+ if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
+ box = elem.getBoundingClientRect();
+ }
+ win = getWindow( doc );
+ return {
+ top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
+ left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
+ };
+};
+
+jQuery.offset = {
+
+ setOffset: function( elem, options, i ) {
+ var position = jQuery.css( elem, "position" );
+
+ // set position first, in-case top/left are set even on static elem
+ if ( position === "static" ) {
+ elem.style.position = "relative";
+ }
+
+ var curElem = jQuery( elem ),
+ curOffset = curElem.offset(),
+ curCSSTop = jQuery.css( elem, "top" ),
+ curCSSLeft = jQuery.css( elem, "left" ),
+ calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
+ props = {}, curPosition = {}, curTop, curLeft;
+
+ // need to be able to calculate position if either top or left is auto and position is either absolute or fixed
+ if ( calculatePosition ) {
+ curPosition = curElem.position();
+ curTop = curPosition.top;
+ curLeft = curPosition.left;
+ } else {
+ curTop = parseFloat( curCSSTop ) || 0;
+ curLeft = parseFloat( curCSSLeft ) || 0;
+ }
+
+ if ( jQuery.isFunction( options ) ) {
+ options = options.call( elem, i, curOffset );
+ }
+
+ if ( options.top != null ) {
+ props.top = ( options.top - curOffset.top ) + curTop;
+ }
+ if ( options.left != null ) {
+ props.left = ( options.left - curOffset.left ) + curLeft;
+ }
+
+ if ( "using" in options ) {
+ options.using.call( elem, props );
+ } else {
+ curElem.css( props );
+ }
+ }
+};
+
+
+jQuery.fn.extend({
+
+ position: function() {
+ if ( !this[ 0 ] ) {
+ return;
+ }
+
+ var offsetParent, offset,
+ parentOffset = { top: 0, left: 0 },
+ elem = this[ 0 ];
+
+ // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
+ if ( jQuery.css( elem, "position" ) === "fixed" ) {
+ // we assume that getBoundingClientRect is available when computed position is fixed
+ offset = elem.getBoundingClientRect();
+ } else {
+ // Get *real* offsetParent
+ offsetParent = this.offsetParent();
+
+ // Get correct offsets
+ offset = this.offset();
+ if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
+ parentOffset = offsetParent.offset();
+ }
+
+ // Add offsetParent borders
+ parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
+ parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
+ }
+
+ // Subtract parent offsets and element margins
+ // note: when an element has margin: auto the offsetLeft and marginLeft
+ // are the same in Safari causing offset.left to incorrectly be 0
+ return {
+ top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
+ left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
+ };
+ },
+
+ offsetParent: function() {
+ return this.map(function() {
+ var offsetParent = this.offsetParent || document.documentElement;
+ while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
+ offsetParent = offsetParent.offsetParent;
+ }
+ return offsetParent || document.documentElement;
+ });
+ }
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
+ var top = /Y/.test( prop );
+
+ jQuery.fn[ method ] = function( val ) {
+ return jQuery.access( this, function( elem, method, val ) {
+ var win = getWindow( elem );
+
+ if ( val === undefined ) {
+ return win ? (prop in win) ? win[ prop ] :
+ win.document.documentElement[ method ] :
+ elem[ method ];
+ }
+
+ if ( win ) {
+ win.scrollTo(
+ !top ? val : jQuery( win ).scrollLeft(),
+ top ? val : jQuery( win ).scrollTop()
+ );
+
+ } else {
+ elem[ method ] = val;
+ }
+ }, method, val, arguments.length, null );
+ };
+});
+
+function getWindow( elem ) {
+ return jQuery.isWindow( elem ) ?
+ elem :
+ elem.nodeType === 9 ?
+ elem.defaultView || elem.parentWindow :
+ false;
+}
+// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
+jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
+ jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
+ // margin is only for outerHeight, outerWidth
+ jQuery.fn[ funcName ] = function( margin, value ) {
+ var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
+ extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
+
+ return jQuery.access( this, function( elem, type, value ) {
+ var doc;
+
+ if ( jQuery.isWindow( elem ) ) {
+ // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
+ // isn't a whole lot we can do. See pull request at this URL for discussion:
+ // https://github.com/jquery/jquery/pull/764
+ return elem.document.documentElement[ "client" + name ];
+ }
+
+ // Get document width or height
+ if ( elem.nodeType === 9 ) {
+ doc = elem.documentElement;
+
+ // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
+ // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
+ return Math.max(
+ elem.body[ "scroll" + name ], doc[ "scroll" + name ],
+ elem.body[ "offset" + name ], doc[ "offset" + name ],
+ doc[ "client" + name ]
+ );
+ }
+
+ return value === undefined ?
+ // Get width or height on the element, requesting but not forcing parseFloat
+ jQuery.css( elem, type, extra ) :
+
+ // Set width or height on the element
+ jQuery.style( elem, type, value, extra );
+ }, type, chainable ? margin : undefined, chainable, null );
+ };
+ });
+});
+// Limit scope pollution from any deprecated API
+// (function() {
+
+// })();
+// Expose jQuery to the global object
+window.jQuery = window.$ = jQuery;
+
+// Expose jQuery as an AMD module, but only for AMD loaders that
+// understand the issues with loading multiple versions of jQuery
+// in a page that all might call define(). The loader will indicate
+// they have special allowances for multiple jQuery versions by
+// specifying define.amd.jQuery = true. Register as a named module,
+// since jQuery can be concatenated with other files that may use define,
+// but not use a proper concatenation script that understands anonymous
+// AMD modules. A named AMD is safest and most robust way to register.
+// Lowercase jquery is used because AMD module names are derived from
+// file names, and jQuery is normally delivered in a lowercase file name.
+// Do this after creating the global so that if an AMD module wants to call
+// noConflict to hide this version of jQuery, it will work.
+if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
+ define( "jquery", [], function () { return jQuery; } );
+}
+
+})( window );
\ No newline at end of file
diff --git a/labs/dependency-examples/backbone_marionette_require/bower_components/requirejs/require.js b/labs/dependency-examples/backbone_marionette_require/bower_components/requirejs/require.js
new file mode 100644
index 0000000000..2109a25149
--- /dev/null
+++ b/labs/dependency-examples/backbone_marionette_require/bower_components/requirejs/require.js
@@ -0,0 +1,2045 @@
+/** vim: et:ts=4:sw=4:sts=4
+ * @license RequireJS 2.1.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+//Not using strict: uneven strict support in browsers, #392, and causes
+//problems with requirejs.exec()/transpiler plugins that may not be strict.
+/*jslint regexp: true, nomen: true, sloppy: true */
+/*global window, navigator, document, importScripts, setTimeout, opera */
+
+var requirejs, require, define;
+(function (global) {
+ var req, s, head, baseElement, dataMain, src,
+ interactiveScript, currentlyAddingScript, mainScript, subPath,
+ version = '2.1.6',
+ commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
+ cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
+ jsSuffixRegExp = /\.js$/,
+ currDirRegExp = /^\.\//,
+ op = Object.prototype,
+ ostring = op.toString,
+ hasOwn = op.hasOwnProperty,
+ ap = Array.prototype,
+ apsp = ap.splice,
+ isBrowser = !!(typeof window !== 'undefined' && navigator && window.document),
+ isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
+ //PS3 indicates loaded and complete, but need to wait for complete
+ //specifically. Sequence is 'loading', 'loaded', execution,
+ // then 'complete'. The UA check is unfortunate, but not sure how
+ //to feature test w/o causing perf issues.
+ readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
+ /^complete$/ : /^(complete|loaded)$/,
+ defContextName = '_',
+ //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
+ isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
+ contexts = {},
+ cfg = {},
+ globalDefQueue = [],
+ useInteractive = false;
+
+ function isFunction(it) {
+ return ostring.call(it) === '[object Function]';
+ }
+
+ function isArray(it) {
+ return ostring.call(it) === '[object Array]';
+ }
+
+ /**
+ * Helper function for iterating over an array. If the func returns
+ * a true value, it will break out of the loop.
+ */
+ function each(ary, func) {
+ if (ary) {
+ var i;
+ for (i = 0; i < ary.length; i += 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Helper function for iterating over an array backwards. If the func
+ * returns a true value, it will break out of the loop.
+ */
+ function eachReverse(ary, func) {
+ if (ary) {
+ var i;
+ for (i = ary.length - 1; i > -1; i -= 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop);
+ }
+
+ function getOwn(obj, prop) {
+ return hasProp(obj, prop) && obj[prop];
+ }
+
+ /**
+ * Cycles over properties in an object and calls a function for each
+ * property value. If the function returns a truthy value, then the
+ * iteration is stopped.
+ */
+ function eachProp(obj, func) {
+ var prop;
+ for (prop in obj) {
+ if (hasProp(obj, prop)) {
+ if (func(obj[prop], prop)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Simple function to mix in properties from source into target,
+ * but only if target does not already have a property of the same name.
+ */
+ function mixin(target, source, force, deepStringMixin) {
+ if (source) {
+ eachProp(source, function (value, prop) {
+ if (force || !hasProp(target, prop)) {
+ if (deepStringMixin && typeof value !== 'string') {
+ if (!target[prop]) {
+ target[prop] = {};
+ }
+ mixin(target[prop], value, force, deepStringMixin);
+ } else {
+ target[prop] = value;
+ }
+ }
+ });
+ }
+ return target;
+ }
+
+ //Similar to Function.prototype.bind, but the 'this' object is specified
+ //first, since it is easier to read/figure out what 'this' will be.
+ function bind(obj, fn) {
+ return function () {
+ return fn.apply(obj, arguments);
+ };
+ }
+
+ function scripts() {
+ return document.getElementsByTagName('script');
+ }
+
+ function defaultOnError(err) {
+ throw err;
+ }
+
+ //Allow getting a global that expressed in
+ //dot notation, like 'a.b.c'.
+ function getGlobal(value) {
+ if (!value) {
+ return value;
+ }
+ var g = global;
+ each(value.split('.'), function (part) {
+ g = g[part];
+ });
+ return g;
+ }
+
+ /**
+ * Constructs an error with a pointer to an URL with more information.
+ * @param {String} id the error ID that maps to an ID on a web page.
+ * @param {String} message human readable error.
+ * @param {Error} [err] the original error, if there is one.
+ *
+ * @returns {Error}
+ */
+ function makeError(id, msg, err, requireModules) {
+ var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
+ e.requireType = id;
+ e.requireModules = requireModules;
+ if (err) {
+ e.originalError = err;
+ }
+ return e;
+ }
+
+ if (typeof define !== 'undefined') {
+ //If a define is already in play via another AMD loader,
+ //do not overwrite.
+ return;
+ }
+
+ if (typeof requirejs !== 'undefined') {
+ if (isFunction(requirejs)) {
+ //Do not overwrite and existing requirejs instance.
+ return;
+ }
+ cfg = requirejs;
+ requirejs = undefined;
+ }
+
+ //Allow for a require config object
+ if (typeof require !== 'undefined' && !isFunction(require)) {
+ //assume it is a config object.
+ cfg = require;
+ require = undefined;
+ }
+
+ function newContext(contextName) {
+ var inCheckLoaded, Module, context, handlers,
+ checkLoadedTimeoutId,
+ config = {
+ //Defaults. Do not set a default for map
+ //config to speed up normalize(), which
+ //will run faster if there is no default.
+ waitSeconds: 7,
+ baseUrl: './',
+ paths: {},
+ pkgs: {},
+ shim: {},
+ config: {}
+ },
+ registry = {},
+ //registry of just enabled modules, to speed
+ //cycle breaking code when lots of modules
+ //are registered, but not activated.
+ enabledRegistry = {},
+ undefEvents = {},
+ defQueue = [],
+ defined = {},
+ urlFetched = {},
+ requireCounter = 1,
+ unnormalizedCounter = 1;
+
+ /**
+ * Trims the . and .. from an array of path segments.
+ * It will keep a leading path segment if a .. will become
+ * the first path segment, to help with module name lookups,
+ * which act like paths, but can be remapped. But the end result,
+ * all paths that use this function should look normalized.
+ * NOTE: this method MODIFIES the input array.
+ * @param {Array} ary the array of path segments.
+ */
+ function trimDots(ary) {
+ var i, part;
+ for (i = 0; ary[i]; i += 1) {
+ part = ary[i];
+ if (part === '.') {
+ ary.splice(i, 1);
+ i -= 1;
+ } else if (part === '..') {
+ if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
+ //End of the line. Keep at least one non-dot
+ //path segment at the front so it can be mapped
+ //correctly to disk. Otherwise, there is likely
+ //no path mapping for a path starting with '..'.
+ //This can still fail, but catches the most reasonable
+ //uses of ..
+ break;
+ } else if (i > 0) {
+ ary.splice(i - 1, 2);
+ i -= 2;
+ }
+ }
+ }
+ }
+
+ /**
+ * Given a relative module name, like ./something, normalize it to
+ * a real name that can be mapped to a path.
+ * @param {String} name the relative name
+ * @param {String} baseName a real name that the name arg is relative
+ * to.
+ * @param {Boolean} applyMap apply the map config to the value. Should
+ * only be done if this normalization is for a dependency ID.
+ * @returns {String} normalized name
+ */
+ function normalize(name, baseName, applyMap) {
+ var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
+ foundMap, foundI, foundStarMap, starI,
+ baseParts = baseName && baseName.split('/'),
+ normalizedBaseParts = baseParts,
+ map = config.map,
+ starMap = map && map['*'];
+
+ //Adjust any relative paths.
+ if (name && name.charAt(0) === '.') {
+ //If have a base name, try to normalize against it,
+ //otherwise, assume it is a top-level require that will
+ //be relative to baseUrl in the end.
+ if (baseName) {
+ if (getOwn(config.pkgs, baseName)) {
+ //If the baseName is a package name, then just treat it as one
+ //name to concat the name with.
+ normalizedBaseParts = baseParts = [baseName];
+ } else {
+ //Convert baseName to array, and lop off the last part,
+ //so that . matches that 'directory' and not name of the baseName's
+ //module. For instance, baseName of 'one/two/three', maps to
+ //'one/two/three.js', but we want the directory, 'one/two' for
+ //this normalization.
+ normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
+ }
+
+ name = normalizedBaseParts.concat(name.split('/'));
+ trimDots(name);
+
+ //Some use of packages may use a . path to reference the
+ //'main' module name, so normalize for that.
+ pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));
+ name = name.join('/');
+ if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
+ name = pkgName;
+ }
+ } else if (name.indexOf('./') === 0) {
+ // No baseName, so this is ID is resolved relative
+ // to baseUrl, pull off the leading dot.
+ name = name.substring(2);
+ }
+ }
+
+ //Apply map config if available.
+ if (applyMap && map && (baseParts || starMap)) {
+ nameParts = name.split('/');
+
+ for (i = nameParts.length; i > 0; i -= 1) {
+ nameSegment = nameParts.slice(0, i).join('/');
+
+ if (baseParts) {
+ //Find the longest baseName segment match in the config.
+ //So, do joins on the biggest to smallest lengths of baseParts.
+ for (j = baseParts.length; j > 0; j -= 1) {
+ mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
+
+ //baseName segment has config, find if it has one for
+ //this name.
+ if (mapValue) {
+ mapValue = getOwn(mapValue, nameSegment);
+ if (mapValue) {
+ //Match, update name to the new value.
+ foundMap = mapValue;
+ foundI = i;
+ break;
+ }
+ }
+ }
+ }
+
+ if (foundMap) {
+ break;
+ }
+
+ //Check for a star map match, but just hold on to it,
+ //if there is a shorter segment match later in a matching
+ //config, then favor over this star map.
+ if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
+ foundStarMap = getOwn(starMap, nameSegment);
+ starI = i;
+ }
+ }
+
+ if (!foundMap && foundStarMap) {
+ foundMap = foundStarMap;
+ foundI = starI;
+ }
+
+ if (foundMap) {
+ nameParts.splice(0, foundI, foundMap);
+ name = nameParts.join('/');
+ }
+ }
+
+ return name;
+ }
+
+ function removeScript(name) {
+ if (isBrowser) {
+ each(scripts(), function (scriptNode) {
+ if (scriptNode.getAttribute('data-requiremodule') === name &&
+ scriptNode.getAttribute('data-requirecontext') === context.contextName) {
+ scriptNode.parentNode.removeChild(scriptNode);
+ return true;
+ }
+ });
+ }
+ }
+
+ function hasPathFallback(id) {
+ var pathConfig = getOwn(config.paths, id);
+ if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
+ removeScript(id);
+ //Pop off the first array value, since it failed, and
+ //retry
+ pathConfig.shift();
+ context.require.undef(id);
+ context.require([id]);
+ return true;
+ }
+ }
+
+ //Turns a plugin!resource to [plugin, resource]
+ //with the plugin being undefined if the name
+ //did not have a plugin prefix.
+ function splitPrefix(name) {
+ var prefix,
+ index = name ? name.indexOf('!') : -1;
+ if (index > -1) {
+ prefix = name.substring(0, index);
+ name = name.substring(index + 1, name.length);
+ }
+ return [prefix, name];
+ }
+
+ /**
+ * Creates a module mapping that includes plugin prefix, module
+ * name, and path. If parentModuleMap is provided it will
+ * also normalize the name via require.normalize()
+ *
+ * @param {String} name the module name
+ * @param {String} [parentModuleMap] parent module map
+ * for the module name, used to resolve relative names.
+ * @param {Boolean} isNormalized: is the ID already normalized.
+ * This is true if this call is done for a define() module ID.
+ * @param {Boolean} applyMap: apply the map config to the ID.
+ * Should only be true if this map is for a dependency.
+ *
+ * @returns {Object}
+ */
+ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
+ var url, pluginModule, suffix, nameParts,
+ prefix = null,
+ parentName = parentModuleMap ? parentModuleMap.name : null,
+ originalName = name,
+ isDefine = true,
+ normalizedName = '';
+
+ //If no name, then it means it is a require call, generate an
+ //internal name.
+ if (!name) {
+ isDefine = false;
+ name = '_@r' + (requireCounter += 1);
+ }
+
+ nameParts = splitPrefix(name);
+ prefix = nameParts[0];
+ name = nameParts[1];
+
+ if (prefix) {
+ prefix = normalize(prefix, parentName, applyMap);
+ pluginModule = getOwn(defined, prefix);
+ }
+
+ //Account for relative paths if there is a base name.
+ if (name) {
+ if (prefix) {
+ if (pluginModule && pluginModule.normalize) {
+ //Plugin is loaded, use its normalize method.
+ normalizedName = pluginModule.normalize(name, function (name) {
+ return normalize(name, parentName, applyMap);
+ });
+ } else {
+ normalizedName = normalize(name, parentName, applyMap);
+ }
+ } else {
+ //A regular module.
+ normalizedName = normalize(name, parentName, applyMap);
+
+ //Normalized name may be a plugin ID due to map config
+ //application in normalize. The map config values must
+ //already be normalized, so do not need to redo that part.
+ nameParts = splitPrefix(normalizedName);
+ prefix = nameParts[0];
+ normalizedName = nameParts[1];
+ isNormalized = true;
+
+ url = context.nameToUrl(normalizedName);
+ }
+ }
+
+ //If the id is a plugin id that cannot be determined if it needs
+ //normalization, stamp it with a unique ID so two matching relative
+ //ids that may conflict can be separate.
+ suffix = prefix && !pluginModule && !isNormalized ?
+ '_unnormalized' + (unnormalizedCounter += 1) :
+ '';
+
+ return {
+ prefix: prefix,
+ name: normalizedName,
+ parentMap: parentModuleMap,
+ unnormalized: !!suffix,
+ url: url,
+ originalName: originalName,
+ isDefine: isDefine,
+ id: (prefix ?
+ prefix + '!' + normalizedName :
+ normalizedName) + suffix
+ };
+ }
+
+ function getModule(depMap) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (!mod) {
+ mod = registry[id] = new context.Module(depMap);
+ }
+
+ return mod;
+ }
+
+ function on(depMap, name, fn) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (hasProp(defined, id) &&
+ (!mod || mod.defineEmitComplete)) {
+ if (name === 'defined') {
+ fn(defined[id]);
+ }
+ } else {
+ mod = getModule(depMap);
+ if (mod.error && name === 'error') {
+ fn(mod.error);
+ } else {
+ mod.on(name, fn);
+ }
+ }
+ }
+
+ function onError(err, errback) {
+ var ids = err.requireModules,
+ notified = false;
+
+ if (errback) {
+ errback(err);
+ } else {
+ each(ids, function (id) {
+ var mod = getOwn(registry, id);
+ if (mod) {
+ //Set error on module, so it skips timeout checks.
+ mod.error = err;
+ if (mod.events.error) {
+ notified = true;
+ mod.emit('error', err);
+ }
+ }
+ });
+
+ if (!notified) {
+ req.onError(err);
+ }
+ }
+ }
+
+ /**
+ * Internal method to transfer globalQueue items to this context's
+ * defQueue.
+ */
+ function takeGlobalQueue() {
+ //Push all the globalDefQueue items into the context's defQueue
+ if (globalDefQueue.length) {
+ //Array splice in the values since the context code has a
+ //local var ref to defQueue, so cannot just reassign the one
+ //on context.
+ apsp.apply(defQueue,
+ [defQueue.length - 1, 0].concat(globalDefQueue));
+ globalDefQueue = [];
+ }
+ }
+
+ handlers = {
+ 'require': function (mod) {
+ if (mod.require) {
+ return mod.require;
+ } else {
+ return (mod.require = context.makeRequire(mod.map));
+ }
+ },
+ 'exports': function (mod) {
+ mod.usingExports = true;
+ if (mod.map.isDefine) {
+ if (mod.exports) {
+ return mod.exports;
+ } else {
+ return (mod.exports = defined[mod.map.id] = {});
+ }
+ }
+ },
+ 'module': function (mod) {
+ if (mod.module) {
+ return mod.module;
+ } else {
+ return (mod.module = {
+ id: mod.map.id,
+ uri: mod.map.url,
+ config: function () {
+ var c,
+ pkg = getOwn(config.pkgs, mod.map.id);
+ // For packages, only support config targeted
+ // at the main module.
+ c = pkg ? getOwn(config.config, mod.map.id + '/' + pkg.main) :
+ getOwn(config.config, mod.map.id);
+ return c || {};
+ },
+ exports: defined[mod.map.id]
+ });
+ }
+ }
+ };
+
+ function cleanRegistry(id) {
+ //Clean up machinery used for waiting modules.
+ delete registry[id];
+ delete enabledRegistry[id];
+ }
+
+ function breakCycle(mod, traced, processed) {
+ var id = mod.map.id;
+
+ if (mod.error) {
+ mod.emit('error', mod.error);
+ } else {
+ traced[id] = true;
+ each(mod.depMaps, function (depMap, i) {
+ var depId = depMap.id,
+ dep = getOwn(registry, depId);
+
+ //Only force things that have not completed
+ //being defined, so still in the registry,
+ //and only if it has not been matched up
+ //in the module already.
+ if (dep && !mod.depMatched[i] && !processed[depId]) {
+ if (getOwn(traced, depId)) {
+ mod.defineDep(i, defined[depId]);
+ mod.check(); //pass false?
+ } else {
+ breakCycle(dep, traced, processed);
+ }
+ }
+ });
+ processed[id] = true;
+ }
+ }
+
+ function checkLoaded() {
+ var map, modId, err, usingPathFallback,
+ waitInterval = config.waitSeconds * 1000,
+ //It is possible to disable the wait interval by using waitSeconds of 0.
+ expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
+ noLoads = [],
+ reqCalls = [],
+ stillLoading = false,
+ needCycleCheck = true;
+
+ //Do not bother if this call was a result of a cycle break.
+ if (inCheckLoaded) {
+ return;
+ }
+
+ inCheckLoaded = true;
+
+ //Figure out the state of all the modules.
+ eachProp(enabledRegistry, function (mod) {
+ map = mod.map;
+ modId = map.id;
+
+ //Skip things that are not enabled or in error state.
+ if (!mod.enabled) {
+ return;
+ }
+
+ if (!map.isDefine) {
+ reqCalls.push(mod);
+ }
+
+ if (!mod.error) {
+ //If the module should be executed, and it has not
+ //been inited and time is up, remember it.
+ if (!mod.inited && expired) {
+ if (hasPathFallback(modId)) {
+ usingPathFallback = true;
+ stillLoading = true;
+ } else {
+ noLoads.push(modId);
+ removeScript(modId);
+ }
+ } else if (!mod.inited && mod.fetched && map.isDefine) {
+ stillLoading = true;
+ if (!map.prefix) {
+ //No reason to keep looking for unfinished
+ //loading. If the only stillLoading is a
+ //plugin resource though, keep going,
+ //because it may be that a plugin resource
+ //is waiting on a non-plugin cycle.
+ return (needCycleCheck = false);
+ }
+ }
+ }
+ });
+
+ if (expired && noLoads.length) {
+ //If wait time expired, throw error of unloaded modules.
+ err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
+ err.contextName = context.contextName;
+ return onError(err);
+ }
+
+ //Not expired, check for a cycle.
+ if (needCycleCheck) {
+ each(reqCalls, function (mod) {
+ breakCycle(mod, {}, {});
+ });
+ }
+
+ //If still waiting on loads, and the waiting load is something
+ //other than a plugin resource, or there are still outstanding
+ //scripts, then just try back later.
+ if ((!expired || usingPathFallback) && stillLoading) {
+ //Something is still waiting to load. Wait for it, but only
+ //if a timeout is not already in effect.
+ if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
+ checkLoadedTimeoutId = setTimeout(function () {
+ checkLoadedTimeoutId = 0;
+ checkLoaded();
+ }, 50);
+ }
+ }
+
+ inCheckLoaded = false;
+ }
+
+ Module = function (map) {
+ this.events = getOwn(undefEvents, map.id) || {};
+ this.map = map;
+ this.shim = getOwn(config.shim, map.id);
+ this.depExports = [];
+ this.depMaps = [];
+ this.depMatched = [];
+ this.pluginMaps = {};
+ this.depCount = 0;
+
+ /* this.exports this.factory
+ this.depMaps = [],
+ this.enabled, this.fetched
+ */
+ };
+
+ Module.prototype = {
+ init: function (depMaps, factory, errback, options) {
+ options = options || {};
+
+ //Do not do more inits if already done. Can happen if there
+ //are multiple define calls for the same module. That is not
+ //a normal, common case, but it is also not unexpected.
+ if (this.inited) {
+ return;
+ }
+
+ this.factory = factory;
+
+ if (errback) {
+ //Register for errors on this module.
+ this.on('error', errback);
+ } else if (this.events.error) {
+ //If no errback already, but there are error listeners
+ //on this module, set up an errback to pass to the deps.
+ errback = bind(this, function (err) {
+ this.emit('error', err);
+ });
+ }
+
+ //Do a copy of the dependency array, so that
+ //source inputs are not modified. For example
+ //"shim" deps are passed in here directly, and
+ //doing a direct modification of the depMaps array
+ //would affect that config.
+ this.depMaps = depMaps && depMaps.slice(0);
+
+ this.errback = errback;
+
+ //Indicate this module has be initialized
+ this.inited = true;
+
+ this.ignore = options.ignore;
+
+ //Could have option to init this module in enabled mode,
+ //or could have been previously marked as enabled. However,
+ //the dependencies are not known until init is called. So
+ //if enabled previously, now trigger dependencies as enabled.
+ if (options.enabled || this.enabled) {
+ //Enable this module and dependencies.
+ //Will call this.check()
+ this.enable();
+ } else {
+ this.check();
+ }
+ },
+
+ defineDep: function (i, depExports) {
+ //Because of cycles, defined callback for a given
+ //export can be called more than once.
+ if (!this.depMatched[i]) {
+ this.depMatched[i] = true;
+ this.depCount -= 1;
+ this.depExports[i] = depExports;
+ }
+ },
+
+ fetch: function () {
+ if (this.fetched) {
+ return;
+ }
+ this.fetched = true;
+
+ context.startTime = (new Date()).getTime();
+
+ var map = this.map;
+
+ //If the manager is for a plugin managed resource,
+ //ask the plugin to load it now.
+ if (this.shim) {
+ context.makeRequire(this.map, {
+ enableBuildCallback: true
+ })(this.shim.deps || [], bind(this, function () {
+ return map.prefix ? this.callPlugin() : this.load();
+ }));
+ } else {
+ //Regular dependency.
+ return map.prefix ? this.callPlugin() : this.load();
+ }
+ },
+
+ load: function () {
+ var url = this.map.url;
+
+ //Regular dependency.
+ if (!urlFetched[url]) {
+ urlFetched[url] = true;
+ context.load(this.map.id, url);
+ }
+ },
+
+ /**
+ * Checks if the module is ready to define itself, and if so,
+ * define it.
+ */
+ check: function () {
+ if (!this.enabled || this.enabling) {
+ return;
+ }
+
+ var err, cjsModule,
+ id = this.map.id,
+ depExports = this.depExports,
+ exports = this.exports,
+ factory = this.factory;
+
+ if (!this.inited) {
+ this.fetch();
+ } else if (this.error) {
+ this.emit('error', this.error);
+ } else if (!this.defining) {
+ //The factory could trigger another require call
+ //that would result in checking this module to
+ //define itself again. If already in the process
+ //of doing that, skip this work.
+ this.defining = true;
+
+ if (this.depCount < 1 && !this.defined) {
+ if (isFunction(factory)) {
+ //If there is an error listener, favor passing
+ //to that instead of throwing an error. However,
+ //only do it for define()'d modules. require
+ //errbacks should not be called for failures in
+ //their callbacks (#699). However if a global
+ //onError is set, use that.
+ if ((this.events.error && this.map.isDefine) ||
+ req.onError !== defaultOnError) {
+ try {
+ exports = context.execCb(id, factory, depExports, exports);
+ } catch (e) {
+ err = e;
+ }
+ } else {
+ exports = context.execCb(id, factory, depExports, exports);
+ }
+
+ if (this.map.isDefine) {
+ //If setting exports via 'module' is in play,
+ //favor that over return value and exports. After that,
+ //favor a non-undefined return value over exports use.
+ cjsModule = this.module;
+ if (cjsModule &&
+ cjsModule.exports !== undefined &&
+ //Make sure it is not already the exports value
+ cjsModule.exports !== this.exports) {
+ exports = cjsModule.exports;
+ } else if (exports === undefined && this.usingExports) {
+ //exports already set the defined value.
+ exports = this.exports;
+ }
+ }
+
+ if (err) {
+ err.requireMap = this.map;
+ err.requireModules = this.map.isDefine ? [this.map.id] : null;
+ err.requireType = this.map.isDefine ? 'define' : 'require';
+ return onError((this.error = err));
+ }
+
+ } else {
+ //Just a literal value
+ exports = factory;
+ }
+
+ this.exports = exports;
+
+ if (this.map.isDefine && !this.ignore) {
+ defined[id] = exports;
+
+ if (req.onResourceLoad) {
+ req.onResourceLoad(context, this.map, this.depMaps);
+ }
+ }
+
+ //Clean up
+ cleanRegistry(id);
+
+ this.defined = true;
+ }
+
+ //Finished the define stage. Allow calling check again
+ //to allow define notifications below in the case of a
+ //cycle.
+ this.defining = false;
+
+ if (this.defined && !this.defineEmitted) {
+ this.defineEmitted = true;
+ this.emit('defined', this.exports);
+ this.defineEmitComplete = true;
+ }
+
+ }
+ },
+
+ callPlugin: function () {
+ var map = this.map,
+ id = map.id,
+ //Map already normalized the prefix.
+ pluginMap = makeModuleMap(map.prefix);
+
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(pluginMap);
+
+ on(pluginMap, 'defined', bind(this, function (plugin) {
+ var load, normalizedMap, normalizedMod,
+ name = this.map.name,
+ parentName = this.map.parentMap ? this.map.parentMap.name : null,
+ localRequire = context.makeRequire(map.parentMap, {
+ enableBuildCallback: true
+ });
+
+ //If current map is not normalized, wait for that
+ //normalized name to load instead of continuing.
+ if (this.map.unnormalized) {
+ //Normalize the ID if the plugin allows it.
+ if (plugin.normalize) {
+ name = plugin.normalize(name, function (name) {
+ return normalize(name, parentName, true);
+ }) || '';
+ }
+
+ //prefix and name should already be normalized, no need
+ //for applying map config again either.
+ normalizedMap = makeModuleMap(map.prefix + '!' + name,
+ this.map.parentMap);
+ on(normalizedMap,
+ 'defined', bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true,
+ ignore: true
+ });
+ }));
+
+ normalizedMod = getOwn(registry, normalizedMap.id);
+ if (normalizedMod) {
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(normalizedMap);
+
+ if (this.events.error) {
+ normalizedMod.on('error', bind(this, function (err) {
+ this.emit('error', err);
+ }));
+ }
+ normalizedMod.enable();
+ }
+
+ return;
+ }
+
+ load = bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true
+ });
+ });
+
+ load.error = bind(this, function (err) {
+ this.inited = true;
+ this.error = err;
+ err.requireModules = [id];
+
+ //Remove temp unnormalized modules for this module,
+ //since they will never be resolved otherwise now.
+ eachProp(registry, function (mod) {
+ if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
+ cleanRegistry(mod.map.id);
+ }
+ });
+
+ onError(err);
+ });
+
+ //Allow plugins to load other code without having to know the
+ //context or how to 'complete' the load.
+ load.fromText = bind(this, function (text, textAlt) {
+ /*jslint evil: true */
+ var moduleName = map.name,
+ moduleMap = makeModuleMap(moduleName),
+ hasInteractive = useInteractive;
+
+ //As of 2.1.0, support just passing the text, to reinforce
+ //fromText only being called once per resource. Still
+ //support old style of passing moduleName but discard
+ //that moduleName in favor of the internal ref.
+ if (textAlt) {
+ text = textAlt;
+ }
+
+ //Turn off interactive script matching for IE for any define
+ //calls in the text, then turn it back on at the end.
+ if (hasInteractive) {
+ useInteractive = false;
+ }
+
+ //Prime the system by creating a module instance for
+ //it.
+ getModule(moduleMap);
+
+ //Transfer any config to this other module.
+ if (hasProp(config.config, id)) {
+ config.config[moduleName] = config.config[id];
+ }
+
+ try {
+ req.exec(text);
+ } catch (e) {
+ return onError(makeError('fromtexteval',
+ 'fromText eval for ' + id +
+ ' failed: ' + e,
+ e,
+ [id]));
+ }
+
+ if (hasInteractive) {
+ useInteractive = true;
+ }
+
+ //Mark this as a dependency for the plugin
+ //resource
+ this.depMaps.push(moduleMap);
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+
+ //Bind the value of that module to the value for this
+ //resource ID.
+ localRequire([moduleName], load);
+ });
+
+ //Use parentName here since the plugin's name is not reliable,
+ //could be some weird string with no path that actually wants to
+ //reference the parentName's path.
+ plugin.load(map.name, localRequire, load, config);
+ }));
+
+ context.enable(pluginMap, this);
+ this.pluginMaps[pluginMap.id] = pluginMap;
+ },
+
+ enable: function () {
+ enabledRegistry[this.map.id] = this;
+ this.enabled = true;
+
+ //Set flag mentioning that the module is enabling,
+ //so that immediate calls to the defined callbacks
+ //for dependencies do not trigger inadvertent load
+ //with the depCount still being zero.
+ this.enabling = true;
+
+ //Enable each dependency
+ each(this.depMaps, bind(this, function (depMap, i) {
+ var id, mod, handler;
+
+ if (typeof depMap === 'string') {
+ //Dependency needs to be converted to a depMap
+ //and wired up to this module.
+ depMap = makeModuleMap(depMap,
+ (this.map.isDefine ? this.map : this.map.parentMap),
+ false,
+ !this.skipMap);
+ this.depMaps[i] = depMap;
+
+ handler = getOwn(handlers, depMap.id);
+
+ if (handler) {
+ this.depExports[i] = handler(this);
+ return;
+ }
+
+ this.depCount += 1;
+
+ on(depMap, 'defined', bind(this, function (depExports) {
+ this.defineDep(i, depExports);
+ this.check();
+ }));
+
+ if (this.errback) {
+ on(depMap, 'error', bind(this, this.errback));
+ }
+ }
+
+ id = depMap.id;
+ mod = registry[id];
+
+ //Skip special modules like 'require', 'exports', 'module'
+ //Also, don't call enable if it is already enabled,
+ //important in circular dependency cases.
+ if (!hasProp(handlers, id) && mod && !mod.enabled) {
+ context.enable(depMap, this);
+ }
+ }));
+
+ //Enable each plugin that is used in
+ //a dependency
+ eachProp(this.pluginMaps, bind(this, function (pluginMap) {
+ var mod = getOwn(registry, pluginMap.id);
+ if (mod && !mod.enabled) {
+ context.enable(pluginMap, this);
+ }
+ }));
+
+ this.enabling = false;
+
+ this.check();
+ },
+
+ on: function (name, cb) {
+ var cbs = this.events[name];
+ if (!cbs) {
+ cbs = this.events[name] = [];
+ }
+ cbs.push(cb);
+ },
+
+ emit: function (name, evt) {
+ each(this.events[name], function (cb) {
+ cb(evt);
+ });
+ if (name === 'error') {
+ //Now that the error handler was triggered, remove
+ //the listeners, since this broken Module instance
+ //can stay around for a while in the registry.
+ delete this.events[name];
+ }
+ }
+ };
+
+ function callGetModule(args) {
+ //Skip modules already defined.
+ if (!hasProp(defined, args[0])) {
+ getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
+ }
+ }
+
+ function removeListener(node, func, name, ieName) {
+ //Favor detachEvent because of IE9
+ //issue, see attachEvent/addEventListener comment elsewhere
+ //in this file.
+ if (node.detachEvent && !isOpera) {
+ //Probably IE. If not it will throw an error, which will be
+ //useful to know.
+ if (ieName) {
+ node.detachEvent(ieName, func);
+ }
+ } else {
+ node.removeEventListener(name, func, false);
+ }
+ }
+
+ /**
+ * Given an event from a script node, get the requirejs info from it,
+ * and then removes the event listeners on the node.
+ * @param {Event} evt
+ * @returns {Object}
+ */
+ function getScriptData(evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ var node = evt.currentTarget || evt.srcElement;
+
+ //Remove the listeners once here.
+ removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
+ removeListener(node, context.onScriptError, 'error');
+
+ return {
+ node: node,
+ id: node && node.getAttribute('data-requiremodule')
+ };
+ }
+
+ function intakeDefines() {
+ var args;
+
+ //Any defined modules in the global queue, intake them now.
+ takeGlobalQueue();
+
+ //Make sure any remaining defQueue items get properly processed.
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
+ } else {
+ //args are id, deps, factory. Should be normalized by the
+ //define() function.
+ callGetModule(args);
+ }
+ }
+ }
+
+ context = {
+ config: config,
+ contextName: contextName,
+ registry: registry,
+ defined: defined,
+ urlFetched: urlFetched,
+ defQueue: defQueue,
+ Module: Module,
+ makeModuleMap: makeModuleMap,
+ nextTick: req.nextTick,
+ onError: onError,
+
+ /**
+ * Set a configuration for the context.
+ * @param {Object} cfg config object to integrate.
+ */
+ configure: function (cfg) {
+ //Make sure the baseUrl ends in a slash.
+ if (cfg.baseUrl) {
+ if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
+ cfg.baseUrl += '/';
+ }
+ }
+
+ //Save off the paths and packages since they require special processing,
+ //they are additive.
+ var pkgs = config.pkgs,
+ shim = config.shim,
+ objs = {
+ paths: true,
+ config: true,
+ map: true
+ };
+
+ eachProp(cfg, function (value, prop) {
+ if (objs[prop]) {
+ if (prop === 'map') {
+ if (!config.map) {
+ config.map = {};
+ }
+ mixin(config[prop], value, true, true);
+ } else {
+ mixin(config[prop], value, true);
+ }
+ } else {
+ config[prop] = value;
+ }
+ });
+
+ //Merge shim
+ if (cfg.shim) {
+ eachProp(cfg.shim, function (value, id) {
+ //Normalize the structure
+ if (isArray(value)) {
+ value = {
+ deps: value
+ };
+ }
+ if ((value.exports || value.init) && !value.exportsFn) {
+ value.exportsFn = context.makeShimExports(value);
+ }
+ shim[id] = value;
+ });
+ config.shim = shim;
+ }
+
+ //Adjust packages if necessary.
+ if (cfg.packages) {
+ each(cfg.packages, function (pkgObj) {
+ var location;
+
+ pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
+ location = pkgObj.location;
+
+ //Create a brand new object on pkgs, since currentPackages can
+ //be passed in again, and config.pkgs is the internal transformed
+ //state for all package configs.
+ pkgs[pkgObj.name] = {
+ name: pkgObj.name,
+ location: location || pkgObj.name,
+ //Remove leading dot in main, so main paths are normalized,
+ //and remove any trailing .js, since different package
+ //envs have different conventions: some use a module name,
+ //some use a file name.
+ main: (pkgObj.main || 'main')
+ .replace(currDirRegExp, '')
+ .replace(jsSuffixRegExp, '')
+ };
+ });
+
+ //Done with modifications, assing packages back to context config
+ config.pkgs = pkgs;
+ }
+
+ //If there are any "waiting to execute" modules in the registry,
+ //update the maps for them, since their info, like URLs to load,
+ //may have changed.
+ eachProp(registry, function (mod, id) {
+ //If module already has init called, since it is too
+ //late to modify them, and ignore unnormalized ones
+ //since they are transient.
+ if (!mod.inited && !mod.map.unnormalized) {
+ mod.map = makeModuleMap(id);
+ }
+ });
+
+ //If a deps array or a config callback is specified, then call
+ //require with those args. This is useful when require is defined as a
+ //config object before require.js is loaded.
+ if (cfg.deps || cfg.callback) {
+ context.require(cfg.deps || [], cfg.callback);
+ }
+ },
+
+ makeShimExports: function (value) {
+ function fn() {
+ var ret;
+ if (value.init) {
+ ret = value.init.apply(global, arguments);
+ }
+ return ret || (value.exports && getGlobal(value.exports));
+ }
+ return fn;
+ },
+
+ makeRequire: function (relMap, options) {
+ options = options || {};
+
+ function localRequire(deps, callback, errback) {
+ var id, map, requireMod;
+
+ if (options.enableBuildCallback && callback && isFunction(callback)) {
+ callback.__requireJsBuild = true;
+ }
+
+ if (typeof deps === 'string') {
+ if (isFunction(callback)) {
+ //Invalid call
+ return onError(makeError('requireargs', 'Invalid require call'), errback);
+ }
+
+ //If require|exports|module are requested, get the
+ //value for them from the special handlers. Caveat:
+ //this only works while module is being defined.
+ if (relMap && hasProp(handlers, deps)) {
+ return handlers[deps](registry[relMap.id]);
+ }
+
+ //Synchronous access to one module. If require.get is
+ //available (as in the Node adapter), prefer that.
+ if (req.get) {
+ return req.get(context, deps, relMap, localRequire);
+ }
+
+ //Normalize module name, if it contains . or ..
+ map = makeModuleMap(deps, relMap, false, true);
+ id = map.id;
+
+ if (!hasProp(defined, id)) {
+ return onError(makeError('notloaded', 'Module name "' +
+ id +
+ '" has not been loaded yet for context: ' +
+ contextName +
+ (relMap ? '' : '. Use require([])')));
+ }
+ return defined[id];
+ }
+
+ //Grab defines waiting in the global queue.
+ intakeDefines();
+
+ //Mark all the dependencies as needing to be loaded.
+ context.nextTick(function () {
+ //Some defines could have been added since the
+ //require call, collect them.
+ intakeDefines();
+
+ requireMod = getModule(makeModuleMap(null, relMap));
+
+ //Store if map config should be applied to this require
+ //call for dependencies.
+ requireMod.skipMap = options.skipMap;
+
+ requireMod.init(deps, callback, errback, {
+ enabled: true
+ });
+
+ checkLoaded();
+ });
+
+ return localRequire;
+ }
+
+ mixin(localRequire, {
+ isBrowser: isBrowser,
+
+ /**
+ * Converts a module name + .extension into an URL path.
+ * *Requires* the use of a module name. It does not support using
+ * plain URLs like nameToUrl.
+ */
+ toUrl: function (moduleNamePlusExt) {
+ var ext,
+ index = moduleNamePlusExt.lastIndexOf('.'),
+ segment = moduleNamePlusExt.split('/')[0],
+ isRelative = segment === '.' || segment === '..';
+
+ //Have a file extension alias, and it is not the
+ //dots from a relative path.
+ if (index !== -1 && (!isRelative || index > 1)) {
+ ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
+ moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
+ }
+
+ return context.nameToUrl(normalize(moduleNamePlusExt,
+ relMap && relMap.id, true), ext, true);
+ },
+
+ defined: function (id) {
+ return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
+ },
+
+ specified: function (id) {
+ id = makeModuleMap(id, relMap, false, true).id;
+ return hasProp(defined, id) || hasProp(registry, id);
+ }
+ });
+
+ //Only allow undef on top level require calls
+ if (!relMap) {
+ localRequire.undef = function (id) {
+ //Bind any waiting define() calls to this context,
+ //fix for #408
+ takeGlobalQueue();
+
+ var map = makeModuleMap(id, relMap, true),
+ mod = getOwn(registry, id);
+
+ delete defined[id];
+ delete urlFetched[map.url];
+ delete undefEvents[id];
+
+ if (mod) {
+ //Hold on to listeners in case the
+ //module will be attempted to be reloaded
+ //using a different config.
+ if (mod.events.defined) {
+ undefEvents[id] = mod.events;
+ }
+
+ cleanRegistry(id);
+ }
+ };
+ }
+
+ return localRequire;
+ },
+
+ /**
+ * Called to enable a module if it is still in the registry
+ * awaiting enablement. A second arg, parent, the parent module,
+ * is passed in for context, when this method is overriden by
+ * the optimizer. Not shown here to keep code compact.
+ */
+ enable: function (depMap) {
+ var mod = getOwn(registry, depMap.id);
+ if (mod) {
+ getModule(depMap).enable();
+ }
+ },
+
+ /**
+ * Internal method used by environment adapters to complete a load event.
+ * A load event could be a script load or just a load pass from a synchronous
+ * load call.
+ * @param {String} moduleName the name of the module to potentially complete.
+ */
+ completeLoad: function (moduleName) {
+ var found, args, mod,
+ shim = getOwn(config.shim, moduleName) || {},
+ shExports = shim.exports;
+
+ takeGlobalQueue();
+
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ args[0] = moduleName;
+ //If already found an anonymous module and bound it
+ //to this name, then this is some other anon module
+ //waiting for its completeLoad to fire.
+ if (found) {
+ break;
+ }
+ found = true;
+ } else if (args[0] === moduleName) {
+ //Found matching define call for this script!
+ found = true;
+ }
+
+ callGetModule(args);
+ }
+
+ //Do this after the cycle of callGetModule in case the result
+ //of those calls/init calls changes the registry.
+ mod = getOwn(registry, moduleName);
+
+ if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
+ if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
+ if (hasPathFallback(moduleName)) {
+ return;
+ } else {
+ return onError(makeError('nodefine',
+ 'No define call for ' + moduleName,
+ null,
+ [moduleName]));
+ }
+ } else {
+ //A script that does not call define(), so just simulate
+ //the call for it.
+ callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
+ }
+ }
+
+ checkLoaded();
+ },
+
+ /**
+ * Converts a module name to a file path. Supports cases where
+ * moduleName may actually be just an URL.
+ * Note that it **does not** call normalize on the moduleName,
+ * it is assumed to have already been normalized. This is an
+ * internal API, not a public one. Use toUrl for the public API.
+ */
+ nameToUrl: function (moduleName, ext, skipExt) {
+ var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
+ parentPath;
+
+ //If a colon is in the URL, it indicates a protocol is used and it is just
+ //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
+ //or ends with .js, then assume the user meant to use an url and not a module id.
+ //The slash is important for protocol-less URLs as well as full paths.
+ if (req.jsExtRegExp.test(moduleName)) {
+ //Just a plain path, not module name lookup, so just return it.
+ //Add extension if it is included. This is a bit wonky, only non-.js things pass
+ //an extension, this method probably needs to be reworked.
+ url = moduleName + (ext || '');
+ } else {
+ //A module that needs to be converted to a path.
+ paths = config.paths;
+ pkgs = config.pkgs;
+
+ syms = moduleName.split('/');
+ //For each module name segment, see if there is a path
+ //registered for it. Start with most specific name
+ //and work up from it.
+ for (i = syms.length; i > 0; i -= 1) {
+ parentModule = syms.slice(0, i).join('/');
+ pkg = getOwn(pkgs, parentModule);
+ parentPath = getOwn(paths, parentModule);
+ if (parentPath) {
+ //If an array, it means there are a few choices,
+ //Choose the one that is desired
+ if (isArray(parentPath)) {
+ parentPath = parentPath[0];
+ }
+ syms.splice(0, i, parentPath);
+ break;
+ } else if (pkg) {
+ //If module name is just the package name, then looking
+ //for the main module.
+ if (moduleName === pkg.name) {
+ pkgPath = pkg.location + '/' + pkg.main;
+ } else {
+ pkgPath = pkg.location;
+ }
+ syms.splice(0, i, pkgPath);
+ break;
+ }
+ }
+
+ //Join the path parts together, then figure out if baseUrl is needed.
+ url = syms.join('/');
+ url += (ext || (/\?/.test(url) || skipExt ? '' : '.js'));
+ url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
+ }
+
+ return config.urlArgs ? url +
+ ((url.indexOf('?') === -1 ? '?' : '&') +
+ config.urlArgs) : url;
+ },
+
+ //Delegates to req.load. Broken out as a separate function to
+ //allow overriding in the optimizer.
+ load: function (id, url) {
+ req.load(context, id, url);
+ },
+
+ /**
+ * Executes a module callback function. Broken out as a separate function
+ * solely to allow the build system to sequence the files in the built
+ * layer in the right sequence.
+ *
+ * @private
+ */
+ execCb: function (name, callback, args, exports) {
+ return callback.apply(exports, args);
+ },
+
+ /**
+ * callback for script loads, used to check status of loading.
+ *
+ * @param {Event} evt the event from the browser for the script
+ * that was loaded.
+ */
+ onScriptLoad: function (evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ if (evt.type === 'load' ||
+ (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
+ //Reset interactive script so a script node is not held onto for
+ //to long.
+ interactiveScript = null;
+
+ //Pull out the name of the module and the context.
+ var data = getScriptData(evt);
+ context.completeLoad(data.id);
+ }
+ },
+
+ /**
+ * Callback for script errors.
+ */
+ onScriptError: function (evt) {
+ var data = getScriptData(evt);
+ if (!hasPathFallback(data.id)) {
+ return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
+ }
+ }
+ };
+
+ context.require = context.makeRequire();
+ return context;
+ }
+
+ /**
+ * Main entry point.
+ *
+ * If the only argument to require is a string, then the module that
+ * is represented by that string is fetched for the appropriate context.
+ *
+ * If the first argument is an array, then it will be treated as an array
+ * of dependency string names to fetch. An optional function callback can
+ * be specified to execute when all of those dependencies are available.
+ *
+ * Make a local req variable to help Caja compliance (it assumes things
+ * on a require that are not standardized), and to give a short
+ * name for minification/local scope use.
+ */
+ req = requirejs = function (deps, callback, errback, optional) {
+
+ //Find the right context, use default
+ var context, config,
+ contextName = defContextName;
+
+ // Determine if have config object in the call.
+ if (!isArray(deps) && typeof deps !== 'string') {
+ // deps is a config object
+ config = deps;
+ if (isArray(callback)) {
+ // Adjust args if there are dependencies
+ deps = callback;
+ callback = errback;
+ errback = optional;
+ } else {
+ deps = [];
+ }
+ }
+
+ if (config && config.context) {
+ contextName = config.context;
+ }
+
+ context = getOwn(contexts, contextName);
+ if (!context) {
+ context = contexts[contextName] = req.s.newContext(contextName);
+ }
+
+ if (config) {
+ context.configure(config);
+ }
+
+ return context.require(deps, callback, errback);
+ };
+
+ /**
+ * Support require.config() to make it easier to cooperate with other
+ * AMD loaders on globally agreed names.
+ */
+ req.config = function (config) {
+ return req(config);
+ };
+
+ /**
+ * Execute something after the current tick
+ * of the event loop. Override for other envs
+ * that have a better solution than setTimeout.
+ * @param {Function} fn function to execute later.
+ */
+ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
+ setTimeout(fn, 4);
+ } : function (fn) { fn(); };
+
+ /**
+ * Export require as a global, but only if it does not already exist.
+ */
+ if (!require) {
+ require = req;
+ }
+
+ req.version = version;
+
+ //Used to filter out dependencies that are already paths.
+ req.jsExtRegExp = /^\/|:|\?|\.js$/;
+ req.isBrowser = isBrowser;
+ s = req.s = {
+ contexts: contexts,
+ newContext: newContext
+ };
+
+ //Create default context.
+ req({});
+
+ //Exports some context-sensitive methods on global require.
+ each([
+ 'toUrl',
+ 'undef',
+ 'defined',
+ 'specified'
+ ], function (prop) {
+ //Reference from contexts instead of early binding to default context,
+ //so that during builds, the latest instance of the default context
+ //with its config gets used.
+ req[prop] = function () {
+ var ctx = contexts[defContextName];
+ return ctx.require[prop].apply(ctx, arguments);
+ };
+ });
+
+ if (isBrowser) {
+ head = s.head = document.getElementsByTagName('head')[0];
+ //If BASE tag is in play, using appendChild is a problem for IE6.
+ //When that browser dies, this can be removed. Details in this jQuery bug:
+ //http://dev.jquery.com/ticket/2709
+ baseElement = document.getElementsByTagName('base')[0];
+ if (baseElement) {
+ head = s.head = baseElement.parentNode;
+ }
+ }
+
+ /**
+ * Any errors that require explicitly generates will be passed to this
+ * function. Intercept/override it if you want custom error handling.
+ * @param {Error} err the error object.
+ */
+ req.onError = defaultOnError;
+
+ /**
+ * Does the request to load a module for the browser case.
+ * Make this a separate function to allow other environments
+ * to override it.
+ *
+ * @param {Object} context the require context to find state.
+ * @param {String} moduleName the name of the module.
+ * @param {Object} url the URL to the module.
+ */
+ req.load = function (context, moduleName, url) {
+ var config = (context && context.config) || {},
+ node;
+ if (isBrowser) {
+ //In the browser so use a script tag
+ node = config.xhtml ?
+ document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
+ document.createElement('script');
+ node.type = config.scriptType || 'text/javascript';
+ node.charset = 'utf-8';
+ node.async = true;
+
+ node.setAttribute('data-requirecontext', context.contextName);
+ node.setAttribute('data-requiremodule', moduleName);
+
+ //Set up load listener. Test attachEvent first because IE9 has
+ //a subtle issue in its addEventListener and script onload firings
+ //that do not match the behavior of all other browsers with
+ //addEventListener support, which fire the onload event for a
+ //script right after the script execution. See:
+ //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
+ //UNFORTUNATELY Opera implements attachEvent but does not follow the script
+ //script execution mode.
+ if (node.attachEvent &&
+ //Check if node.attachEvent is artificially added by custom script or
+ //natively supported by browser
+ //read https://github.com/jrburke/requirejs/issues/187
+ //if we can NOT find [native code] then it must NOT natively supported.
+ //in IE8, node.attachEvent does not have toString()
+ //Note the test for "[native code" with no closing brace, see:
+ //https://github.com/jrburke/requirejs/issues/273
+ !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
+ !isOpera) {
+ //Probably IE. IE (at least 6-8) do not fire
+ //script onload right after executing the script, so
+ //we cannot tie the anonymous define call to a name.
+ //However, IE reports the script as being in 'interactive'
+ //readyState at the time of the define call.
+ useInteractive = true;
+
+ node.attachEvent('onreadystatechange', context.onScriptLoad);
+ //It would be great to add an error handler here to catch
+ //404s in IE9+. However, onreadystatechange will fire before
+ //the error handler, so that does not help. If addEventListener
+ //is used, then IE will fire error before load, but we cannot
+ //use that pathway given the connect.microsoft.com issue
+ //mentioned above about not doing the 'script execute,
+ //then fire the script load event listener before execute
+ //next script' that other browsers do.
+ //Best hope: IE10 fixes the issues,
+ //and then destroys all installs of IE 6-9.
+ //node.attachEvent('onerror', context.onScriptError);
+ } else {
+ node.addEventListener('load', context.onScriptLoad, false);
+ node.addEventListener('error', context.onScriptError, false);
+ }
+ node.src = url;
+
+ //For some cache cases in IE 6-8, the script executes before the end
+ //of the appendChild execution, so to tie an anonymous define
+ //call to the module name (which is stored on the node), hold on
+ //to a reference to this node, but clear after the DOM insertion.
+ currentlyAddingScript = node;
+ if (baseElement) {
+ head.insertBefore(node, baseElement);
+ } else {
+ head.appendChild(node);
+ }
+ currentlyAddingScript = null;
+
+ return node;
+ } else if (isWebWorker) {
+ try {
+ //In a web worker, use importScripts. This is not a very
+ //efficient use of importScripts, importScripts will block until
+ //its script is downloaded and evaluated. However, if web workers
+ //are in play, the expectation that a build has been done so that
+ //only one script needs to be loaded anyway. This may need to be
+ //reevaluated if other use cases become common.
+ importScripts(url);
+
+ //Account for anonymous modules
+ context.completeLoad(moduleName);
+ } catch (e) {
+ context.onError(makeError('importscripts',
+ 'importScripts failed for ' +
+ moduleName + ' at ' + url,
+ e,
+ [moduleName]));
+ }
+ }
+ };
+
+ function getInteractiveScript() {
+ if (interactiveScript && interactiveScript.readyState === 'interactive') {
+ return interactiveScript;
+ }
+
+ eachReverse(scripts(), function (script) {
+ if (script.readyState === 'interactive') {
+ return (interactiveScript = script);
+ }
+ });
+ return interactiveScript;
+ }
+
+ //Look for a data-main script attribute, which could also adjust the baseUrl.
+ if (isBrowser) {
+ //Figure out baseUrl. Get it from the script tag with require.js in it.
+ eachReverse(scripts(), function (script) {
+ //Set the 'head' where we can append children by
+ //using the script's parent.
+ if (!head) {
+ head = script.parentNode;
+ }
+
+ //Look for a data-main attribute to set main script for the page
+ //to load. If it is there, the path to data main becomes the
+ //baseUrl, if it is not already set.
+ dataMain = script.getAttribute('data-main');
+ if (dataMain) {
+ //Preserve dataMain in case it is a path (i.e. contains '?')
+ mainScript = dataMain;
+
+ //Set final baseUrl if there is not already an explicit one.
+ if (!cfg.baseUrl) {
+ //Pull off the directory of data-main for use as the
+ //baseUrl.
+ src = mainScript.split('/');
+ mainScript = src.pop();
+ subPath = src.length ? src.join('/') + '/' : './';
+
+ cfg.baseUrl = subPath;
+ }
+
+ //Strip off any trailing .js since mainScript is now
+ //like a module name.
+ mainScript = mainScript.replace(jsSuffixRegExp, '');
+
+ //If mainScript is still a path, fall back to dataMain
+ if (req.jsExtRegExp.test(mainScript)) {
+ mainScript = dataMain;
+ }
+
+ //Put the data-main script in the files to load.
+ cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
+
+ return true;
+ }
+ });
+ }
+
+ /**
+ * The function that handles definitions of modules. Differs from
+ * require() in that a string for the module should be the first argument,
+ * and the function to execute after dependencies are loaded should
+ * return a value to define the module corresponding to the first argument's
+ * name.
+ */
+ define = function (name, deps, callback) {
+ var node, context;
+
+ //Allow for anonymous modules
+ if (typeof name !== 'string') {
+ //Adjust args appropriately
+ callback = deps;
+ deps = name;
+ name = null;
+ }
+
+ //This module may not have dependencies
+ if (!isArray(deps)) {
+ callback = deps;
+ deps = null;
+ }
+
+ //If no name, and callback is a function, then figure out if it a
+ //CommonJS thing with dependencies.
+ if (!deps && isFunction(callback)) {
+ deps = [];
+ //Remove comments from the callback string,
+ //look for require calls, and pull them into the dependencies,
+ //but only if there are function args.
+ if (callback.length) {
+ callback
+ .toString()
+ .replace(commentRegExp, '')
+ .replace(cjsRequireRegExp, function (match, dep) {
+ deps.push(dep);
+ });
+
+ //May be a CommonJS thing even without require calls, but still
+ //could use exports, and module. Avoid doing exports and module
+ //work though if it just needs require.
+ //REQUIRES the function to expect the CommonJS variables in the
+ //order listed below.
+ deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
+ }
+ }
+
+ //If in IE 6-8 and hit an anonymous define() call, do the interactive
+ //work.
+ if (useInteractive) {
+ node = currentlyAddingScript || getInteractiveScript();
+ if (node) {
+ if (!name) {
+ name = node.getAttribute('data-requiremodule');
+ }
+ context = contexts[node.getAttribute('data-requirecontext')];
+ }
+ }
+
+ //Always save off evaluating the def call until the script onload handler.
+ //This allows multiple modules to be in a file without prematurely
+ //tracing dependencies, and allows for anonymous module support,
+ //where the module name is not known until the script onload event
+ //occurs. If no context, use the global queue, and get it processed
+ //in the onscript load callback.
+ (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
+ };
+
+ define.amd = {
+ jQuery: true
+ };
+
+
+ /**
+ * Executes the text. Normally just uses eval, but can be modified
+ * to use a better, environment-specific call. Only used for transpiling
+ * loader plugins, not for plain JS modules.
+ * @param {String} text the text to execute/evaluate.
+ */
+ req.exec = function (text) {
+ /*jslint evil: true */
+ return eval(text);
+ };
+
+ //Set up with config info.
+ req(cfg);
+}(this));
diff --git a/labs/dependency-examples/backbone_marionette_require/bower_components/todomvc-common/base.css b/labs/dependency-examples/backbone_marionette_require/bower_components/todomvc-common/base.css
new file mode 100644
index 0000000000..a726662053
--- /dev/null
+++ b/labs/dependency-examples/backbone_marionette_require/bower_components/todomvc-common/base.css
@@ -0,0 +1,555 @@
+html,
+body {
+ margin: 0;
+ padding: 0;
+}
+
+button {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ background: none;
+ font-size: 100%;
+ vertical-align: baseline;
+ font-family: inherit;
+ color: inherit;
+ -webkit-appearance: none;
+ /*-moz-appearance: none;*/
+ -ms-appearance: none;
+ -o-appearance: none;
+ appearance: none;
+}
+
+body {
+ font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ line-height: 1.4em;
+ background: #eaeaea url('bg.png');
+ color: #4d4d4d;
+ width: 550px;
+ margin: 0 auto;
+ -webkit-font-smoothing: antialiased;
+ -moz-font-smoothing: antialiased;
+ -ms-font-smoothing: antialiased;
+ -o-font-smoothing: antialiased;
+ font-smoothing: antialiased;
+}
+
+#todoapp {
+ background: #fff;
+ background: rgba(255, 255, 255, 0.9);
+ margin: 130px 0 40px 0;
+ border: 1px solid #ccc;
+ position: relative;
+ border-top-left-radius: 2px;
+ border-top-right-radius: 2px;
+ box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.2),
+ 0 25px 50px 0 rgba(0, 0, 0, 0.15);
+}
+
+#todoapp:before {
+ content: '';
+ border-left: 1px solid #f5d6d6;
+ border-right: 1px solid #f5d6d6;
+ width: 2px;
+ position: absolute;
+ top: 0;
+ left: 40px;
+ height: 100%;
+}
+
+#todoapp input::-webkit-input-placeholder {
+ font-style: italic;
+}
+
+#todoapp input:-moz-placeholder {
+ font-style: italic;
+ color: #a9a9a9;
+}
+
+#todoapp h1 {
+ position: absolute;
+ top: -120px;
+ width: 100%;
+ font-size: 70px;
+ font-weight: bold;
+ text-align: center;
+ color: #b3b3b3;
+ color: rgba(255, 255, 255, 0.3);
+ text-shadow: -1px -1px rgba(0, 0, 0, 0.2);
+ -webkit-text-rendering: optimizeLegibility;
+ -moz-text-rendering: optimizeLegibility;
+ -ms-text-rendering: optimizeLegibility;
+ -o-text-rendering: optimizeLegibility;
+ text-rendering: optimizeLegibility;
+}
+
+#header {
+ padding-top: 15px;
+ border-radius: inherit;
+}
+
+#header:before {
+ content: '';
+ position: absolute;
+ top: 0;
+ right: 0;
+ left: 0;
+ height: 15px;
+ z-index: 2;
+ border-bottom: 1px solid #6c615c;
+ background: #8d7d77;
+ background: -webkit-gradient(linear, left top, left bottom, from(rgba(132, 110, 100, 0.8)),to(rgba(101, 84, 76, 0.8)));
+ background: -webkit-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
+ background: -moz-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
+ background: -o-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
+ background: -ms-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
+ background: linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
+ filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#9d8b83', EndColorStr='#847670');
+ border-top-left-radius: 1px;
+ border-top-right-radius: 1px;
+}
+
+#new-todo,
+.edit {
+ position: relative;
+ margin: 0;
+ width: 100%;
+ font-size: 24px;
+ font-family: inherit;
+ line-height: 1.4em;
+ border: 0;
+ outline: none;
+ color: inherit;
+ padding: 6px;
+ border: 1px solid #999;
+ box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ -ms-box-sizing: border-box;
+ -o-box-sizing: border-box;
+ box-sizing: border-box;
+ -webkit-font-smoothing: antialiased;
+ -moz-font-smoothing: antialiased;
+ -ms-font-smoothing: antialiased;
+ -o-font-smoothing: antialiased;
+ font-smoothing: antialiased;
+}
+
+#new-todo {
+ padding: 16px 16px 16px 60px;
+ border: none;
+ background: rgba(0, 0, 0, 0.02);
+ z-index: 2;
+ box-shadow: none;
+}
+
+#main {
+ position: relative;
+ z-index: 2;
+ border-top: 1px dotted #adadad;
+}
+
+label[for='toggle-all'] {
+ display: none;
+}
+
+#toggle-all {
+ position: absolute;
+ top: -42px;
+ left: -4px;
+ width: 40px;
+ text-align: center;
+ border: none; /* Mobile Safari */
+}
+
+#toggle-all:before {
+ content: '»';
+ font-size: 28px;
+ color: #d9d9d9;
+ padding: 0 25px 7px;
+}
+
+#toggle-all:checked:before {
+ color: #737373;
+}
+
+#todo-list {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+#todo-list li {
+ position: relative;
+ font-size: 24px;
+ border-bottom: 1px dotted #ccc;
+}
+
+#todo-list li:last-child {
+ border-bottom: none;
+}
+
+#todo-list li.editing {
+ border-bottom: none;
+ padding: 0;
+}
+
+#todo-list li.editing .edit {
+ display: block;
+ width: 506px;
+ padding: 13px 17px 12px 17px;
+ margin: 0 0 0 43px;
+}
+
+#todo-list li.editing .view {
+ display: none;
+}
+
+#todo-list li .toggle {
+ text-align: center;
+ width: 40px;
+ /* auto, since non-WebKit browsers doesn't support input styling */
+ height: auto;
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ margin: auto 0;
+ border: none; /* Mobile Safari */
+ -webkit-appearance: none;
+ /*-moz-appearance: none;*/
+ -ms-appearance: none;
+ -o-appearance: none;
+ appearance: none;
+}
+
+#todo-list li .toggle:after {
+ content: '✔';
+ line-height: 43px; /* 40 + a couple of pixels visual adjustment */
+ font-size: 20px;
+ color: #d9d9d9;
+ text-shadow: 0 -1px 0 #bfbfbf;
+}
+
+#todo-list li .toggle:checked:after {
+ color: #85ada7;
+ text-shadow: 0 1px 0 #669991;
+ bottom: 1px;
+ position: relative;
+}
+
+#todo-list li label {
+ word-break: break-word;
+ padding: 15px;
+ margin-left: 45px;
+ display: block;
+ line-height: 1.2;
+ -webkit-transition: color 0.4s;
+ -moz-transition: color 0.4s;
+ -ms-transition: color 0.4s;
+ -o-transition: color 0.4s;
+ transition: color 0.4s;
+}
+
+#todo-list li.completed label {
+ color: #a9a9a9;
+ text-decoration: line-through;
+}
+
+#todo-list li .destroy {
+ display: none;
+ position: absolute;
+ top: 0;
+ right: 10px;
+ bottom: 0;
+ width: 40px;
+ height: 40px;
+ margin: auto 0;
+ font-size: 22px;
+ color: #a88a8a;
+ -webkit-transition: all 0.2s;
+ -moz-transition: all 0.2s;
+ -ms-transition: all 0.2s;
+ -o-transition: all 0.2s;
+ transition: all 0.2s;
+}
+
+#todo-list li .destroy:hover {
+ text-shadow: 0 0 1px #000,
+ 0 0 10px rgba(199, 107, 107, 0.8);
+ -webkit-transform: scale(1.3);
+ -moz-transform: scale(1.3);
+ -ms-transform: scale(1.3);
+ -o-transform: scale(1.3);
+ transform: scale(1.3);
+}
+
+#todo-list li .destroy:after {
+ content: '✖';
+}
+
+#todo-list li:hover .destroy {
+ display: block;
+}
+
+#todo-list li .edit {
+ display: none;
+}
+
+#todo-list li.editing:last-child {
+ margin-bottom: -1px;
+}
+
+#footer {
+ color: #777;
+ padding: 0 15px;
+ position: absolute;
+ right: 0;
+ bottom: -31px;
+ left: 0;
+ height: 20px;
+ z-index: 1;
+ text-align: center;
+}
+
+#footer:before {
+ content: '';
+ position: absolute;
+ right: 0;
+ bottom: 31px;
+ left: 0;
+ height: 50px;
+ z-index: -1;
+ box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3),
+ 0 6px 0 -3px rgba(255, 255, 255, 0.8),
+ 0 7px 1px -3px rgba(0, 0, 0, 0.3),
+ 0 43px 0 -6px rgba(255, 255, 255, 0.8),
+ 0 44px 2px -6px rgba(0, 0, 0, 0.2);
+}
+
+#todo-count {
+ float: left;
+ text-align: left;
+}
+
+#filters {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ position: absolute;
+ right: 0;
+ left: 0;
+}
+
+#filters li {
+ display: inline;
+}
+
+#filters li a {
+ color: #83756f;
+ margin: 2px;
+ text-decoration: none;
+}
+
+#filters li a.selected {
+ font-weight: bold;
+}
+
+#clear-completed {
+ float: right;
+ position: relative;
+ line-height: 20px;
+ text-decoration: none;
+ background: rgba(0, 0, 0, 0.1);
+ font-size: 11px;
+ padding: 0 10px;
+ border-radius: 3px;
+ box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.2);
+}
+
+#clear-completed:hover {
+ background: rgba(0, 0, 0, 0.15);
+ box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.3);
+}
+
+#info {
+ margin: 65px auto 0;
+ color: #a6a6a6;
+ font-size: 12px;
+ text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7);
+ text-align: center;
+}
+
+#info a {
+ color: inherit;
+}
+
+/*
+ Hack to remove background from Mobile Safari.
+ Can't use it globally since it destroys checkboxes in Firefox and Opera
+*/
+@media screen and (-webkit-min-device-pixel-ratio:0) {
+ #toggle-all,
+ #todo-list li .toggle {
+ background: none;
+ }
+
+ #todo-list li .toggle {
+ height: 40px;
+ }
+
+ #toggle-all {
+ top: -56px;
+ left: -15px;
+ width: 65px;
+ height: 41px;
+ -webkit-transform: rotate(90deg);
+ transform: rotate(90deg);
+ -webkit-appearance: none;
+ appearance: none;
+ }
+}
+
+.hidden{
+ display:none;
+}
+
+hr {
+ margin: 20px 0;
+ border: 0;
+ border-top: 1px dashed #C5C5C5;
+ border-bottom: 1px dashed #F7F7F7;
+}
+
+.learn a {
+ font-weight: normal;
+ text-decoration: none;
+ color: #b83f45;
+}
+
+.learn a:hover {
+ text-decoration: underline;
+ color: #787e7e;
+}
+
+.learn h3,
+.learn h4,
+.learn h5 {
+ margin: 10px 0;
+ font-weight: 500;
+ line-height: 1.2;
+ color: #000;
+}
+
+.learn h3 {
+ font-size: 24px;
+}
+
+.learn h4 {
+ font-size: 18px;
+}
+
+.learn h5 {
+ margin-bottom: 0;
+ font-size: 14px;
+}
+
+.learn ul {
+ padding: 0;
+ margin: 0 0 30px 25px;
+}
+
+.learn li {
+ line-height: 20px;
+}
+
+.learn p {
+ font-size: 15px;
+ font-weight: 300;
+ line-height: 1.3;
+ margin-top: 0;
+ margin-bottom: 0;
+}
+
+.quote {
+ border: none;
+ margin: 20px 0 60px 0;
+}
+
+.quote p {
+ font-style: italic;
+}
+
+.quote p:before {
+ content: '“';
+ font-size: 50px;
+ opacity: .15;
+ position: absolute;
+ top: -20px;
+ left: 3px;
+}
+
+.quote p:after {
+ content: '”';
+ font-size: 50px;
+ opacity: .15;
+ position: absolute;
+ bottom: -42px;
+ right: 3px;
+}
+
+.quote footer {
+ position: absolute;
+ bottom: -40px;
+ right: 0;
+}
+
+.quote footer img {
+ border-radius: 3px;
+}
+
+.quote footer a {
+ margin-left: 5px;
+ vertical-align: middle;
+}
+
+.speech-bubble {
+ position: relative;
+ padding: 10px;
+ background: rgba(0, 0, 0, .04);
+ border-radius: 5px;
+}
+
+.speech-bubble:after {
+ content: '';
+ position: absolute;
+ top: 100%;
+ right: 30px;
+ border: 13px solid transparent;
+ border-top-color: rgba(0, 0, 0, .04);
+}
+
+/**body*/.learn-bar > .learn {
+ position: absolute;
+ width: 272px;
+ top: 8px;
+ left: -300px;
+ padding: 10px;
+ border-radius: 5px;
+ background-color: rgba(255, 255, 255, .6);
+ transition-property: left;
+ transition-duration: 500ms;
+}
+
+@media (min-width: 899px) {
+ /**body*/.learn-bar {
+ width: auto;
+ margin: 0 0 0 300px;
+ }
+ /**body*/.learn-bar > .learn {
+ left: 8px;
+ }
+ /**body*/.learn-bar #todoapp {
+ width: 550px;
+ margin: 130px auto 40px auto;
+ }
+}
diff --git a/labs/dependency-examples/backbone_marionette_require/bower_components/todomvc-common/base.js b/labs/dependency-examples/backbone_marionette_require/bower_components/todomvc-common/base.js
new file mode 100644
index 0000000000..5ca690ece1
--- /dev/null
+++ b/labs/dependency-examples/backbone_marionette_require/bower_components/todomvc-common/base.js
@@ -0,0 +1,182 @@
+(function () {
+ 'use strict';
+
+ if (location.hostname === 'todomvc.com') {
+ window._gaq = [['_setAccount','UA-31081062-1'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'));
+ }
+
+ function getSourcePath() {
+ // If accessed via tastejs.github.io/todomvc/, strip the project path.
+ if (location.hostname.indexOf('github.io') > 0) {
+ return location.pathname.replace(/todomvc\//, '');
+ }
+ return location.pathname;
+ }
+
+ function appendSourceLink() {
+ var sourceLink = document.createElement('a');
+ var paragraph = document.createElement('p');
+ var footer = document.getElementById('info');
+ var urlBase = 'https://github.com/tastejs/todomvc/tree/gh-pages';
+
+ if (footer) {
+ sourceLink.href = urlBase + getSourcePath();
+ sourceLink.appendChild(document.createTextNode('Check out the source'));
+ paragraph.appendChild(sourceLink);
+ footer.appendChild(paragraph);
+ }
+ }
+
+ function redirect() {
+ if (location.hostname === 'tastejs.github.io') {
+ location.href = location.href.replace('tastejs.github.io/todomvc', 'todomvc.com');
+ }
+ }
+
+ function findRoot() {
+ var base;
+
+ [/labs/, /\w*-examples/].forEach(function (href) {
+ var match = location.href.match(href);
+
+ if (!base && match) {
+ base = location.href.indexOf(match);
+ }
+ });
+
+ return location.href.substr(0, base);
+ }
+
+ function getFile(file, callback) {
+ var xhr = new XMLHttpRequest();
+
+ xhr.open('GET', findRoot() + file, true);
+ xhr.send();
+
+ xhr.onload = function () {
+ if (xhr.status === 200 && callback) {
+ callback(xhr.responseText);
+ }
+ };
+ }
+
+ function Learn(learnJSON, config) {
+ if (!(this instanceof Learn)) {
+ return new Learn(learnJSON, config);
+ }
+
+ var template, framework;
+
+ if (typeof learnJSON !== 'object') {
+ try {
+ learnJSON = JSON.parse(learnJSON);
+ } catch (e) {
+ return;
+ }
+ }
+
+ if (config) {
+ template = config.template;
+ framework = config.framework;
+ }
+
+ if (!template && learnJSON.templates) {
+ template = learnJSON.templates.todomvc;
+ }
+
+ if (!framework && document.querySelector('[data-framework]')) {
+ framework = document.querySelector('[data-framework]').getAttribute('data-framework');
+ }
+
+ if (template && learnJSON[framework]) {
+ this.frameworkJSON = learnJSON[framework];
+ this.template = template;
+
+ this.append();
+ }
+ }
+
+ Learn.prototype._prepareTemplate = function () {
+ var aside = document.createElement('aside');
+ aside.innerHTML = this.template;
+
+ var header = aside.cloneNode(true);
+ header.removeChild(header.querySelector('ul'));
+ header.removeChild(header.querySelectorAll('footer')[1]);
+
+ return {
+ header: header,
+ links: aside.cloneNode(true).querySelector('ul a'),
+ footer: aside.cloneNode(true).querySelectorAll('footer')[1]
+ };
+ };
+
+ Learn.prototype._parseTemplate = function () {
+ if (!this.template) {
+ return;
+ }
+
+ var frameworkJSON = this.frameworkJSON;
+ var template = this._prepareTemplate();
+
+ var aside = document.createElement('aside');
+ var linksTemplate = template.links.outerHTML;
+ var parser = /\{\{([^}]*)\}\}/g;
+
+ var header, examples, links;
+
+ header = template.header.innerHTML.replace(parser, function (match, key) {
+ return frameworkJSON[key];
+ });
+
+ aside.innerHTML = header;
+
+ if (frameworkJSON.examples) {
+ examples = frameworkJSON.examples.map(function (example) {
+ return ''
+ + '
' + example.name + ' '
+ + '
'
+ + (location.href.match(example.url + '/') ? '' : ' Demo , ')
+ + ' Source '
+ + '
';
+ }).join('');
+
+ aside.querySelector('.source-links').innerHTML = examples;
+ }
+
+ if (frameworkJSON.link_groups) {
+ links = frameworkJSON.link_groups.map(function (linkGroup) {
+ return ''
+ + '
' + linkGroup.heading + ' '
+ + '
'
+ + linkGroup.links.map(function (link) {
+ return ''
+ + ''
+ + linksTemplate.replace(parser, function (match, key) {
+ return link[key];
+ })
+ + ' ';
+ }).join('')
+ + ' ';
+ }).join('');
+
+ aside.innerHTML += links;
+ aside.innerHTML += template.footer.outerHTML;
+ }
+
+ return aside;
+ };
+
+ Learn.prototype.append = function () {
+ var aside = this._parseTemplate();
+
+ aside.className = 'learn';
+
+ document.body.className = (document.body.className + ' learn-bar').trim();
+ document.body.insertAdjacentElement('afterBegin', aside);
+ };
+
+ appendSourceLink();
+ redirect();
+ getFile('learn.json', Learn);
+})();
diff --git a/labs/dependency-examples/backbone_marionette_require/bower_components/todomvc-common/bg.png b/labs/dependency-examples/backbone_marionette_require/bower_components/todomvc-common/bg.png
new file mode 100644
index 0000000000000000000000000000000000000000..b2a7600825ee11f21849ed475499c7d1ecbcc870
GIT binary patch
literal 2126
zcmV-U2(kBxP)
+9y`=HK7nt=~3t000O5Nklm=04hVa_lXl_bm=+M;=eI<%$rO2ta`suh*Sr#POw*?adq!O!CV
z*0&b)rkCCEV)1nIuiLBntUH-MJI;&qYgz|d@Nhnn_abi2g`pu4NAMVid3hS%?quz~
zjlJf(x8cj{VS
zUVEP1msg9`^OFUhSO5rtXHhRlyU2i>6$BT=glG`{JlctGHrwRIm)6Buu65jLQn^H8
zvl9lZqUBA+%qvM5XC+yY@mfA(YB~XP=e|6<{%$^eU8nrK?v2ccb@Jom5CG>rKAL7J
zplHEIavVp|0p1&m!G`Ti?<7iZ;}@G7#Z)}Km%2!FHnQ0*&?PLR)G!HAaHgU#c|$dz
zpj#0HmeadIe>`#)=Jjkb{B=FKnU3pc-&Y@j_j6(h4Y~+Uq!^J=LHunx1xi4QXK-Y{&MoT8ky6Vb9c|WhnOwF~c=3zOy8agktliS6#
z`#8F`9H)D=bmk9B5MnW&_r#)f$c+;$LSr-@^An8dhc~Iquuv>jOK7pw7LJ;&X0i1C
zGMsHdP1Os@ny$$j!>XAii%7bp5k>`pyNA!~epb)()p9zR4Yl6z=U}{CIdh1z(FpAo
zQIW!;0zpCyC4*7YLkZCO@cul0R_&zghsA8Ek)z%jNpKa92{@NH+SstX%@}xB*Jk!l}PZ1cClIns~}5^!RncUk*rmA
z%SIVgt58EQxLJ+OiFqKkBuwquyZLUp|gr
zPUbUbFbBrPd1xO`^C*r-i3p9*F#(OBh!4Wy@aC&*!|O|GXcjDA&YhF{;cD7*o(GS^
z@pQSE7)x_81=Qyje6*LQ#TXu-7(o;S8u3tpDA0_ddj%hmCspeXdhYR}-i9A=C`EoChUYuH~^x!9+|&(Pgb*>Ck<=9j|)*@xyfT
zpP#+Kt<}39b|3Wl4fxT(+G?aH>gG^d@MEaUOJRfy55TtFI7^Y)VuMU=7Pp0y55jS~
z+TJ)igMyrqkX;wU8j68iIDtqJYhS_D3_Oem-@g6me_RfiQ}uT_K-A-9qG%}gk3E9c
z!8`KgsMNXm)beloPfMql*|&$M>1q`i!cY)RFYnjNYu*gSv@8XebV7%}xYL>6)GJPJ
zJpA7K31lcJuIFKSw-{x4FX0K2Az)~Xg<`sOu$4|^-(^XJX4YzoiNRvL
zyuY7~26w-P^Zw%6F}shBwV2$02c8RsSUy6dM92diCAxiX3IUqsq5ig6>U_!Vy*q5$
zjm}16tJr+QZ&T?HkkpeIwVX-r1EI=@%Zlt;6g*mj&E!A))%gXJ=x6u#l
zcKEP>bx4rqV*k`BBrZ$Mqjt{TsHcxUH>;)iAK}B(Kila&VD%b?6m&^0WK4^&EZNAI
z8AMYs_%$D%|M+@+cQqL-hi4yG>h*jwdii!W1{}p>ZhwFYt_4Su1kjY9<-5`!$VNOI1y(EDSH4WpCijE_>al!Nt=^eVER#uJ1=b
z;BWF2IgyF5LexV+yec$Kin;Ai@myo;G>zJ&jrdW#ecXhIZph5OYqw_PEfcF56Z5Zu_ZZE#q3Mc+N&1O^7hoh9QR7`+L$cBP5pqG=fqA0uh
zUBukaxTFmH)<|Xbvp2c=HSbNkpXw73a5lv7V$jb92#yZ141@$X?F}Jt8gIU7Wm6m9
z?e_;;zsnm6`LZeP>T=$)Kr>Z?kr*UmFqR7zx0C6^bmcsc@1AGtw_rNH>-Xm$d*|Q<
zn&1Ln0u7=l&ILs>%CkJp`DiG9F18x4Ne+lg<#i?e7jL%x;4ZnRkN^Mx07*qoM6N<$
Ef(>0N!2kdN
literal 0
HcmV?d00001
diff --git a/labs/dependency-examples/backbone_marionette_require/bower_components/underscore/underscore.js b/labs/dependency-examples/backbone_marionette_require/bower_components/underscore/underscore.js
new file mode 100644
index 0000000000..a12f0d96cf
--- /dev/null
+++ b/labs/dependency-examples/backbone_marionette_require/bower_components/underscore/underscore.js
@@ -0,0 +1,1226 @@
+// Underscore.js 1.4.4
+// http://underscorejs.org
+// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
+// Underscore may be freely distributed under the MIT license.
+
+(function() {
+
+ // Baseline setup
+ // --------------
+
+ // Establish the root object, `window` in the browser, or `global` on the server.
+ var root = this;
+
+ // Save the previous value of the `_` variable.
+ var previousUnderscore = root._;
+
+ // Establish the object that gets returned to break out of a loop iteration.
+ var breaker = {};
+
+ // Save bytes in the minified (but not gzipped) version:
+ var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
+
+ // Create quick reference variables for speed access to core prototypes.
+ var push = ArrayProto.push,
+ slice = ArrayProto.slice,
+ concat = ArrayProto.concat,
+ toString = ObjProto.toString,
+ hasOwnProperty = ObjProto.hasOwnProperty;
+
+ // All **ECMAScript 5** native function implementations that we hope to use
+ // are declared here.
+ var
+ nativeForEach = ArrayProto.forEach,
+ nativeMap = ArrayProto.map,
+ nativeReduce = ArrayProto.reduce,
+ nativeReduceRight = ArrayProto.reduceRight,
+ nativeFilter = ArrayProto.filter,
+ nativeEvery = ArrayProto.every,
+ nativeSome = ArrayProto.some,
+ nativeIndexOf = ArrayProto.indexOf,
+ nativeLastIndexOf = ArrayProto.lastIndexOf,
+ nativeIsArray = Array.isArray,
+ nativeKeys = Object.keys,
+ nativeBind = FuncProto.bind;
+
+ // Create a safe reference to the Underscore object for use below.
+ var _ = function(obj) {
+ if (obj instanceof _) return obj;
+ if (!(this instanceof _)) return new _(obj);
+ this._wrapped = obj;
+ };
+
+ // Export the Underscore object for **Node.js**, with
+ // backwards-compatibility for the old `require()` API. If we're in
+ // the browser, add `_` as a global object via a string identifier,
+ // for Closure Compiler "advanced" mode.
+ if (typeof exports !== 'undefined') {
+ if (typeof module !== 'undefined' && module.exports) {
+ exports = module.exports = _;
+ }
+ exports._ = _;
+ } else {
+ root._ = _;
+ }
+
+ // Current version.
+ _.VERSION = '1.4.4';
+
+ // Collection Functions
+ // --------------------
+
+ // The cornerstone, an `each` implementation, aka `forEach`.
+ // Handles objects with the built-in `forEach`, arrays, and raw objects.
+ // Delegates to **ECMAScript 5**'s native `forEach` if available.
+ var each = _.each = _.forEach = function(obj, iterator, context) {
+ if (obj == null) return;
+ if (nativeForEach && obj.forEach === nativeForEach) {
+ obj.forEach(iterator, context);
+ } else if (obj.length === +obj.length) {
+ for (var i = 0, l = obj.length; i < l; i++) {
+ if (iterator.call(context, obj[i], i, obj) === breaker) return;
+ }
+ } else {
+ for (var key in obj) {
+ if (_.has(obj, key)) {
+ if (iterator.call(context, obj[key], key, obj) === breaker) return;
+ }
+ }
+ }
+ };
+
+ // Return the results of applying the iterator to each element.
+ // Delegates to **ECMAScript 5**'s native `map` if available.
+ _.map = _.collect = function(obj, iterator, context) {
+ var results = [];
+ if (obj == null) return results;
+ if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
+ each(obj, function(value, index, list) {
+ results[results.length] = iterator.call(context, value, index, list);
+ });
+ return results;
+ };
+
+ var reduceError = 'Reduce of empty array with no initial value';
+
+ // **Reduce** builds up a single result from a list of values, aka `inject`,
+ // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
+ _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
+ var initial = arguments.length > 2;
+ if (obj == null) obj = [];
+ if (nativeReduce && obj.reduce === nativeReduce) {
+ if (context) iterator = _.bind(iterator, context);
+ return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
+ }
+ each(obj, function(value, index, list) {
+ if (!initial) {
+ memo = value;
+ initial = true;
+ } else {
+ memo = iterator.call(context, memo, value, index, list);
+ }
+ });
+ if (!initial) throw new TypeError(reduceError);
+ return memo;
+ };
+
+ // The right-associative version of reduce, also known as `foldr`.
+ // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
+ _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
+ var initial = arguments.length > 2;
+ if (obj == null) obj = [];
+ if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
+ if (context) iterator = _.bind(iterator, context);
+ return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
+ }
+ var length = obj.length;
+ if (length !== +length) {
+ var keys = _.keys(obj);
+ length = keys.length;
+ }
+ each(obj, function(value, index, list) {
+ index = keys ? keys[--length] : --length;
+ if (!initial) {
+ memo = obj[index];
+ initial = true;
+ } else {
+ memo = iterator.call(context, memo, obj[index], index, list);
+ }
+ });
+ if (!initial) throw new TypeError(reduceError);
+ return memo;
+ };
+
+ // Return the first value which passes a truth test. Aliased as `detect`.
+ _.find = _.detect = function(obj, iterator, context) {
+ var result;
+ any(obj, function(value, index, list) {
+ if (iterator.call(context, value, index, list)) {
+ result = value;
+ return true;
+ }
+ });
+ return result;
+ };
+
+ // Return all the elements that pass a truth test.
+ // Delegates to **ECMAScript 5**'s native `filter` if available.
+ // Aliased as `select`.
+ _.filter = _.select = function(obj, iterator, context) {
+ var results = [];
+ if (obj == null) return results;
+ if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
+ each(obj, function(value, index, list) {
+ if (iterator.call(context, value, index, list)) results[results.length] = value;
+ });
+ return results;
+ };
+
+ // Return all the elements for which a truth test fails.
+ _.reject = function(obj, iterator, context) {
+ return _.filter(obj, function(value, index, list) {
+ return !iterator.call(context, value, index, list);
+ }, context);
+ };
+
+ // Determine whether all of the elements match a truth test.
+ // Delegates to **ECMAScript 5**'s native `every` if available.
+ // Aliased as `all`.
+ _.every = _.all = function(obj, iterator, context) {
+ iterator || (iterator = _.identity);
+ var result = true;
+ if (obj == null) return result;
+ if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
+ each(obj, function(value, index, list) {
+ if (!(result = result && iterator.call(context, value, index, list))) return breaker;
+ });
+ return !!result;
+ };
+
+ // Determine if at least one element in the object matches a truth test.
+ // Delegates to **ECMAScript 5**'s native `some` if available.
+ // Aliased as `any`.
+ var any = _.some = _.any = function(obj, iterator, context) {
+ iterator || (iterator = _.identity);
+ var result = false;
+ if (obj == null) return result;
+ if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
+ each(obj, function(value, index, list) {
+ if (result || (result = iterator.call(context, value, index, list))) return breaker;
+ });
+ return !!result;
+ };
+
+ // Determine if the array or object contains a given value (using `===`).
+ // Aliased as `include`.
+ _.contains = _.include = function(obj, target) {
+ if (obj == null) return false;
+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
+ return any(obj, function(value) {
+ return value === target;
+ });
+ };
+
+ // Invoke a method (with arguments) on every item in a collection.
+ _.invoke = function(obj, method) {
+ var args = slice.call(arguments, 2);
+ var isFunc = _.isFunction(method);
+ return _.map(obj, function(value) {
+ return (isFunc ? method : value[method]).apply(value, args);
+ });
+ };
+
+ // Convenience version of a common use case of `map`: fetching a property.
+ _.pluck = function(obj, key) {
+ return _.map(obj, function(value){ return value[key]; });
+ };
+
+ // Convenience version of a common use case of `filter`: selecting only objects
+ // containing specific `key:value` pairs.
+ _.where = function(obj, attrs, first) {
+ if (_.isEmpty(attrs)) return first ? null : [];
+ return _[first ? 'find' : 'filter'](obj, function(value) {
+ for (var key in attrs) {
+ if (attrs[key] !== value[key]) return false;
+ }
+ return true;
+ });
+ };
+
+ // Convenience version of a common use case of `find`: getting the first object
+ // containing specific `key:value` pairs.
+ _.findWhere = function(obj, attrs) {
+ return _.where(obj, attrs, true);
+ };
+
+ // Return the maximum element or (element-based computation).
+ // Can't optimize arrays of integers longer than 65,535 elements.
+ // See: https://bugs.webkit.org/show_bug.cgi?id=80797
+ _.max = function(obj, iterator, context) {
+ if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
+ return Math.max.apply(Math, obj);
+ }
+ if (!iterator && _.isEmpty(obj)) return -Infinity;
+ var result = {computed : -Infinity, value: -Infinity};
+ each(obj, function(value, index, list) {
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
+ computed >= result.computed && (result = {value : value, computed : computed});
+ });
+ return result.value;
+ };
+
+ // Return the minimum element (or element-based computation).
+ _.min = function(obj, iterator, context) {
+ if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
+ return Math.min.apply(Math, obj);
+ }
+ if (!iterator && _.isEmpty(obj)) return Infinity;
+ var result = {computed : Infinity, value: Infinity};
+ each(obj, function(value, index, list) {
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
+ computed < result.computed && (result = {value : value, computed : computed});
+ });
+ return result.value;
+ };
+
+ // Shuffle an array.
+ _.shuffle = function(obj) {
+ var rand;
+ var index = 0;
+ var shuffled = [];
+ each(obj, function(value) {
+ rand = _.random(index++);
+ shuffled[index - 1] = shuffled[rand];
+ shuffled[rand] = value;
+ });
+ return shuffled;
+ };
+
+ // An internal function to generate lookup iterators.
+ var lookupIterator = function(value) {
+ return _.isFunction(value) ? value : function(obj){ return obj[value]; };
+ };
+
+ // Sort the object's values by a criterion produced by an iterator.
+ _.sortBy = function(obj, value, context) {
+ var iterator = lookupIterator(value);
+ return _.pluck(_.map(obj, function(value, index, list) {
+ return {
+ value : value,
+ index : index,
+ criteria : iterator.call(context, value, index, list)
+ };
+ }).sort(function(left, right) {
+ var a = left.criteria;
+ var b = right.criteria;
+ if (a !== b) {
+ if (a > b || a === void 0) return 1;
+ if (a < b || b === void 0) return -1;
+ }
+ return left.index < right.index ? -1 : 1;
+ }), 'value');
+ };
+
+ // An internal function used for aggregate "group by" operations.
+ var group = function(obj, value, context, behavior) {
+ var result = {};
+ var iterator = lookupIterator(value || _.identity);
+ each(obj, function(value, index) {
+ var key = iterator.call(context, value, index, obj);
+ behavior(result, key, value);
+ });
+ return result;
+ };
+
+ // Groups the object's values by a criterion. Pass either a string attribute
+ // to group by, or a function that returns the criterion.
+ _.groupBy = function(obj, value, context) {
+ return group(obj, value, context, function(result, key, value) {
+ (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
+ });
+ };
+
+ // Counts instances of an object that group by a certain criterion. Pass
+ // either a string attribute to count by, or a function that returns the
+ // criterion.
+ _.countBy = function(obj, value, context) {
+ return group(obj, value, context, function(result, key) {
+ if (!_.has(result, key)) result[key] = 0;
+ result[key]++;
+ });
+ };
+
+ // Use a comparator function to figure out the smallest index at which
+ // an object should be inserted so as to maintain order. Uses binary search.
+ _.sortedIndex = function(array, obj, iterator, context) {
+ iterator = iterator == null ? _.identity : lookupIterator(iterator);
+ var value = iterator.call(context, obj);
+ var low = 0, high = array.length;
+ while (low < high) {
+ var mid = (low + high) >>> 1;
+ iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
+ }
+ return low;
+ };
+
+ // Safely convert anything iterable into a real, live array.
+ _.toArray = function(obj) {
+ if (!obj) return [];
+ if (_.isArray(obj)) return slice.call(obj);
+ if (obj.length === +obj.length) return _.map(obj, _.identity);
+ return _.values(obj);
+ };
+
+ // Return the number of elements in an object.
+ _.size = function(obj) {
+ if (obj == null) return 0;
+ return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
+ };
+
+ // Array Functions
+ // ---------------
+
+ // Get the first element of an array. Passing **n** will return the first N
+ // values in the array. Aliased as `head` and `take`. The **guard** check
+ // allows it to work with `_.map`.
+ _.first = _.head = _.take = function(array, n, guard) {
+ if (array == null) return void 0;
+ return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
+ };
+
+ // Returns everything but the last entry of the array. Especially useful on
+ // the arguments object. Passing **n** will return all the values in
+ // the array, excluding the last N. The **guard** check allows it to work with
+ // `_.map`.
+ _.initial = function(array, n, guard) {
+ return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
+ };
+
+ // Get the last element of an array. Passing **n** will return the last N
+ // values in the array. The **guard** check allows it to work with `_.map`.
+ _.last = function(array, n, guard) {
+ if (array == null) return void 0;
+ if ((n != null) && !guard) {
+ return slice.call(array, Math.max(array.length - n, 0));
+ } else {
+ return array[array.length - 1];
+ }
+ };
+
+ // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
+ // Especially useful on the arguments object. Passing an **n** will return
+ // the rest N values in the array. The **guard**
+ // check allows it to work with `_.map`.
+ _.rest = _.tail = _.drop = function(array, n, guard) {
+ return slice.call(array, (n == null) || guard ? 1 : n);
+ };
+
+ // Trim out all falsy values from an array.
+ _.compact = function(array) {
+ return _.filter(array, _.identity);
+ };
+
+ // Internal implementation of a recursive `flatten` function.
+ var flatten = function(input, shallow, output) {
+ each(input, function(value) {
+ if (_.isArray(value)) {
+ shallow ? push.apply(output, value) : flatten(value, shallow, output);
+ } else {
+ output.push(value);
+ }
+ });
+ return output;
+ };
+
+ // Return a completely flattened version of an array.
+ _.flatten = function(array, shallow) {
+ return flatten(array, shallow, []);
+ };
+
+ // Return a version of the array that does not contain the specified value(s).
+ _.without = function(array) {
+ return _.difference(array, slice.call(arguments, 1));
+ };
+
+ // Produce a duplicate-free version of the array. If the array has already
+ // been sorted, you have the option of using a faster algorithm.
+ // Aliased as `unique`.
+ _.uniq = _.unique = function(array, isSorted, iterator, context) {
+ if (_.isFunction(isSorted)) {
+ context = iterator;
+ iterator = isSorted;
+ isSorted = false;
+ }
+ var initial = iterator ? _.map(array, iterator, context) : array;
+ var results = [];
+ var seen = [];
+ each(initial, function(value, index) {
+ if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
+ seen.push(value);
+ results.push(array[index]);
+ }
+ });
+ return results;
+ };
+
+ // Produce an array that contains the union: each distinct element from all of
+ // the passed-in arrays.
+ _.union = function() {
+ return _.uniq(concat.apply(ArrayProto, arguments));
+ };
+
+ // Produce an array that contains every item shared between all the
+ // passed-in arrays.
+ _.intersection = function(array) {
+ var rest = slice.call(arguments, 1);
+ return _.filter(_.uniq(array), function(item) {
+ return _.every(rest, function(other) {
+ return _.indexOf(other, item) >= 0;
+ });
+ });
+ };
+
+ // Take the difference between one array and a number of other arrays.
+ // Only the elements present in just the first array will remain.
+ _.difference = function(array) {
+ var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
+ return _.filter(array, function(value){ return !_.contains(rest, value); });
+ };
+
+ // Zip together multiple lists into a single array -- elements that share
+ // an index go together.
+ _.zip = function() {
+ var args = slice.call(arguments);
+ var length = _.max(_.pluck(args, 'length'));
+ var results = new Array(length);
+ for (var i = 0; i < length; i++) {
+ results[i] = _.pluck(args, "" + i);
+ }
+ return results;
+ };
+
+ // Converts lists into objects. Pass either a single array of `[key, value]`
+ // pairs, or two parallel arrays of the same length -- one of keys, and one of
+ // the corresponding values.
+ _.object = function(list, values) {
+ if (list == null) return {};
+ var result = {};
+ for (var i = 0, l = list.length; i < l; i++) {
+ if (values) {
+ result[list[i]] = values[i];
+ } else {
+ result[list[i][0]] = list[i][1];
+ }
+ }
+ return result;
+ };
+
+ // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
+ // we need this function. Return the position of the first occurrence of an
+ // item in an array, or -1 if the item is not included in the array.
+ // Delegates to **ECMAScript 5**'s native `indexOf` if available.
+ // If the array is large and already in sort order, pass `true`
+ // for **isSorted** to use binary search.
+ _.indexOf = function(array, item, isSorted) {
+ if (array == null) return -1;
+ var i = 0, l = array.length;
+ if (isSorted) {
+ if (typeof isSorted == 'number') {
+ i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
+ } else {
+ i = _.sortedIndex(array, item);
+ return array[i] === item ? i : -1;
+ }
+ }
+ if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
+ for (; i < l; i++) if (array[i] === item) return i;
+ return -1;
+ };
+
+ // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
+ _.lastIndexOf = function(array, item, from) {
+ if (array == null) return -1;
+ var hasIndex = from != null;
+ if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
+ return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
+ }
+ var i = (hasIndex ? from : array.length);
+ while (i--) if (array[i] === item) return i;
+ return -1;
+ };
+
+ // Generate an integer Array containing an arithmetic progression. A port of
+ // the native Python `range()` function. See
+ // [the Python documentation](http://docs.python.org/library/functions.html#range).
+ _.range = function(start, stop, step) {
+ if (arguments.length <= 1) {
+ stop = start || 0;
+ start = 0;
+ }
+ step = arguments[2] || 1;
+
+ var len = Math.max(Math.ceil((stop - start) / step), 0);
+ var idx = 0;
+ var range = new Array(len);
+
+ while(idx < len) {
+ range[idx++] = start;
+ start += step;
+ }
+
+ return range;
+ };
+
+ // Function (ahem) Functions
+ // ------------------
+
+ // Create a function bound to a given object (assigning `this`, and arguments,
+ // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
+ // available.
+ _.bind = function(func, context) {
+ if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
+ var args = slice.call(arguments, 2);
+ return function() {
+ return func.apply(context, args.concat(slice.call(arguments)));
+ };
+ };
+
+ // Partially apply a function by creating a version that has had some of its
+ // arguments pre-filled, without changing its dynamic `this` context.
+ _.partial = function(func) {
+ var args = slice.call(arguments, 1);
+ return function() {
+ return func.apply(this, args.concat(slice.call(arguments)));
+ };
+ };
+
+ // Bind all of an object's methods to that object. Useful for ensuring that
+ // all callbacks defined on an object belong to it.
+ _.bindAll = function(obj) {
+ var funcs = slice.call(arguments, 1);
+ if (funcs.length === 0) funcs = _.functions(obj);
+ each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
+ return obj;
+ };
+
+ // Memoize an expensive function by storing its results.
+ _.memoize = function(func, hasher) {
+ var memo = {};
+ hasher || (hasher = _.identity);
+ return function() {
+ var key = hasher.apply(this, arguments);
+ return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
+ };
+ };
+
+ // Delays a function for the given number of milliseconds, and then calls
+ // it with the arguments supplied.
+ _.delay = function(func, wait) {
+ var args = slice.call(arguments, 2);
+ return setTimeout(function(){ return func.apply(null, args); }, wait);
+ };
+
+ // Defers a function, scheduling it to run after the current call stack has
+ // cleared.
+ _.defer = function(func) {
+ return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
+ };
+
+ // Returns a function, that, when invoked, will only be triggered at most once
+ // during a given window of time.
+ _.throttle = function(func, wait) {
+ var context, args, timeout, result;
+ var previous = 0;
+ var later = function() {
+ previous = new Date;
+ timeout = null;
+ result = func.apply(context, args);
+ };
+ return function() {
+ var now = new Date;
+ var remaining = wait - (now - previous);
+ context = this;
+ args = arguments;
+ if (remaining <= 0) {
+ clearTimeout(timeout);
+ timeout = null;
+ previous = now;
+ result = func.apply(context, args);
+ } else if (!timeout) {
+ timeout = setTimeout(later, remaining);
+ }
+ return result;
+ };
+ };
+
+ // Returns a function, that, as long as it continues to be invoked, will not
+ // be triggered. The function will be called after it stops being called for
+ // N milliseconds. If `immediate` is passed, trigger the function on the
+ // leading edge, instead of the trailing.
+ _.debounce = function(func, wait, immediate) {
+ var timeout, result;
+ return function() {
+ var context = this, args = arguments;
+ var later = function() {
+ timeout = null;
+ if (!immediate) result = func.apply(context, args);
+ };
+ var callNow = immediate && !timeout;
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ if (callNow) result = func.apply(context, args);
+ return result;
+ };
+ };
+
+ // Returns a function that will be executed at most one time, no matter how
+ // often you call it. Useful for lazy initialization.
+ _.once = function(func) {
+ var ran = false, memo;
+ return function() {
+ if (ran) return memo;
+ ran = true;
+ memo = func.apply(this, arguments);
+ func = null;
+ return memo;
+ };
+ };
+
+ // Returns the first function passed as an argument to the second,
+ // allowing you to adjust arguments, run code before and after, and
+ // conditionally execute the original function.
+ _.wrap = function(func, wrapper) {
+ return function() {
+ var args = [func];
+ push.apply(args, arguments);
+ return wrapper.apply(this, args);
+ };
+ };
+
+ // Returns a function that is the composition of a list of functions, each
+ // consuming the return value of the function that follows.
+ _.compose = function() {
+ var funcs = arguments;
+ return function() {
+ var args = arguments;
+ for (var i = funcs.length - 1; i >= 0; i--) {
+ args = [funcs[i].apply(this, args)];
+ }
+ return args[0];
+ };
+ };
+
+ // Returns a function that will only be executed after being called N times.
+ _.after = function(times, func) {
+ if (times <= 0) return func();
+ return function() {
+ if (--times < 1) {
+ return func.apply(this, arguments);
+ }
+ };
+ };
+
+ // Object Functions
+ // ----------------
+
+ // Retrieve the names of an object's properties.
+ // Delegates to **ECMAScript 5**'s native `Object.keys`
+ _.keys = nativeKeys || function(obj) {
+ if (obj !== Object(obj)) throw new TypeError('Invalid object');
+ var keys = [];
+ for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
+ return keys;
+ };
+
+ // Retrieve the values of an object's properties.
+ _.values = function(obj) {
+ var values = [];
+ for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
+ return values;
+ };
+
+ // Convert an object into a list of `[key, value]` pairs.
+ _.pairs = function(obj) {
+ var pairs = [];
+ for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
+ return pairs;
+ };
+
+ // Invert the keys and values of an object. The values must be serializable.
+ _.invert = function(obj) {
+ var result = {};
+ for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
+ return result;
+ };
+
+ // Return a sorted list of the function names available on the object.
+ // Aliased as `methods`
+ _.functions = _.methods = function(obj) {
+ var names = [];
+ for (var key in obj) {
+ if (_.isFunction(obj[key])) names.push(key);
+ }
+ return names.sort();
+ };
+
+ // Extend a given object with all the properties in passed-in object(s).
+ _.extend = function(obj) {
+ each(slice.call(arguments, 1), function(source) {
+ if (source) {
+ for (var prop in source) {
+ obj[prop] = source[prop];
+ }
+ }
+ });
+ return obj;
+ };
+
+ // Return a copy of the object only containing the whitelisted properties.
+ _.pick = function(obj) {
+ var copy = {};
+ var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
+ each(keys, function(key) {
+ if (key in obj) copy[key] = obj[key];
+ });
+ return copy;
+ };
+
+ // Return a copy of the object without the blacklisted properties.
+ _.omit = function(obj) {
+ var copy = {};
+ var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
+ for (var key in obj) {
+ if (!_.contains(keys, key)) copy[key] = obj[key];
+ }
+ return copy;
+ };
+
+ // Fill in a given object with default properties.
+ _.defaults = function(obj) {
+ each(slice.call(arguments, 1), function(source) {
+ if (source) {
+ for (var prop in source) {
+ if (obj[prop] == null) obj[prop] = source[prop];
+ }
+ }
+ });
+ return obj;
+ };
+
+ // Create a (shallow-cloned) duplicate of an object.
+ _.clone = function(obj) {
+ if (!_.isObject(obj)) return obj;
+ return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
+ };
+
+ // Invokes interceptor with the obj, and then returns obj.
+ // The primary purpose of this method is to "tap into" a method chain, in
+ // order to perform operations on intermediate results within the chain.
+ _.tap = function(obj, interceptor) {
+ interceptor(obj);
+ return obj;
+ };
+
+ // Internal recursive comparison function for `isEqual`.
+ var eq = function(a, b, aStack, bStack) {
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
+ // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
+ if (a === b) return a !== 0 || 1 / a == 1 / b;
+ // A strict comparison is necessary because `null == undefined`.
+ if (a == null || b == null) return a === b;
+ // Unwrap any wrapped objects.
+ if (a instanceof _) a = a._wrapped;
+ if (b instanceof _) b = b._wrapped;
+ // Compare `[[Class]]` names.
+ var className = toString.call(a);
+ if (className != toString.call(b)) return false;
+ switch (className) {
+ // Strings, numbers, dates, and booleans are compared by value.
+ case '[object String]':
+ // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
+ // equivalent to `new String("5")`.
+ return a == String(b);
+ case '[object Number]':
+ // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
+ // other numeric values.
+ return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
+ case '[object Date]':
+ case '[object Boolean]':
+ // Coerce dates and booleans to numeric primitive values. Dates are compared by their
+ // millisecond representations. Note that invalid dates with millisecond representations
+ // of `NaN` are not equivalent.
+ return +a == +b;
+ // RegExps are compared by their source patterns and flags.
+ case '[object RegExp]':
+ return a.source == b.source &&
+ a.global == b.global &&
+ a.multiline == b.multiline &&
+ a.ignoreCase == b.ignoreCase;
+ }
+ if (typeof a != 'object' || typeof b != 'object') return false;
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
+ var length = aStack.length;
+ while (length--) {
+ // Linear search. Performance is inversely proportional to the number of
+ // unique nested structures.
+ if (aStack[length] == a) return bStack[length] == b;
+ }
+ // Add the first object to the stack of traversed objects.
+ aStack.push(a);
+ bStack.push(b);
+ var size = 0, result = true;
+ // Recursively compare objects and arrays.
+ if (className == '[object Array]') {
+ // Compare array lengths to determine if a deep comparison is necessary.
+ size = a.length;
+ result = size == b.length;
+ if (result) {
+ // Deep compare the contents, ignoring non-numeric properties.
+ while (size--) {
+ if (!(result = eq(a[size], b[size], aStack, bStack))) break;
+ }
+ }
+ } else {
+ // Objects with different constructors are not equivalent, but `Object`s
+ // from different frames are.
+ var aCtor = a.constructor, bCtor = b.constructor;
+ if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
+ _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
+ return false;
+ }
+ // Deep compare objects.
+ for (var key in a) {
+ if (_.has(a, key)) {
+ // Count the expected number of properties.
+ size++;
+ // Deep compare each member.
+ if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
+ }
+ }
+ // Ensure that both objects contain the same number of properties.
+ if (result) {
+ for (key in b) {
+ if (_.has(b, key) && !(size--)) break;
+ }
+ result = !size;
+ }
+ }
+ // Remove the first object from the stack of traversed objects.
+ aStack.pop();
+ bStack.pop();
+ return result;
+ };
+
+ // Perform a deep comparison to check if two objects are equal.
+ _.isEqual = function(a, b) {
+ return eq(a, b, [], []);
+ };
+
+ // Is a given array, string, or object empty?
+ // An "empty" object has no enumerable own-properties.
+ _.isEmpty = function(obj) {
+ if (obj == null) return true;
+ if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
+ for (var key in obj) if (_.has(obj, key)) return false;
+ return true;
+ };
+
+ // Is a given value a DOM element?
+ _.isElement = function(obj) {
+ return !!(obj && obj.nodeType === 1);
+ };
+
+ // Is a given value an array?
+ // Delegates to ECMA5's native Array.isArray
+ _.isArray = nativeIsArray || function(obj) {
+ return toString.call(obj) == '[object Array]';
+ };
+
+ // Is a given variable an object?
+ _.isObject = function(obj) {
+ return obj === Object(obj);
+ };
+
+ // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
+ each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
+ _['is' + name] = function(obj) {
+ return toString.call(obj) == '[object ' + name + ']';
+ };
+ });
+
+ // Define a fallback version of the method in browsers (ahem, IE), where
+ // there isn't any inspectable "Arguments" type.
+ if (!_.isArguments(arguments)) {
+ _.isArguments = function(obj) {
+ return !!(obj && _.has(obj, 'callee'));
+ };
+ }
+
+ // Optimize `isFunction` if appropriate.
+ if (typeof (/./) !== 'function') {
+ _.isFunction = function(obj) {
+ return typeof obj === 'function';
+ };
+ }
+
+ // Is a given object a finite number?
+ _.isFinite = function(obj) {
+ return isFinite(obj) && !isNaN(parseFloat(obj));
+ };
+
+ // Is the given value `NaN`? (NaN is the only number which does not equal itself).
+ _.isNaN = function(obj) {
+ return _.isNumber(obj) && obj != +obj;
+ };
+
+ // Is a given value a boolean?
+ _.isBoolean = function(obj) {
+ return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
+ };
+
+ // Is a given value equal to null?
+ _.isNull = function(obj) {
+ return obj === null;
+ };
+
+ // Is a given variable undefined?
+ _.isUndefined = function(obj) {
+ return obj === void 0;
+ };
+
+ // Shortcut function for checking if an object has a given property directly
+ // on itself (in other words, not on a prototype).
+ _.has = function(obj, key) {
+ return hasOwnProperty.call(obj, key);
+ };
+
+ // Utility Functions
+ // -----------------
+
+ // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
+ // previous owner. Returns a reference to the Underscore object.
+ _.noConflict = function() {
+ root._ = previousUnderscore;
+ return this;
+ };
+
+ // Keep the identity function around for default iterators.
+ _.identity = function(value) {
+ return value;
+ };
+
+ // Run a function **n** times.
+ _.times = function(n, iterator, context) {
+ var accum = Array(n);
+ for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
+ return accum;
+ };
+
+ // Return a random integer between min and max (inclusive).
+ _.random = function(min, max) {
+ if (max == null) {
+ max = min;
+ min = 0;
+ }
+ return min + Math.floor(Math.random() * (max - min + 1));
+ };
+
+ // List of HTML entities for escaping.
+ var entityMap = {
+ escape: {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": ''',
+ '/': '/'
+ }
+ };
+ entityMap.unescape = _.invert(entityMap.escape);
+
+ // Regexes containing the keys and values listed immediately above.
+ var entityRegexes = {
+ escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
+ unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
+ };
+
+ // Functions for escaping and unescaping strings to/from HTML interpolation.
+ _.each(['escape', 'unescape'], function(method) {
+ _[method] = function(string) {
+ if (string == null) return '';
+ return ('' + string).replace(entityRegexes[method], function(match) {
+ return entityMap[method][match];
+ });
+ };
+ });
+
+ // If the value of the named property is a function then invoke it;
+ // otherwise, return it.
+ _.result = function(object, property) {
+ if (object == null) return null;
+ var value = object[property];
+ return _.isFunction(value) ? value.call(object) : value;
+ };
+
+ // Add your own custom functions to the Underscore object.
+ _.mixin = function(obj) {
+ each(_.functions(obj), function(name){
+ var func = _[name] = obj[name];
+ _.prototype[name] = function() {
+ var args = [this._wrapped];
+ push.apply(args, arguments);
+ return result.call(this, func.apply(_, args));
+ };
+ });
+ };
+
+ // Generate a unique integer id (unique within the entire client session).
+ // Useful for temporary DOM ids.
+ var idCounter = 0;
+ _.uniqueId = function(prefix) {
+ var id = ++idCounter + '';
+ return prefix ? prefix + id : id;
+ };
+
+ // By default, Underscore uses ERB-style template delimiters, change the
+ // following template settings to use alternative delimiters.
+ _.templateSettings = {
+ evaluate : /<%([\s\S]+?)%>/g,
+ interpolate : /<%=([\s\S]+?)%>/g,
+ escape : /<%-([\s\S]+?)%>/g
+ };
+
+ // When customizing `templateSettings`, if you don't want to define an
+ // interpolation, evaluation or escaping regex, we need one that is
+ // guaranteed not to match.
+ var noMatch = /(.)^/;
+
+ // Certain characters need to be escaped so that they can be put into a
+ // string literal.
+ var escapes = {
+ "'": "'",
+ '\\': '\\',
+ '\r': 'r',
+ '\n': 'n',
+ '\t': 't',
+ '\u2028': 'u2028',
+ '\u2029': 'u2029'
+ };
+
+ var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
+
+ // JavaScript micro-templating, similar to John Resig's implementation.
+ // Underscore templating handles arbitrary delimiters, preserves whitespace,
+ // and correctly escapes quotes within interpolated code.
+ _.template = function(text, data, settings) {
+ var render;
+ settings = _.defaults({}, settings, _.templateSettings);
+
+ // Combine delimiters into one regular expression via alternation.
+ var matcher = new RegExp([
+ (settings.escape || noMatch).source,
+ (settings.interpolate || noMatch).source,
+ (settings.evaluate || noMatch).source
+ ].join('|') + '|$', 'g');
+
+ // Compile the template source, escaping string literals appropriately.
+ var index = 0;
+ var source = "__p+='";
+ text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
+ source += text.slice(index, offset)
+ .replace(escaper, function(match) { return '\\' + escapes[match]; });
+
+ if (escape) {
+ source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
+ }
+ if (interpolate) {
+ source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
+ }
+ if (evaluate) {
+ source += "';\n" + evaluate + "\n__p+='";
+ }
+ index = offset + match.length;
+ return match;
+ });
+ source += "';\n";
+
+ // If a variable is not specified, place data values in local scope.
+ if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
+
+ source = "var __t,__p='',__j=Array.prototype.join," +
+ "print=function(){__p+=__j.call(arguments,'');};\n" +
+ source + "return __p;\n";
+
+ try {
+ render = new Function(settings.variable || 'obj', '_', source);
+ } catch (e) {
+ e.source = source;
+ throw e;
+ }
+
+ if (data) return render(data, _);
+ var template = function(data) {
+ return render.call(this, data, _);
+ };
+
+ // Provide the compiled function source as a convenience for precompilation.
+ template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
+
+ return template;
+ };
+
+ // Add a "chain" function, which will delegate to the wrapper.
+ _.chain = function(obj) {
+ return _(obj).chain();
+ };
+
+ // OOP
+ // ---------------
+ // If Underscore is called as a function, it returns a wrapped object that
+ // can be used OO-style. This wrapper holds altered versions of all the
+ // underscore functions. Wrapped objects may be chained.
+
+ // Helper function to continue chaining intermediate results.
+ var result = function(obj) {
+ return this._chain ? _(obj).chain() : obj;
+ };
+
+ // Add all of the Underscore functions to the wrapper object.
+ _.mixin(_);
+
+ // Add all mutator Array functions to the wrapper.
+ each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
+ var method = ArrayProto[name];
+ _.prototype[name] = function() {
+ var obj = this._wrapped;
+ method.apply(obj, arguments);
+ if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
+ return result.call(this, obj);
+ };
+ });
+
+ // Add all accessor Array functions to the wrapper.
+ each(['concat', 'join', 'slice'], function(name) {
+ var method = ArrayProto[name];
+ _.prototype[name] = function() {
+ return result.call(this, method.apply(this._wrapped, arguments));
+ };
+ });
+
+ _.extend(_.prototype, {
+
+ // Start chaining a wrapped Underscore object.
+ chain: function() {
+ this._chain = true;
+ return this;
+ },
+
+ // Extracts the result from a wrapped and chained object.
+ value: function() {
+ return this._wrapped;
+ }
+
+ });
+
+}).call(this);
diff --git a/labs/dependency-examples/backbone_marionette_require/index-dev.html b/labs/dependency-examples/backbone_marionette_require/index-dev.html
index 071d5f690e..cf068562bd 100644
--- a/labs/dependency-examples/backbone_marionette_require/index-dev.html
+++ b/labs/dependency-examples/backbone_marionette_require/index-dev.html
@@ -1,38 +1,27 @@
-
+
-
-
- Backbone.Marionette & Requirejs • TodoMVC
-
-
-
+
+
+ Backbone.Marionette & Requirejs • TodoMVC
+
+
-
-
-
-
-
+
+
+
+
diff --git a/labs/dependency-examples/backbone_marionette_require/index.html b/labs/dependency-examples/backbone_marionette_require/index.html
index 5af6634689..dca1cc22a1 100644
--- a/labs/dependency-examples/backbone_marionette_require/index.html
+++ b/labs/dependency-examples/backbone_marionette_require/index.html
@@ -1,38 +1,27 @@
-
+
-
-
- Backbone.Marionette & Requirejs • TodoMVC
-
-
-
+
+
+ Backbone.Marionette & Requirejs • TodoMVC
+
+
-
-
-
-
-
+
+
+
+
diff --git a/labs/dependency-examples/backbone_marionette_require/js/lib/require.js b/labs/dependency-examples/backbone_marionette_require/js/lib/require.js
deleted file mode 100644
index a1a1e4d5d3..0000000000
--- a/labs/dependency-examples/backbone_marionette_require/js/lib/require.js
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- RequireJS 2.0.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
- Available via the MIT or new BSD license.
- see: http://github.com/jrburke/requirejs for details
- */
-var requirejs,require,define;
-(function(Z){function x(b){return J.call(b)==="[object Function]"}function E(b){return J.call(b)==="[object Array]"}function o(b,e){if(b){var f;for(f=0;f-1;f-=1)if(b[f]&&e(b[f],f,b))break}}function y(b,e){for(var f in b)if(b.hasOwnProperty(f)&&e(b[f],f))break}function N(b,e,f,h){e&&y(e,function(e,j){if(f||!F.call(b,j))h&&typeof e!=="string"?(b[j]||(b[j]={}),N(b[j],e,f,h)):b[j]=e});return b}function t(b,e){return function(){return e.apply(b,
- arguments)}}function $(b){if(!b)return b;var e=Z;o(b.split("."),function(b){e=e[b]});return e}function aa(b,e,f){return function(){var h=ga.call(arguments,0),c;if(f&&x(c=h[h.length-1]))c.__requireJsBuild=!0;h.push(e);return b.apply(null,h)}}function ba(b,e,f){o([["toUrl"],["undef"],["defined","requireDefined"],["specified","requireSpecified"]],function(h){var c=h[1]||h[0];b[h[0]]=e?aa(e[c],f):function(){var b=z[O];return b[c].apply(b,arguments)}})}function G(b,e,f,h){e=Error(e+"\nhttp://requirejs.org/docs/errors.html#"+
- b);e.requireType=b;e.requireModules=h;if(f)e.originalError=f;return e}function ha(){if(H&&H.readyState==="interactive")return H;M(document.getElementsByTagName("script"),function(b){if(b.readyState==="interactive")return H=b});return H}var j,p,u,B,s,C,H,I,ca,da,ia=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ja=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,ea=/\.js$/,ka=/^\.\//;p=Object.prototype;var J=p.toString,F=p.hasOwnProperty;p=Array.prototype;var ga=p.slice,la=p.splice,w=!!(typeof window!==
- "undefined"&&navigator&&document),fa=!w&&typeof importScripts!=="undefined",ma=w&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,O="_",S=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",z={},r={},P=[],K=!1;if(typeof define==="undefined"){if(typeof requirejs!=="undefined"){if(x(requirejs))return;r=requirejs;requirejs=void 0}typeof require!=="undefined"&&!x(require)&&(r=require,require=void 0);j=requirejs=function(b,e,f,h){var c,o=O;!E(b)&&typeof b!=="string"&&
-(c=b,E(e)?(b=e,e=f,f=h):b=[]);if(c&&c.context)o=c.context;(h=z[o])||(h=z[o]=j.s.newContext(o));c&&h.configure(c);return h.require(b,e,f)};j.config=function(b){return j(b)};require||(require=j);j.version="2.0.6";j.jsExtRegExp=/^\/|:|\?|\.js$/;j.isBrowser=w;p=j.s={contexts:z,newContext:function(b){function e(a,d,k){var l,b,i,v,e,c,f,g=d&&d.split("/");l=g;var h=m.map,j=h&&h["*"];if(a&&a.charAt(0)===".")if(d){l=m.pkgs[d]?g=[d]:g.slice(0,g.length-1);d=a=l.concat(a.split("/"));for(l=0;d[l];l+=1)if(b=d[l],
- b===".")d.splice(l,1),l-=1;else if(b==="..")if(l===1&&(d[2]===".."||d[0]===".."))break;else l>0&&(d.splice(l-1,2),l-=2);l=m.pkgs[d=a[0]];a=a.join("/");l&&a===d+"/"+l.main&&(a=d)}else a.indexOf("./")===0&&(a=a.substring(2));if(k&&(g||j)&&h){d=a.split("/");for(l=d.length;l>0;l-=1){i=d.slice(0,l).join("/");if(g)for(b=g.length;b>0;b-=1)if(k=h[g.slice(0,b).join("/")])if(k=k[i]){v=k;e=l;break}if(v)break;!c&&j&&j[i]&&(c=j[i],f=l)}!v&&c&&(v=c,e=f);v&&(d.splice(0,e,v),a=d.join("/"))}return a}function f(a){w&&
-o(document.getElementsByTagName("script"),function(d){if(d.getAttribute("data-requiremodule")===a&&d.getAttribute("data-requirecontext")===g.contextName)return d.parentNode.removeChild(d),!0})}function h(a){var d=m.paths[a];if(d&&E(d)&&d.length>1)return f(a),d.shift(),g.undef(a),g.require([a]),!0}function c(a,d,k,l){var b,i,v=a?a.indexOf("!"):-1,c=null,f=d?d.name:null,h=a,j=!0,m="";a||(j=!1,a="_@r"+(M+=1));v!==-1&&(c=a.substring(0,v),a=a.substring(v+1,a.length));c&&(c=e(c,f,l),i=q[c]);a&&(c?m=i&&
- i.normalize?i.normalize(a,function(a){return e(a,f,l)}):e(a,f,l):(m=e(a,f,l),b=g.nameToUrl(m)));a=c&&!i&&!k?"_unnormalized"+(O+=1):"";return{prefix:c,name:m,parentMap:d,unnormalized:!!a,url:b,originalName:h,isDefine:j,id:(c?c+"!"+m:m)+a}}function p(a){var d=a.id,k=n[d];k||(k=n[d]=new g.Module(a));return k}function r(a,d,k){var b=a.id,c=n[b];if(F.call(q,b)&&(!c||c.defineEmitComplete))d==="defined"&&k(q[b]);else p(a).on(d,k)}function A(a,d){var k=a.requireModules,b=!1;if(d)d(a);else if(o(k,function(d){if(d=
- n[d])d.error=a,d.events.error&&(b=!0,d.emit("error",a))}),!b)j.onError(a)}function s(){P.length&&(la.apply(D,[D.length-1,0].concat(P)),P=[])}function u(a,d,k){a=a&&a.map;d=aa(k||g.require,a,d);ba(d,g,a);d.isBrowser=w;return d}function z(a){delete n[a];o(L,function(d,k){if(d.map.id===a)return L.splice(k,1),d.defined||(g.waitCount-=1),!0})}function B(a,d,k){var b=a.map.id,c=a.depMaps,i;if(a.inited){if(d[b])return a;d[b]=!0;o(c,function(a){var a=a.id,b=n[a];return!b||k[a]||!b.inited||!b.enabled?void 0:
- i=B(b,d,k)});k[b]=!0;return i}}function C(a,d,b){var l=a.map.id,c=a.depMaps;if(a.inited&&a.map.isDefine){if(d[l])return q[l];d[l]=a;o(c,function(i){var i=i.id,c=n[i];!Q[i]&&c&&(!c.inited||!c.enabled?b[l]=!0:(c=C(c,d,b),b[i]||a.defineDepById(i,c)))});a.check(!0);return q[l]}}function I(a){a.check()}function T(){var a,d,b,l,c=(b=m.waitSeconds*1E3)&&g.startTime+b<(new Date).getTime(),i=[],e=!1,j=!0;if(!U){U=!0;y(n,function(b){a=b.map;d=a.id;if(b.enabled&&!b.error)if(!b.inited&&c)h(d)?e=l=!0:(i.push(d),
- f(d));else if(!b.inited&&b.fetched&&a.isDefine&&(e=!0,!a.prefix))return j=!1});if(c&&i.length)return b=G("timeout","Load timeout for modules: "+i,null,i),b.contextName=g.contextName,A(b);j&&(o(L,function(a){if(!a.defined){var a=B(a,{},{}),d={};a&&(C(a,d,{}),y(d,I))}}),y(n,I));if((!c||l)&&e)if((w||fa)&&!V)V=setTimeout(function(){V=0;T()},50);U=!1}}function W(a){p(c(a[0],null,!0)).init(a[1],a[2])}function J(a){var a=a.currentTarget||a.srcElement,d=g.onScriptLoad;a.detachEvent&&!S?a.detachEvent("onreadystatechange",
- d):a.removeEventListener("load",d,!1);d=g.onScriptError;a.detachEvent&&!S||a.removeEventListener("error",d,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}var U,X,g,Q,V,m={waitSeconds:7,baseUrl:"./",paths:{},pkgs:{},shim:{}},n={},Y={},D=[],q={},R={},M=1,O=1,L=[];Q={require:function(a){return u(a)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports=q[a.map.id]={}},module:function(a){return a.module={id:a.map.id,uri:a.map.url,config:function(){return m.config&&m.config[a.map.id]||
-{}},exports:q[a.map.id]}}};X=function(a){this.events=Y[a.id]||{};this.map=a;this.shim=m.shim[a.id];this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};X.prototype={init:function(a,d,b,c){c=c||{};if(!this.inited){this.factory=d;if(b)this.on("error",b);else this.events.error&&(b=t(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.depMaps.rjsSkipMap=a.rjsSkipMap;this.errback=b;this.inited=!0;this.ignore=c.ignore;c.enabled||this.enabled?this.enable():
- this.check()}},defineDepById:function(a,d){var b;o(this.depMaps,function(d,c){if(d.id===a)return b=c,!0});return this.defineDep(b,d)},defineDep:function(a,d){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=d)},fetch:function(){if(!this.fetched){this.fetched=!0;g.startTime=(new Date).getTime();var a=this.map;if(this.shim)u(this,!0)(this.shim.deps||[],t(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},
- load:function(){var a=this.map.url;R[a]||(R[a]=!0,g.load(this.map.id,a))},check:function(a){if(this.enabled&&!this.enabling){var d,b,c=this.map.id;b=this.depExports;var e=this.exports,i=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){this.defining=!0;if(this.depCount<1&&!this.defined){if(x(i)){if(this.events.error)try{e=g.execCb(c,i,b,e)}catch(f){d=f}else e=g.execCb(c,i,b,e);if(this.map.isDefine)if((b=this.module)&&b.exports!==void 0&&b.exports!==this.exports)e=
- b.exports;else if(e===void 0&&this.usingExports)e=this.exports;if(d)return d.requireMap=this.map,d.requireModules=[this.map.id],d.requireType="define",A(this.error=d)}else e=i;this.exports=e;if(this.map.isDefine&&!this.ignore&&(q[c]=e,j.onResourceLoad))j.onResourceLoad(g,this.map,this.depMaps);delete n[c];this.defined=!0;g.waitCount-=1;g.waitCount===0&&(L=[])}this.defining=!1;if(!a&&this.defined&&!this.defineEmitted)this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0}}else this.fetch()}},
- callPlugin:function(){var a=this.map,d=a.id,b=c(a.prefix,null,!1,!0);r(b,"defined",t(this,function(b){var k;k=this.map.name;var i=this.map.parentMap?this.map.parentMap.name:null;if(this.map.unnormalized){if(b.normalize&&(k=b.normalize(k,function(a){return e(a,i,!0)})||""),b=c(a.prefix+"!"+k,this.map.parentMap,!1,!0),r(b,"defined",t(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),b=n[b.id]){if(this.events.error)b.on("error",t(this,function(a){this.emit("error",a)}));
- b.enable()}}else k=t(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),k.error=t(this,function(a){this.inited=!0;this.error=a;a.requireModules=[d];y(n,function(a){a.map.id.indexOf(d+"_unnormalized")===0&&z(a.map.id)});A(a)}),k.fromText=function(a,b){var d=K;d&&(K=!1);p(c(a));j.exec(b);d&&(K=!0);g.completeLoad(a)},b.load(a.name,u(a.parentMap,!0,function(a,b,d){a.rjsSkipMap=!0;return g.require(a,b,d)}),k,m)}));g.enable(b,this);this.pluginMaps[b.id]=b},enable:function(){this.enabled=
- !0;if(!this.waitPushed)L.push(this),g.waitCount+=1,this.waitPushed=!0;this.enabling=!0;o(this.depMaps,t(this,function(a,b){var k,e;if(typeof a==="string"){a=c(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.depMaps.rjsSkipMap);this.depMaps[b]=a;if(k=Q[a.id]){this.depExports[b]=k(this);return}this.depCount+=1;r(a,"defined",t(this,function(a){this.defineDep(b,a);this.check()}));this.errback&&r(a,"error",this.errback)}k=a.id;e=n[k];!Q[k]&&e&&!e.enabled&&g.enable(a,this)}));y(this.pluginMaps,
- t(this,function(a){var b=n[a.id];b&&!b.enabled&&g.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){o(this.events[a],function(a){a(b)});a==="error"&&delete this.events[a]}};return g={config:m,contextName:b,registry:n,defined:q,urlFetched:R,waitCount:0,defQueue:D,Module:X,makeModuleMap:c,configure:function(a){a.baseUrl&&a.baseUrl.charAt(a.baseUrl.length-1)!=="/"&&(a.baseUrl+="/");var b=m.pkgs,e=m.shim,f=m.paths,
- j=m.map;N(m,a,!0);m.paths=N(f,a.paths,!0);if(a.map)m.map=N(j||{},a.map,!0,!0);if(a.shim)y(a.shim,function(a,b){E(a)&&(a={deps:a});if(a.exports&&!a.exports.__buildReady)a.exports=g.makeShimExports(a.exports);e[b]=a}),m.shim=e;if(a.packages)o(a.packages,function(a){a=typeof a==="string"?{name:a}:a;b[a.name]={name:a.name,location:a.location||a.name,main:(a.main||"main").replace(ka,"").replace(ea,"")}}),m.pkgs=b;y(n,function(a,b){if(!a.inited&&!a.map.unnormalized)a.map=c(b)});if(a.deps||a.callback)g.require(a.deps||
- [],a.callback)},makeShimExports:function(a){var b;return typeof a==="string"?(b=function(){return $(a)},b.exports=a,b):function(){return a.apply(Z,arguments)}},requireDefined:function(a,b){var e=c(a,b,!1,!0).id;return F.call(q,e)},requireSpecified:function(a,b){a=c(a,b,!1,!0).id;return F.call(q,a)||F.call(n,a)},require:function(a,d,e,f){var h;if(typeof a==="string"){if(x(d))return A(G("requireargs","Invalid require call"),e);if(j.get)return j.get(g,a,d);a=c(a,d,!1,!0);a=a.id;return!F.call(q,a)?A(G("notloaded",
- 'Module name "'+a+'" has not been loaded yet for context: '+b)):q[a]}e&&!x(e)&&(f=e,e=void 0);d&&!x(d)&&(f=d,d=void 0);for(s();D.length;)if(h=D.shift(),h[0]===null)return A(G("mismatch","Mismatched anonymous define() module: "+h[h.length-1]));else W(h);p(c(null,f)).init(a,d,e,{enabled:!0});T();return g.require},undef:function(a){s();var b=c(a,null,!0),e=n[a];delete q[a];delete R[b.url];delete Y[a];if(e){if(e.events.defined)Y[a]=e.events;z(a)}},enable:function(a){n[a.id]&&p(a).enable()},completeLoad:function(a){var b,
- c,e=m.shim[a]||{},f=e.exports&&e.exports.exports;for(s();D.length;){c=D.shift();if(c[0]===null){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);W(c)}c=n[a];if(!b&&!q[a]&&c&&!c.inited)if(m.enforceDefine&&(!f||!$(f)))if(h(a))return;else return A(G("nodefine","No define call for "+a,null,[a]));else W([a,e.deps||[],e.exports]);T()},toUrl:function(a,b){var c=a.lastIndexOf("."),f=null;c!==-1&&(f=a.substring(c,a.length),a=a.substring(0,c));return g.nameToUrl(e(a,b&&b.id,!0),f)},nameToUrl:function(a,b){var c,
- e,f,i,h,g;if(j.jsExtRegExp.test(a))i=a+(b||"");else{c=m.paths;e=m.pkgs;i=a.split("/");for(h=i.length;h>0;h-=1)if(g=i.slice(0,h).join("/"),f=e[g],g=c[g]){E(g)&&(g=g[0]);i.splice(0,h,g);break}else if(f){c=a===f.name?f.location+"/"+f.main:f.location;i.splice(0,h,c);break}i=i.join("/");i+=b||(/\?/.test(i)?"":".js");i=(i.charAt(0)==="/"||i.match(/^[\w\+\.\-]+:/)?"":m.baseUrl)+i}return m.urlArgs?i+((i.indexOf("?")===-1?"?":"&")+m.urlArgs):i},load:function(a,b){j.load(g,a,b)},execCb:function(a,b,c,e){return b.apply(e,
- c)},onScriptLoad:function(a){if(a.type==="load"||ma.test((a.currentTarget||a.srcElement).readyState))H=null,a=J(a),g.completeLoad(a.id)},onScriptError:function(a){var b=J(a);if(!h(b.id))return A(G("scripterror","Script error",a,[b.id]))}}}};j({});ba(j);if(w&&(u=p.head=document.getElementsByTagName("head")[0],B=document.getElementsByTagName("base")[0]))u=p.head=B.parentNode;j.onError=function(b){throw b;};j.load=function(b,e,f){var h=b&&b.config||{},c;if(w)return c=h.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml",
- "html:script"):document.createElement("script"),c.type=h.scriptType||"text/javascript",c.charset="utf-8",c.async=!0,c.setAttribute("data-requirecontext",b.contextName),c.setAttribute("data-requiremodule",e),c.attachEvent&&!(c.attachEvent.toString&&c.attachEvent.toString().indexOf("[native code")<0)&&!S?(K=!0,c.attachEvent("onreadystatechange",b.onScriptLoad)):(c.addEventListener("load",b.onScriptLoad,!1),c.addEventListener("error",b.onScriptError,!1)),c.src=f,I=c,B?u.insertBefore(c,B):u.appendChild(c),
- I=null,c;else fa&&(importScripts(f),b.completeLoad(e))};w&&M(document.getElementsByTagName("script"),function(b){if(!u)u=b.parentNode;if(s=b.getAttribute("data-main")){if(!r.baseUrl)C=s.split("/"),ca=C.pop(),da=C.length?C.join("/")+"/":"./",r.baseUrl=da,s=ca;s=s.replace(ea,"");r.deps=r.deps?r.deps.concat(s):[s];return!0}});define=function(b,e,f){var h,c;typeof b!=="string"&&(f=e,e=b,b=null);E(e)||(f=e,e=[]);!e.length&&x(f)&&f.length&&(f.toString().replace(ia,"").replace(ja,function(b,c){e.push(c)}),
- e=(f.length===1?["require"]:["require","exports","module"]).concat(e));if(K&&(h=I||ha()))b||(b=h.getAttribute("data-requiremodule")),c=z[h.getAttribute("data-requirecontext")];(c?c.defQueue:P).push([b,e,f])};define.amd={jQuery:!0};j.exec=function(b){return eval(b)};j(r)}})(this);
diff --git a/labs/dependency-examples/backbone_marionette_require/js/main.js b/labs/dependency-examples/backbone_marionette_require/js/main.js
index 6442e5edd4..8988f1ced0 100644
--- a/labs/dependency-examples/backbone_marionette_require/js/main.js
+++ b/labs/dependency-examples/backbone_marionette_require/js/main.js
@@ -1,9 +1,9 @@
require.config({
paths : {
- underscore : 'lib/underscore',
+ underscore : '../bower_components/underscore/underscore',
backbone : 'lib/backbone',
marionette : 'lib/backbone.marionette',
- jquery : '../../../../assets/jquery.min',
+ jquery : '../bower_components/jquery/jquery',
tpl : 'lib/tpl'
},
shim : {
diff --git a/labs/dependency-examples/backbone_marionette_require/r.js b/labs/dependency-examples/backbone_marionette_require/r.js
deleted file mode 100644
index 15fe091410..0000000000
--- a/labs/dependency-examples/backbone_marionette_require/r.js
+++ /dev/null
@@ -1,15483 +0,0 @@
-/**
- * @license r.js 2.0.6+ Thu, 23 Aug 2012 17:16:22 GMT Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
-/*
- * This is a bootstrap script to allow running RequireJS in the command line
- * in either a Java/Rhino or Node environment. It is modified by the top-level
- * dist.js file to inject other files to completely enable this file. It is
- * the shell of the r.js file.
- */
-
-/*jslint evil: true, nomen: true, sloppy: true */
-/*global readFile: true, process: false, Packages: false, print: false,
- console: false, java: false, module: false, requirejsVars */
-
-var requirejs, require, define;
-(function (console, args, readFileFunc) {
-
- var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire,
- nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode,
- version = '2.0.6+ Thu, 23 Aug 2012 17:16:22 GMT',
- jsSuffixRegExp = /\.js$/,
- commandOption = '',
- useLibLoaded = {},
- //Used by jslib/rhino/args.js
- rhinoArgs = args,
- readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null;
-
- function showHelp() {
- console.log('See https://github.com/jrburke/r.js for usage.');
- }
-
- if (typeof Packages !== 'undefined') {
- env = 'rhino';
-
- fileName = args[0];
-
- if (fileName && fileName.indexOf('-') === 0) {
- commandOption = fileName.substring(1);
- fileName = args[1];
- }
-
- //Set up execution context.
- rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext();
-
- exec = function (string, name) {
- return rhinoContext.evaluateString(this, string, name, 0, null);
- };
-
- exists = function (fileName) {
- return (new java.io.File(fileName)).exists();
- };
-
- //Define a console.log for easier logging. Don't
- //get fancy though.
- if (typeof console === 'undefined') {
- console = {
- log: function () {
- print.apply(undefined, arguments);
- }
- };
- }
- } else if (typeof process !== 'undefined') {
- env = 'node';
-
- //Get the fs module via Node's require before it
- //gets replaced. Used in require/node.js
- fs = require('fs');
- vm = require('vm');
- path = require('path');
- //In Node 0.7+ existsSync is on fs.
- existsForNode = fs.existsSync || path.existsSync;
-
- nodeRequire = require;
- nodeDefine = define;
- reqMain = require.main;
-
- //Temporarily hide require and define to allow require.js to define
- //them.
- require = undefined;
- define = undefined;
-
- readFile = function (path) {
- return fs.readFileSync(path, 'utf8');
- };
-
- exec = function (string, name) {
- return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string),
- name ? fs.realpathSync(name) : '');
- };
-
- exists = function (fileName) {
- return existsForNode(fileName);
- };
-
-
- fileName = process.argv[2];
-
- if (fileName && fileName.indexOf('-') === 0) {
- commandOption = fileName.substring(1);
- fileName = process.argv[3];
- }
- }
-
- /** vim: et:ts=4:sw=4:sts=4
- * @license RequireJS 2.0.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
- //Not using strict: uneven strict support in browsers, #392, and causes
- //problems with requirejs.exec()/transpiler plugins that may not be strict.
- /*jslint regexp: true, nomen: true, sloppy: true */
- /*global window, navigator, document, importScripts, jQuery, setTimeout, opera */
-
-
- (function (global) {
- var req, s, head, baseElement, dataMain, src,
- interactiveScript, currentlyAddingScript, mainScript, subPath,
- version = '2.0.6',
- commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
- cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
- jsSuffixRegExp = /\.js$/,
- currDirRegExp = /^\.\//,
- op = Object.prototype,
- ostring = op.toString,
- hasOwn = op.hasOwnProperty,
- ap = Array.prototype,
- aps = ap.slice,
- apsp = ap.splice,
- isBrowser = !!(typeof window !== 'undefined' && navigator && document),
- isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
- //PS3 indicates loaded and complete, but need to wait for complete
- //specifically. Sequence is 'loading', 'loaded', execution,
- // then 'complete'. The UA check is unfortunate, but not sure how
- //to feature test w/o causing perf issues.
- readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
- /^complete$/ : /^(complete|loaded)$/,
- defContextName = '_',
- //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
- isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
- contexts = {},
- cfg = {},
- globalDefQueue = [],
- useInteractive = false;
-
- function isFunction(it) {
- return ostring.call(it) === '[object Function]';
- }
-
- function isArray(it) {
- return ostring.call(it) === '[object Array]';
- }
-
- /**
- * Helper function for iterating over an array. If the func returns
- * a true value, it will break out of the loop.
- */
- function each(ary, func) {
- if (ary) {
- var i;
- for (i = 0; i < ary.length; i += 1) {
- if (ary[i] && func(ary[i], i, ary)) {
- break;
- }
- }
- }
- }
-
- /**
- * Helper function for iterating over an array backwards. If the func
- * returns a true value, it will break out of the loop.
- */
- function eachReverse(ary, func) {
- if (ary) {
- var i;
- for (i = ary.length - 1; i > -1; i -= 1) {
- if (ary[i] && func(ary[i], i, ary)) {
- break;
- }
- }
- }
- }
-
- function hasProp(obj, prop) {
- return hasOwn.call(obj, prop);
- }
-
- /**
- * Cycles over properties in an object and calls a function for each
- * property value. If the function returns a truthy value, then the
- * iteration is stopped.
- */
- function eachProp(obj, func) {
- var prop;
- for (prop in obj) {
- if (obj.hasOwnProperty(prop)) {
- if (func(obj[prop], prop)) {
- break;
- }
- }
- }
- }
-
- /**
- * Simple function to mix in properties from source into target,
- * but only if target does not already have a property of the same name.
- * This is not robust in IE for transferring methods that match
- * Object.prototype names, but the uses of mixin here seem unlikely to
- * trigger a problem related to that.
- */
- function mixin(target, source, force, deepStringMixin) {
- if (source) {
- eachProp(source, function (value, prop) {
- if (force || !hasProp(target, prop)) {
- if (deepStringMixin && typeof value !== 'string') {
- if (!target[prop]) {
- target[prop] = {};
- }
- mixin(target[prop], value, force, deepStringMixin);
- } else {
- target[prop] = value;
- }
- }
- });
- }
- return target;
- }
-
- //Similar to Function.prototype.bind, but the 'this' object is specified
- //first, since it is easier to read/figure out what 'this' will be.
- function bind(obj, fn) {
- return function () {
- return fn.apply(obj, arguments);
- };
- }
-
- function scripts() {
- return document.getElementsByTagName('script');
- }
-
- //Allow getting a global that expressed in
- //dot notation, like 'a.b.c'.
- function getGlobal(value) {
- if (!value) {
- return value;
- }
- var g = global;
- each(value.split('.'), function (part) {
- g = g[part];
- });
- return g;
- }
-
- function makeContextModuleFunc(func, relMap, enableBuildCallback) {
- return function () {
- //A version of a require function that passes a moduleName
- //value for items that may need to
- //look up paths relative to the moduleName
- var args = aps.call(arguments, 0), lastArg;
- if (enableBuildCallback &&
- isFunction((lastArg = args[args.length - 1]))) {
- lastArg.__requireJsBuild = true;
- }
- args.push(relMap);
- return func.apply(null, args);
- };
- }
-
- function addRequireMethods(req, context, relMap) {
- each([
- ['toUrl'],
- ['undef'],
- ['defined', 'requireDefined'],
- ['specified', 'requireSpecified']
- ], function (item) {
- var prop = item[1] || item[0];
- req[item[0]] = context ? makeContextModuleFunc(context[prop], relMap) :
- //If no context, then use default context. Reference from
- //contexts instead of early binding to default context, so
- //that during builds, the latest instance of the default
- //context with its config gets used.
- function () {
- var ctx = contexts[defContextName];
- return ctx[prop].apply(ctx, arguments);
- };
- });
- }
-
- /**
- * Constructs an error with a pointer to an URL with more information.
- * @param {String} id the error ID that maps to an ID on a web page.
- * @param {String} message human readable error.
- * @param {Error} [err] the original error, if there is one.
- *
- * @returns {Error}
- */
- function makeError(id, msg, err, requireModules) {
- var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
- e.requireType = id;
- e.requireModules = requireModules;
- if (err) {
- e.originalError = err;
- }
- return e;
- }
-
- if (typeof define !== 'undefined') {
- //If a define is already in play via another AMD loader,
- //do not overwrite.
- return;
- }
-
- if (typeof requirejs !== 'undefined') {
- if (isFunction(requirejs)) {
- //Do not overwrite and existing requirejs instance.
- return;
- }
- cfg = requirejs;
- requirejs = undefined;
- }
-
- //Allow for a require config object
- if (typeof require !== 'undefined' && !isFunction(require)) {
- //assume it is a config object.
- cfg = require;
- require = undefined;
- }
-
- function newContext(contextName) {
- var inCheckLoaded, Module, context, handlers,
- checkLoadedTimeoutId,
- config = {
- waitSeconds: 7,
- baseUrl: './',
- paths: {},
- pkgs: {},
- shim: {}
- },
- registry = {},
- undefEvents = {},
- defQueue = [],
- defined = {},
- urlFetched = {},
- requireCounter = 1,
- unnormalizedCounter = 1,
- //Used to track the order in which modules
- //should be executed, by the order they
- //load. Important for consistent cycle resolution
- //behavior.
- waitAry = [];
-
- /**
- * Trims the . and .. from an array of path segments.
- * It will keep a leading path segment if a .. will become
- * the first path segment, to help with module name lookups,
- * which act like paths, but can be remapped. But the end result,
- * all paths that use this function should look normalized.
- * NOTE: this method MODIFIES the input array.
- * @param {Array} ary the array of path segments.
- */
- function trimDots(ary) {
- var i, part;
- for (i = 0; ary[i]; i += 1) {
- part = ary[i];
- if (part === '.') {
- ary.splice(i, 1);
- i -= 1;
- } else if (part === '..') {
- if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
- //End of the line. Keep at least one non-dot
- //path segment at the front so it can be mapped
- //correctly to disk. Otherwise, there is likely
- //no path mapping for a path starting with '..'.
- //This can still fail, but catches the most reasonable
- //uses of ..
- break;
- } else if (i > 0) {
- ary.splice(i - 1, 2);
- i -= 2;
- }
- }
- }
- }
-
- /**
- * Given a relative module name, like ./something, normalize it to
- * a real name that can be mapped to a path.
- * @param {String} name the relative name
- * @param {String} baseName a real name that the name arg is relative
- * to.
- * @param {Boolean} applyMap apply the map config to the value. Should
- * only be done if this normalization is for a dependency ID.
- * @returns {String} normalized name
- */
- function normalize(name, baseName, applyMap) {
- var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
- foundMap, foundI, foundStarMap, starI,
- baseParts = baseName && baseName.split('/'),
- normalizedBaseParts = baseParts,
- map = config.map,
- starMap = map && map['*'];
-
- //Adjust any relative paths.
- if (name && name.charAt(0) === '.') {
- //If have a base name, try to normalize against it,
- //otherwise, assume it is a top-level require that will
- //be relative to baseUrl in the end.
- if (baseName) {
- if (config.pkgs[baseName]) {
- //If the baseName is a package name, then just treat it as one
- //name to concat the name with.
- normalizedBaseParts = baseParts = [baseName];
- } else {
- //Convert baseName to array, and lop off the last part,
- //so that . matches that 'directory' and not name of the baseName's
- //module. For instance, baseName of 'one/two/three', maps to
- //'one/two/three.js', but we want the directory, 'one/two' for
- //this normalization.
- normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
- }
-
- name = normalizedBaseParts.concat(name.split('/'));
- trimDots(name);
-
- //Some use of packages may use a . path to reference the
- //'main' module name, so normalize for that.
- pkgConfig = config.pkgs[(pkgName = name[0])];
- name = name.join('/');
- if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
- name = pkgName;
- }
- } else if (name.indexOf('./') === 0) {
- // No baseName, so this is ID is resolved relative
- // to baseUrl, pull off the leading dot.
- name = name.substring(2);
- }
- }
-
- //Apply map config if available.
- if (applyMap && (baseParts || starMap) && map) {
- nameParts = name.split('/');
-
- for (i = nameParts.length; i > 0; i -= 1) {
- nameSegment = nameParts.slice(0, i).join('/');
-
- if (baseParts) {
- //Find the longest baseName segment match in the config.
- //So, do joins on the biggest to smallest lengths of baseParts.
- for (j = baseParts.length; j > 0; j -= 1) {
- mapValue = map[baseParts.slice(0, j).join('/')];
-
- //baseName segment has config, find if it has one for
- //this name.
- if (mapValue) {
- mapValue = mapValue[nameSegment];
- if (mapValue) {
- //Match, update name to the new value.
- foundMap = mapValue;
- foundI = i;
- break;
- }
- }
- }
- }
-
- if (foundMap) {
- break;
- }
-
- //Check for a star map match, but just hold on to it,
- //if there is a shorter segment match later in a matching
- //config, then favor over this star map.
- if (!foundStarMap && starMap && starMap[nameSegment]) {
- foundStarMap = starMap[nameSegment];
- starI = i;
- }
- }
-
- if (!foundMap && foundStarMap) {
- foundMap = foundStarMap;
- foundI = starI;
- }
-
- if (foundMap) {
- nameParts.splice(0, foundI, foundMap);
- name = nameParts.join('/');
- }
- }
-
- return name;
- }
-
- function removeScript(name) {
- if (isBrowser) {
- each(scripts(), function (scriptNode) {
- if (scriptNode.getAttribute('data-requiremodule') === name &&
- scriptNode.getAttribute('data-requirecontext') === context.contextName) {
- scriptNode.parentNode.removeChild(scriptNode);
- return true;
- }
- });
- }
- }
-
- function hasPathFallback(id) {
- var pathConfig = config.paths[id];
- if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
- removeScript(id);
- //Pop off the first array value, since it failed, and
- //retry
- pathConfig.shift();
- context.undef(id);
- context.require([id]);
- return true;
- }
- }
-
- /**
- * Creates a module mapping that includes plugin prefix, module
- * name, and path. If parentModuleMap is provided it will
- * also normalize the name via require.normalize()
- *
- * @param {String} name the module name
- * @param {String} [parentModuleMap] parent module map
- * for the module name, used to resolve relative names.
- * @param {Boolean} isNormalized: is the ID already normalized.
- * This is true if this call is done for a define() module ID.
- * @param {Boolean} applyMap: apply the map config to the ID.
- * Should only be true if this map is for a dependency.
- *
- * @returns {Object}
- */
- function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
- var url, pluginModule, suffix,
- index = name ? name.indexOf('!') : -1,
- prefix = null,
- parentName = parentModuleMap ? parentModuleMap.name : null,
- originalName = name,
- isDefine = true,
- normalizedName = '';
-
- //If no name, then it means it is a require call, generate an
- //internal name.
- if (!name) {
- isDefine = false;
- name = '_@r' + (requireCounter += 1);
- }
-
- if (index !== -1) {
- prefix = name.substring(0, index);
- name = name.substring(index + 1, name.length);
- }
-
- if (prefix) {
- prefix = normalize(prefix, parentName, applyMap);
- pluginModule = defined[prefix];
- }
-
- //Account for relative paths if there is a base name.
- if (name) {
- if (prefix) {
- if (pluginModule && pluginModule.normalize) {
- //Plugin is loaded, use its normalize method.
- normalizedName = pluginModule.normalize(name, function (name) {
- return normalize(name, parentName, applyMap);
- });
- } else {
- normalizedName = normalize(name, parentName, applyMap);
- }
- } else {
- //A regular module.
- normalizedName = normalize(name, parentName, applyMap);
- url = context.nameToUrl(normalizedName);
- }
- }
-
- //If the id is a plugin id that cannot be determined if it needs
- //normalization, stamp it with a unique ID so two matching relative
- //ids that may conflict can be separate.
- suffix = prefix && !pluginModule && !isNormalized ?
- '_unnormalized' + (unnormalizedCounter += 1) :
- '';
-
- return {
- prefix: prefix,
- name: normalizedName,
- parentMap: parentModuleMap,
- unnormalized: !!suffix,
- url: url,
- originalName: originalName,
- isDefine: isDefine,
- id: (prefix ?
- prefix + '!' + normalizedName :
- normalizedName) + suffix
- };
- }
-
- function getModule(depMap) {
- var id = depMap.id,
- mod = registry[id];
-
- if (!mod) {
- mod = registry[id] = new context.Module(depMap);
- }
-
- return mod;
- }
-
- function on(depMap, name, fn) {
- var id = depMap.id,
- mod = registry[id];
-
- if (hasProp(defined, id) &&
- (!mod || mod.defineEmitComplete)) {
- if (name === 'defined') {
- fn(defined[id]);
- }
- } else {
- getModule(depMap).on(name, fn);
- }
- }
-
- function onError(err, errback) {
- var ids = err.requireModules,
- notified = false;
-
- if (errback) {
- errback(err);
- } else {
- each(ids, function (id) {
- var mod = registry[id];
- if (mod) {
- //Set error on module, so it skips timeout checks.
- mod.error = err;
- if (mod.events.error) {
- notified = true;
- mod.emit('error', err);
- }
- }
- });
-
- if (!notified) {
- req.onError(err);
- }
- }
- }
-
- /**
- * Internal method to transfer globalQueue items to this context's
- * defQueue.
- */
- function takeGlobalQueue() {
- //Push all the globalDefQueue items into the context's defQueue
- if (globalDefQueue.length) {
- //Array splice in the values since the context code has a
- //local var ref to defQueue, so cannot just reassign the one
- //on context.
- apsp.apply(defQueue,
- [defQueue.length - 1, 0].concat(globalDefQueue));
- globalDefQueue = [];
- }
- }
-
- /**
- * Helper function that creates a require function object to give to
- * modules that ask for it as a dependency. It needs to be specific
- * per module because of the implication of path mappings that may
- * need to be relative to the module name.
- */
- function makeRequire(mod, enableBuildCallback, altRequire) {
- var relMap = mod && mod.map,
- modRequire = makeContextModuleFunc(altRequire || context.require,
- relMap,
- enableBuildCallback);
-
- addRequireMethods(modRequire, context, relMap);
- modRequire.isBrowser = isBrowser;
-
- return modRequire;
- }
-
- handlers = {
- 'require': function (mod) {
- return makeRequire(mod);
- },
- 'exports': function (mod) {
- mod.usingExports = true;
- if (mod.map.isDefine) {
- return (mod.exports = defined[mod.map.id] = {});
- }
- },
- 'module': function (mod) {
- return (mod.module = {
- id: mod.map.id,
- uri: mod.map.url,
- config: function () {
- return (config.config && config.config[mod.map.id]) || {};
- },
- exports: defined[mod.map.id]
- });
- }
- };
-
- function removeWaiting(id) {
- //Clean up machinery used for waiting modules.
- delete registry[id];
-
- each(waitAry, function (mod, i) {
- if (mod.map.id === id) {
- waitAry.splice(i, 1);
- if (!mod.defined) {
- context.waitCount -= 1;
- }
- return true;
- }
- });
- }
-
- function findCycle(mod, traced, processed) {
- var id = mod.map.id,
- depArray = mod.depMaps,
- foundModule;
-
- //Do not bother with unitialized modules or not yet enabled
- //modules.
- if (!mod.inited) {
- return;
- }
-
- //Found the cycle.
- if (traced[id]) {
- return mod;
- }
-
- traced[id] = true;
-
- //Trace through the dependencies.
- each(depArray, function (depMap) {
- var depId = depMap.id,
- depMod = registry[depId];
-
- if (!depMod || processed[depId] ||
- !depMod.inited || !depMod.enabled) {
- return;
- }
-
- return (foundModule = findCycle(depMod, traced, processed));
- });
-
- processed[id] = true;
-
- return foundModule;
- }
-
- function forceExec(mod, traced, uninited) {
- var id = mod.map.id,
- depArray = mod.depMaps;
-
- if (!mod.inited || !mod.map.isDefine) {
- return;
- }
-
- if (traced[id]) {
- return defined[id];
- }
-
- traced[id] = mod;
-
- each(depArray, function (depMap) {
- var depId = depMap.id,
- depMod = registry[depId],
- value;
-
- if (handlers[depId]) {
- return;
- }
-
- if (depMod) {
- if (!depMod.inited || !depMod.enabled) {
- //Dependency is not inited,
- //so this module cannot be
- //given a forced value yet.
- uninited[id] = true;
- return;
- }
-
- //Get the value for the current dependency
- value = forceExec(depMod, traced, uninited);
-
- //Even with forcing it may not be done,
- //in particular if the module is waiting
- //on a plugin resource.
- if (!uninited[depId]) {
- mod.defineDepById(depId, value);
- }
- }
- });
-
- mod.check(true);
-
- return defined[id];
- }
-
- function modCheck(mod) {
- mod.check();
- }
-
- function checkLoaded() {
- var map, modId, err, usingPathFallback,
- waitInterval = config.waitSeconds * 1000,
- //It is possible to disable the wait interval by using waitSeconds of 0.
- expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
- noLoads = [],
- stillLoading = false,
- needCycleCheck = true;
-
- //Do not bother if this call was a result of a cycle break.
- if (inCheckLoaded) {
- return;
- }
-
- inCheckLoaded = true;
-
- //Figure out the state of all the modules.
- eachProp(registry, function (mod) {
- map = mod.map;
- modId = map.id;
-
- //Skip things that are not enabled or in error state.
- if (!mod.enabled) {
- return;
- }
-
- if (!mod.error) {
- //If the module should be executed, and it has not
- //been inited and time is up, remember it.
- if (!mod.inited && expired) {
- if (hasPathFallback(modId)) {
- usingPathFallback = true;
- stillLoading = true;
- } else {
- noLoads.push(modId);
- removeScript(modId);
- }
- } else if (!mod.inited && mod.fetched && map.isDefine) {
- stillLoading = true;
- if (!map.prefix) {
- //No reason to keep looking for unfinished
- //loading. If the only stillLoading is a
- //plugin resource though, keep going,
- //because it may be that a plugin resource
- //is waiting on a non-plugin cycle.
- return (needCycleCheck = false);
- }
- }
- }
- });
-
- if (expired && noLoads.length) {
- //If wait time expired, throw error of unloaded modules.
- err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
- err.contextName = context.contextName;
- return onError(err);
- }
-
- //Not expired, check for a cycle.
- if (needCycleCheck) {
-
- each(waitAry, function (mod) {
- if (mod.defined) {
- return;
- }
-
- var cycleMod = findCycle(mod, {}, {}),
- traced = {};
-
- if (cycleMod) {
- forceExec(cycleMod, traced, {});
-
- //traced modules may have been
- //removed from the registry, but
- //their listeners still need to
- //be called.
- eachProp(traced, modCheck);
- }
- });
-
- //Now that dependencies have
- //been satisfied, trigger the
- //completion check that then
- //notifies listeners.
- eachProp(registry, modCheck);
- }
-
- //If still waiting on loads, and the waiting load is something
- //other than a plugin resource, or there are still outstanding
- //scripts, then just try back later.
- if ((!expired || usingPathFallback) && stillLoading) {
- //Something is still waiting to load. Wait for it, but only
- //if a timeout is not already in effect.
- if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
- checkLoadedTimeoutId = setTimeout(function () {
- checkLoadedTimeoutId = 0;
- checkLoaded();
- }, 50);
- }
- }
-
- inCheckLoaded = false;
- }
-
- Module = function (map) {
- this.events = undefEvents[map.id] || {};
- this.map = map;
- this.shim = config.shim[map.id];
- this.depExports = [];
- this.depMaps = [];
- this.depMatched = [];
- this.pluginMaps = {};
- this.depCount = 0;
-
- /* this.exports this.factory
- this.depMaps = [],
- this.enabled, this.fetched
- */
- };
-
- Module.prototype = {
- init: function (depMaps, factory, errback, options) {
- options = options || {};
-
- //Do not do more inits if already done. Can happen if there
- //are multiple define calls for the same module. That is not
- //a normal, common case, but it is also not unexpected.
- if (this.inited) {
- return;
- }
-
- this.factory = factory;
-
- if (errback) {
- //Register for errors on this module.
- this.on('error', errback);
- } else if (this.events.error) {
- //If no errback already, but there are error listeners
- //on this module, set up an errback to pass to the deps.
- errback = bind(this, function (err) {
- this.emit('error', err);
- });
- }
-
- //Do a copy of the dependency array, so that
- //source inputs are not modified. For example
- //"shim" deps are passed in here directly, and
- //doing a direct modification of the depMaps array
- //would affect that config.
- this.depMaps = depMaps && depMaps.slice(0);
- this.depMaps.rjsSkipMap = depMaps.rjsSkipMap;
-
- this.errback = errback;
-
- //Indicate this module has be initialized
- this.inited = true;
-
- this.ignore = options.ignore;
-
- //Could have option to init this module in enabled mode,
- //or could have been previously marked as enabled. However,
- //the dependencies are not known until init is called. So
- //if enabled previously, now trigger dependencies as enabled.
- if (options.enabled || this.enabled) {
- //Enable this module and dependencies.
- //Will call this.check()
- this.enable();
- } else {
- this.check();
- }
- },
-
- defineDepById: function (id, depExports) {
- var i;
-
- //Find the index for this dependency.
- each(this.depMaps, function (map, index) {
- if (map.id === id) {
- i = index;
- return true;
- }
- });
-
- return this.defineDep(i, depExports);
- },
-
- defineDep: function (i, depExports) {
- //Because of cycles, defined callback for a given
- //export can be called more than once.
- if (!this.depMatched[i]) {
- this.depMatched[i] = true;
- this.depCount -= 1;
- this.depExports[i] = depExports;
- }
- },
-
- fetch: function () {
- if (this.fetched) {
- return;
- }
- this.fetched = true;
-
- context.startTime = (new Date()).getTime();
-
- var map = this.map;
-
- //If the manager is for a plugin managed resource,
- //ask the plugin to load it now.
- if (this.shim) {
- makeRequire(this, true)(this.shim.deps || [], bind(this, function () {
- return map.prefix ? this.callPlugin() : this.load();
- }));
- } else {
- //Regular dependency.
- return map.prefix ? this.callPlugin() : this.load();
- }
- },
-
- load: function () {
- var url = this.map.url;
-
- //Regular dependency.
- if (!urlFetched[url]) {
- urlFetched[url] = true;
- context.load(this.map.id, url);
- }
- },
-
- /**
- * Checks is the module is ready to define itself, and if so,
- * define it. If the silent argument is true, then it will just
- * define, but not notify listeners, and not ask for a context-wide
- * check of all loaded modules. That is useful for cycle breaking.
- */
- check: function (silent) {
- if (!this.enabled || this.enabling) {
- return;
- }
-
- var err, cjsModule,
- id = this.map.id,
- depExports = this.depExports,
- exports = this.exports,
- factory = this.factory;
-
- if (!this.inited) {
- this.fetch();
- } else if (this.error) {
- this.emit('error', this.error);
- } else if (!this.defining) {
- //The factory could trigger another require call
- //that would result in checking this module to
- //define itself again. If already in the process
- //of doing that, skip this work.
- this.defining = true;
-
- if (this.depCount < 1 && !this.defined) {
- if (isFunction(factory)) {
- //If there is an error listener, favor passing
- //to that instead of throwing an error.
- if (this.events.error) {
- try {
- exports = context.execCb(id, factory, depExports, exports);
- } catch (e) {
- err = e;
- }
- } else {
- exports = context.execCb(id, factory, depExports, exports);
- }
-
- if (this.map.isDefine) {
- //If setting exports via 'module' is in play,
- //favor that over return value and exports. After that,
- //favor a non-undefined return value over exports use.
- cjsModule = this.module;
- if (cjsModule &&
- cjsModule.exports !== undefined &&
- //Make sure it is not already the exports value
- cjsModule.exports !== this.exports) {
- exports = cjsModule.exports;
- } else if (exports === undefined && this.usingExports) {
- //exports already set the defined value.
- exports = this.exports;
- }
- }
-
- if (err) {
- err.requireMap = this.map;
- err.requireModules = [this.map.id];
- err.requireType = 'define';
- return onError((this.error = err));
- }
-
- } else {
- //Just a literal value
- exports = factory;
- }
-
- this.exports = exports;
-
- if (this.map.isDefine && !this.ignore) {
- defined[id] = exports;
-
- if (req.onResourceLoad) {
- req.onResourceLoad(context, this.map, this.depMaps);
- }
- }
-
- //Clean up
- delete registry[id];
-
- this.defined = true;
- context.waitCount -= 1;
- if (context.waitCount === 0) {
- //Clear the wait array used for cycles.
- waitAry = [];
- }
- }
-
- //Finished the define stage. Allow calling check again
- //to allow define notifications below in the case of a
- //cycle.
- this.defining = false;
-
- if (!silent) {
- if (this.defined && !this.defineEmitted) {
- this.defineEmitted = true;
- this.emit('defined', this.exports);
- this.defineEmitComplete = true;
- }
- }
- }
- },
-
- callPlugin: function () {
- var map = this.map,
- id = map.id,
- pluginMap = makeModuleMap(map.prefix, null, false, true);
-
- on(pluginMap, 'defined', bind(this, function (plugin) {
- var load, normalizedMap, normalizedMod,
- name = this.map.name,
- parentName = this.map.parentMap ? this.map.parentMap.name : null;
-
- //If current map is not normalized, wait for that
- //normalized name to load instead of continuing.
- if (this.map.unnormalized) {
- //Normalize the ID if the plugin allows it.
- if (plugin.normalize) {
- name = plugin.normalize(name, function (name) {
- return normalize(name, parentName, true);
- }) || '';
- }
-
- normalizedMap = makeModuleMap(map.prefix + '!' + name,
- this.map.parentMap,
- false,
- true);
- on(normalizedMap,
- 'defined', bind(this, function (value) {
- this.init([], function () { return value; }, null, {
- enabled: true,
- ignore: true
- });
- }));
- normalizedMod = registry[normalizedMap.id];
- if (normalizedMod) {
- if (this.events.error) {
- normalizedMod.on('error', bind(this, function (err) {
- this.emit('error', err);
- }));
- }
- normalizedMod.enable();
- }
-
- return;
- }
-
- load = bind(this, function (value) {
- this.init([], function () { return value; }, null, {
- enabled: true
- });
- });
-
- load.error = bind(this, function (err) {
- this.inited = true;
- this.error = err;
- err.requireModules = [id];
-
- //Remove temp unnormalized modules for this module,
- //since they will never be resolved otherwise now.
- eachProp(registry, function (mod) {
- if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
- removeWaiting(mod.map.id);
- }
- });
-
- onError(err);
- });
-
- //Allow plugins to load other code without having to know the
- //context or how to 'complete' the load.
- load.fromText = function (moduleName, text) {
- /*jslint evil: true */
- var hasInteractive = useInteractive;
-
- //Turn off interactive script matching for IE for any define
- //calls in the text, then turn it back on at the end.
- if (hasInteractive) {
- useInteractive = false;
- }
-
- //Prime the system by creating a module instance for
- //it.
- getModule(makeModuleMap(moduleName));
-
- req.exec(text);
-
- if (hasInteractive) {
- useInteractive = true;
- }
-
- //Support anonymous modules.
- context.completeLoad(moduleName);
- };
-
- //Use parentName here since the plugin's name is not reliable,
- //could be some weird string with no path that actually wants to
- //reference the parentName's path.
- plugin.load(map.name, makeRequire(map.parentMap, true, function (deps, cb, er) {
- deps.rjsSkipMap = true;
- return context.require(deps, cb, er);
- }), load, config);
- }));
-
- context.enable(pluginMap, this);
- this.pluginMaps[pluginMap.id] = pluginMap;
- },
-
- enable: function () {
- this.enabled = true;
-
- if (!this.waitPushed) {
- waitAry.push(this);
- context.waitCount += 1;
- this.waitPushed = true;
- }
-
- //Set flag mentioning that the module is enabling,
- //so that immediate calls to the defined callbacks
- //for dependencies do not trigger inadvertent load
- //with the depCount still being zero.
- this.enabling = true;
-
- //Enable each dependency
- each(this.depMaps, bind(this, function (depMap, i) {
- var id, mod, handler;
-
- if (typeof depMap === 'string') {
- //Dependency needs to be converted to a depMap
- //and wired up to this module.
- depMap = makeModuleMap(depMap,
- (this.map.isDefine ? this.map : this.map.parentMap),
- false,
- !this.depMaps.rjsSkipMap);
- this.depMaps[i] = depMap;
-
- handler = handlers[depMap.id];
-
- if (handler) {
- this.depExports[i] = handler(this);
- return;
- }
-
- this.depCount += 1;
-
- on(depMap, 'defined', bind(this, function (depExports) {
- this.defineDep(i, depExports);
- this.check();
- }));
-
- if (this.errback) {
- on(depMap, 'error', this.errback);
- }
- }
-
- id = depMap.id;
- mod = registry[id];
-
- //Skip special modules like 'require', 'exports', 'module'
- //Also, don't call enable if it is already enabled,
- //important in circular dependency cases.
- if (!handlers[id] && mod && !mod.enabled) {
- context.enable(depMap, this);
- }
- }));
-
- //Enable each plugin that is used in
- //a dependency
- eachProp(this.pluginMaps, bind(this, function (pluginMap) {
- var mod = registry[pluginMap.id];
- if (mod && !mod.enabled) {
- context.enable(pluginMap, this);
- }
- }));
-
- this.enabling = false;
-
- this.check();
- },
-
- on: function (name, cb) {
- var cbs = this.events[name];
- if (!cbs) {
- cbs = this.events[name] = [];
- }
- cbs.push(cb);
- },
-
- emit: function (name, evt) {
- each(this.events[name], function (cb) {
- cb(evt);
- });
- if (name === 'error') {
- //Now that the error handler was triggered, remove
- //the listeners, since this broken Module instance
- //can stay around for a while in the registry/waitAry.
- delete this.events[name];
- }
- }
- };
-
- function callGetModule(args) {
- getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
- }
-
- function removeListener(node, func, name, ieName) {
- //Favor detachEvent because of IE9
- //issue, see attachEvent/addEventListener comment elsewhere
- //in this file.
- if (node.detachEvent && !isOpera) {
- //Probably IE. If not it will throw an error, which will be
- //useful to know.
- if (ieName) {
- node.detachEvent(ieName, func);
- }
- } else {
- node.removeEventListener(name, func, false);
- }
- }
-
- /**
- * Given an event from a script node, get the requirejs info from it,
- * and then removes the event listeners on the node.
- * @param {Event} evt
- * @returns {Object}
- */
- function getScriptData(evt) {
- //Using currentTarget instead of target for Firefox 2.0's sake. Not
- //all old browsers will be supported, but this one was easy enough
- //to support and still makes sense.
- var node = evt.currentTarget || evt.srcElement;
-
- //Remove the listeners once here.
- removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
- removeListener(node, context.onScriptError, 'error');
-
- return {
- node: node,
- id: node && node.getAttribute('data-requiremodule')
- };
- }
-
- return (context = {
- config: config,
- contextName: contextName,
- registry: registry,
- defined: defined,
- urlFetched: urlFetched,
- waitCount: 0,
- defQueue: defQueue,
- Module: Module,
- makeModuleMap: makeModuleMap,
-
- /**
- * Set a configuration for the context.
- * @param {Object} cfg config object to integrate.
- */
- configure: function (cfg) {
- //Make sure the baseUrl ends in a slash.
- if (cfg.baseUrl) {
- if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
- cfg.baseUrl += '/';
- }
- }
-
- //Save off the paths and packages since they require special processing,
- //they are additive.
- var pkgs = config.pkgs,
- shim = config.shim,
- paths = config.paths,
- map = config.map;
-
- //Mix in the config values, favoring the new values over
- //existing ones in context.config.
- mixin(config, cfg, true);
-
- //Merge paths.
- config.paths = mixin(paths, cfg.paths, true);
-
- //Merge map
- if (cfg.map) {
- config.map = mixin(map || {}, cfg.map, true, true);
- }
-
- //Merge shim
- if (cfg.shim) {
- eachProp(cfg.shim, function (value, id) {
- //Normalize the structure
- if (isArray(value)) {
- value = {
- deps: value
- };
- }
- if (value.exports && !value.exports.__buildReady) {
- value.exports = context.makeShimExports(value.exports);
- }
- shim[id] = value;
- });
- config.shim = shim;
- }
-
- //Adjust packages if necessary.
- if (cfg.packages) {
- each(cfg.packages, function (pkgObj) {
- var location;
-
- pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
- location = pkgObj.location;
-
- //Create a brand new object on pkgs, since currentPackages can
- //be passed in again, and config.pkgs is the internal transformed
- //state for all package configs.
- pkgs[pkgObj.name] = {
- name: pkgObj.name,
- location: location || pkgObj.name,
- //Remove leading dot in main, so main paths are normalized,
- //and remove any trailing .js, since different package
- //envs have different conventions: some use a module name,
- //some use a file name.
- main: (pkgObj.main || 'main')
- .replace(currDirRegExp, '')
- .replace(jsSuffixRegExp, '')
- };
- });
-
- //Done with modifications, assing packages back to context config
- config.pkgs = pkgs;
- }
-
- //If there are any "waiting to execute" modules in the registry,
- //update the maps for them, since their info, like URLs to load,
- //may have changed.
- eachProp(registry, function (mod, id) {
- //If module already has init called, since it is too
- //late to modify them, and ignore unnormalized ones
- //since they are transient.
- if (!mod.inited && !mod.map.unnormalized) {
- mod.map = makeModuleMap(id);
- }
- });
-
- //If a deps array or a config callback is specified, then call
- //require with those args. This is useful when require is defined as a
- //config object before require.js is loaded.
- if (cfg.deps || cfg.callback) {
- context.require(cfg.deps || [], cfg.callback);
- }
- },
-
- makeShimExports: function (exports) {
- var func;
- if (typeof exports === 'string') {
- func = function () {
- return getGlobal(exports);
- };
- //Save the exports for use in nodefine checking.
- func.exports = exports;
- return func;
- } else {
- return function () {
- return exports.apply(global, arguments);
- };
- }
- },
-
- requireDefined: function (id, relMap) {
- return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
- },
-
- requireSpecified: function (id, relMap) {
- id = makeModuleMap(id, relMap, false, true).id;
- return hasProp(defined, id) || hasProp(registry, id);
- },
-
- require: function (deps, callback, errback, relMap) {
- var moduleName, id, map, requireMod, args;
- if (typeof deps === 'string') {
- if (isFunction(callback)) {
- //Invalid call
- return onError(makeError('requireargs', 'Invalid require call'), errback);
- }
-
- //Synchronous access to one module. If require.get is
- //available (as in the Node adapter), prefer that.
- //In this case deps is the moduleName and callback is
- //the relMap
- if (req.get) {
- return req.get(context, deps, callback);
- }
-
- //Just return the module wanted. In this scenario, the
- //second arg (if passed) is just the relMap.
- moduleName = deps;
- relMap = callback;
-
- //Normalize module name, if it contains . or ..
- map = makeModuleMap(moduleName, relMap, false, true);
- id = map.id;
-
- if (!hasProp(defined, id)) {
- return onError(makeError('notloaded', 'Module name "' +
- id +
- '" has not been loaded yet for context: ' +
- contextName));
- }
- return defined[id];
- }
-
- //Callback require. Normalize args. if callback or errback is
- //not a function, it means it is a relMap. Test errback first.
- if (errback && !isFunction(errback)) {
- relMap = errback;
- errback = undefined;
- }
- if (callback && !isFunction(callback)) {
- relMap = callback;
- callback = undefined;
- }
-
- //Any defined modules in the global queue, intake them now.
- takeGlobalQueue();
-
- //Make sure any remaining defQueue items get properly processed.
- while (defQueue.length) {
- args = defQueue.shift();
- if (args[0] === null) {
- return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
- } else {
- //args are id, deps, factory. Should be normalized by the
- //define() function.
- callGetModule(args);
- }
- }
-
- //Mark all the dependencies as needing to be loaded.
- requireMod = getModule(makeModuleMap(null, relMap));
-
- requireMod.init(deps, callback, errback, {
- enabled: true
- });
-
- checkLoaded();
-
- return context.require;
- },
-
- undef: function (id) {
- //Bind any waiting define() calls to this context,
- //fix for #408
- takeGlobalQueue();
-
- var map = makeModuleMap(id, null, true),
- mod = registry[id];
-
- delete defined[id];
- delete urlFetched[map.url];
- delete undefEvents[id];
-
- if (mod) {
- //Hold on to listeners in case the
- //module will be attempted to be reloaded
- //using a different config.
- if (mod.events.defined) {
- undefEvents[id] = mod.events;
- }
-
- removeWaiting(id);
- }
- },
-
- /**
- * Called to enable a module if it is still in the registry
- * awaiting enablement. parent module is passed in for context,
- * used by the optimizer.
- */
- enable: function (depMap, parent) {
- var mod = registry[depMap.id];
- if (mod) {
- getModule(depMap).enable();
- }
- },
-
- /**
- * Internal method used by environment adapters to complete a load event.
- * A load event could be a script load or just a load pass from a synchronous
- * load call.
- * @param {String} moduleName the name of the module to potentially complete.
- */
- completeLoad: function (moduleName) {
- var found, args, mod,
- shim = config.shim[moduleName] || {},
- shExports = shim.exports && shim.exports.exports;
-
- takeGlobalQueue();
-
- while (defQueue.length) {
- args = defQueue.shift();
- if (args[0] === null) {
- args[0] = moduleName;
- //If already found an anonymous module and bound it
- //to this name, then this is some other anon module
- //waiting for its completeLoad to fire.
- if (found) {
- break;
- }
- found = true;
- } else if (args[0] === moduleName) {
- //Found matching define call for this script!
- found = true;
- }
-
- callGetModule(args);
- }
-
- //Do this after the cycle of callGetModule in case the result
- //of those calls/init calls changes the registry.
- mod = registry[moduleName];
-
- if (!found && !defined[moduleName] && mod && !mod.inited) {
- if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
- if (hasPathFallback(moduleName)) {
- return;
- } else {
- return onError(makeError('nodefine',
- 'No define call for ' + moduleName,
- null,
- [moduleName]));
- }
- } else {
- //A script that does not call define(), so just simulate
- //the call for it.
- callGetModule([moduleName, (shim.deps || []), shim.exports]);
- }
- }
-
- checkLoaded();
- },
-
- /**
- * Converts a module name + .extension into an URL path.
- * *Requires* the use of a module name. It does not support using
- * plain URLs like nameToUrl.
- */
- toUrl: function (moduleNamePlusExt, relModuleMap) {
- var index = moduleNamePlusExt.lastIndexOf('.'),
- ext = null;
-
- if (index !== -1) {
- ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
- moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
- }
-
- return context.nameToUrl(normalize(moduleNamePlusExt, relModuleMap && relModuleMap.id, true),
- ext);
- },
-
- /**
- * Converts a module name to a file path. Supports cases where
- * moduleName may actually be just an URL.
- * Note that it **does not** call normalize on the moduleName,
- * it is assumed to have already been normalized. This is an
- * internal API, not a public one. Use toUrl for the public API.
- */
- nameToUrl: function (moduleName, ext) {
- var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
- parentPath;
-
- //If a colon is in the URL, it indicates a protocol is used and it is just
- //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
- //or ends with .js, then assume the user meant to use an url and not a module id.
- //The slash is important for protocol-less URLs as well as full paths.
- if (req.jsExtRegExp.test(moduleName)) {
- //Just a plain path, not module name lookup, so just return it.
- //Add extension if it is included. This is a bit wonky, only non-.js things pass
- //an extension, this method probably needs to be reworked.
- url = moduleName + (ext || '');
- } else {
- //A module that needs to be converted to a path.
- paths = config.paths;
- pkgs = config.pkgs;
-
- syms = moduleName.split('/');
- //For each module name segment, see if there is a path
- //registered for it. Start with most specific name
- //and work up from it.
- for (i = syms.length; i > 0; i -= 1) {
- parentModule = syms.slice(0, i).join('/');
- pkg = pkgs[parentModule];
- parentPath = paths[parentModule];
- if (parentPath) {
- //If an array, it means there are a few choices,
- //Choose the one that is desired
- if (isArray(parentPath)) {
- parentPath = parentPath[0];
- }
- syms.splice(0, i, parentPath);
- break;
- } else if (pkg) {
- //If module name is just the package name, then looking
- //for the main module.
- if (moduleName === pkg.name) {
- pkgPath = pkg.location + '/' + pkg.main;
- } else {
- pkgPath = pkg.location;
- }
- syms.splice(0, i, pkgPath);
- break;
- }
- }
-
- //Join the path parts together, then figure out if baseUrl is needed.
- url = syms.join('/');
- url += (ext || (/\?/.test(url) ? '' : '.js'));
- url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
- }
-
- return config.urlArgs ? url +
- ((url.indexOf('?') === -1 ? '?' : '&') +
- config.urlArgs) : url;
- },
-
- //Delegates to req.load. Broken out as a separate function to
- //allow overriding in the optimizer.
- load: function (id, url) {
- req.load(context, id, url);
- },
-
- /**
- * Executes a module callack function. Broken out as a separate function
- * solely to allow the build system to sequence the files in the built
- * layer in the right sequence.
- *
- * @private
- */
- execCb: function (name, callback, args, exports) {
- return callback.apply(exports, args);
- },
-
- /**
- * callback for script loads, used to check status of loading.
- *
- * @param {Event} evt the event from the browser for the script
- * that was loaded.
- */
- onScriptLoad: function (evt) {
- //Using currentTarget instead of target for Firefox 2.0's sake. Not
- //all old browsers will be supported, but this one was easy enough
- //to support and still makes sense.
- if (evt.type === 'load' ||
- (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
- //Reset interactive script so a script node is not held onto for
- //to long.
- interactiveScript = null;
-
- //Pull out the name of the module and the context.
- var data = getScriptData(evt);
- context.completeLoad(data.id);
- }
- },
-
- /**
- * Callback for script errors.
- */
- onScriptError: function (evt) {
- var data = getScriptData(evt);
- if (!hasPathFallback(data.id)) {
- return onError(makeError('scripterror', 'Script error', evt, [data.id]));
- }
- }
- });
- }
-
- /**
- * Main entry point.
- *
- * If the only argument to require is a string, then the module that
- * is represented by that string is fetched for the appropriate context.
- *
- * If the first argument is an array, then it will be treated as an array
- * of dependency string names to fetch. An optional function callback can
- * be specified to execute when all of those dependencies are available.
- *
- * Make a local req variable to help Caja compliance (it assumes things
- * on a require that are not standardized), and to give a short
- * name for minification/local scope use.
- */
- req = requirejs = function (deps, callback, errback, optional) {
-
- //Find the right context, use default
- var context, config,
- contextName = defContextName;
-
- // Determine if have config object in the call.
- if (!isArray(deps) && typeof deps !== 'string') {
- // deps is a config object
- config = deps;
- if (isArray(callback)) {
- // Adjust args if there are dependencies
- deps = callback;
- callback = errback;
- errback = optional;
- } else {
- deps = [];
- }
- }
-
- if (config && config.context) {
- contextName = config.context;
- }
-
- context = contexts[contextName];
- if (!context) {
- context = contexts[contextName] = req.s.newContext(contextName);
- }
-
- if (config) {
- context.configure(config);
- }
-
- return context.require(deps, callback, errback);
- };
-
- /**
- * Support require.config() to make it easier to cooperate with other
- * AMD loaders on globally agreed names.
- */
- req.config = function (config) {
- return req(config);
- };
-
- /**
- * Export require as a global, but only if it does not already exist.
- */
- if (!require) {
- require = req;
- }
-
- req.version = version;
-
- //Used to filter out dependencies that are already paths.
- req.jsExtRegExp = /^\/|:|\?|\.js$/;
- req.isBrowser = isBrowser;
- s = req.s = {
- contexts: contexts,
- newContext: newContext
- };
-
- //Create default context.
- req({});
-
- //Exports some context-sensitive methods on global require, using
- //default context if no context specified.
- addRequireMethods(req);
-
- if (isBrowser) {
- head = s.head = document.getElementsByTagName('head')[0];
- //If BASE tag is in play, using appendChild is a problem for IE6.
- //When that browser dies, this can be removed. Details in this jQuery bug:
- //http://dev.jquery.com/ticket/2709
- baseElement = document.getElementsByTagName('base')[0];
- if (baseElement) {
- head = s.head = baseElement.parentNode;
- }
- }
-
- /**
- * Any errors that require explicitly generates will be passed to this
- * function. Intercept/override it if you want custom error handling.
- * @param {Error} err the error object.
- */
- req.onError = function (err) {
- throw err;
- };
-
- /**
- * Does the request to load a module for the browser case.
- * Make this a separate function to allow other environments
- * to override it.
- *
- * @param {Object} context the require context to find state.
- * @param {String} moduleName the name of the module.
- * @param {Object} url the URL to the module.
- */
- req.load = function (context, moduleName, url) {
- var config = (context && context.config) || {},
- node;
- if (isBrowser) {
- //In the browser so use a script tag
- node = config.xhtml ?
- document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
- document.createElement('script');
- node.type = config.scriptType || 'text/javascript';
- node.charset = 'utf-8';
- node.async = true;
-
- node.setAttribute('data-requirecontext', context.contextName);
- node.setAttribute('data-requiremodule', moduleName);
-
- //Set up load listener. Test attachEvent first because IE9 has
- //a subtle issue in its addEventListener and script onload firings
- //that do not match the behavior of all other browsers with
- //addEventListener support, which fire the onload event for a
- //script right after the script execution. See:
- //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
- //UNFORTUNATELY Opera implements attachEvent but does not follow the script
- //script execution mode.
- if (node.attachEvent &&
- //Check if node.attachEvent is artificially added by custom script or
- //natively supported by browser
- //read https://github.com/jrburke/requirejs/issues/187
- //if we can NOT find [native code] then it must NOT natively supported.
- //in IE8, node.attachEvent does not have toString()
- //Note the test for "[native code" with no closing brace, see:
- //https://github.com/jrburke/requirejs/issues/273
- !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
- !isOpera) {
- //Probably IE. IE (at least 6-8) do not fire
- //script onload right after executing the script, so
- //we cannot tie the anonymous define call to a name.
- //However, IE reports the script as being in 'interactive'
- //readyState at the time of the define call.
- useInteractive = true;
-
- node.attachEvent('onreadystatechange', context.onScriptLoad);
- //It would be great to add an error handler here to catch
- //404s in IE9+. However, onreadystatechange will fire before
- //the error handler, so that does not help. If addEvenListener
- //is used, then IE will fire error before load, but we cannot
- //use that pathway given the connect.microsoft.com issue
- //mentioned above about not doing the 'script execute,
- //then fire the script load event listener before execute
- //next script' that other browsers do.
- //Best hope: IE10 fixes the issues,
- //and then destroys all installs of IE 6-9.
- //node.attachEvent('onerror', context.onScriptError);
- } else {
- node.addEventListener('load', context.onScriptLoad, false);
- node.addEventListener('error', context.onScriptError, false);
- }
- node.src = url;
-
- //For some cache cases in IE 6-8, the script executes before the end
- //of the appendChild execution, so to tie an anonymous define
- //call to the module name (which is stored on the node), hold on
- //to a reference to this node, but clear after the DOM insertion.
- currentlyAddingScript = node;
- if (baseElement) {
- head.insertBefore(node, baseElement);
- } else {
- head.appendChild(node);
- }
- currentlyAddingScript = null;
-
- return node;
- } else if (isWebWorker) {
- //In a web worker, use importScripts. This is not a very
- //efficient use of importScripts, importScripts will block until
- //its script is downloaded and evaluated. However, if web workers
- //are in play, the expectation that a build has been done so that
- //only one script needs to be loaded anyway. This may need to be
- //reevaluated if other use cases become common.
- importScripts(url);
-
- //Account for anonymous modules
- context.completeLoad(moduleName);
- }
- };
-
- function getInteractiveScript() {
- if (interactiveScript && interactiveScript.readyState === 'interactive') {
- return interactiveScript;
- }
-
- eachReverse(scripts(), function (script) {
- if (script.readyState === 'interactive') {
- return (interactiveScript = script);
- }
- });
- return interactiveScript;
- }
-
- //Look for a data-main script attribute, which could also adjust the baseUrl.
- if (isBrowser) {
- //Figure out baseUrl. Get it from the script tag with require.js in it.
- eachReverse(scripts(), function (script) {
- //Set the 'head' where we can append children by
- //using the script's parent.
- if (!head) {
- head = script.parentNode;
- }
-
- //Look for a data-main attribute to set main script for the page
- //to load. If it is there, the path to data main becomes the
- //baseUrl, if it is not already set.
- dataMain = script.getAttribute('data-main');
- if (dataMain) {
- //Set final baseUrl if there is not already an explicit one.
- if (!cfg.baseUrl) {
- //Pull off the directory of data-main for use as the
- //baseUrl.
- src = dataMain.split('/');
- mainScript = src.pop();
- subPath = src.length ? src.join('/') + '/' : './';
-
- cfg.baseUrl = subPath;
- dataMain = mainScript;
- }
-
- //Strip off any trailing .js since dataMain is now
- //like a module name.
- dataMain = dataMain.replace(jsSuffixRegExp, '');
-
- //Put the data-main script in the files to load.
- cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
-
- return true;
- }
- });
- }
-
- /**
- * The function that handles definitions of modules. Differs from
- * require() in that a string for the module should be the first argument,
- * and the function to execute after dependencies are loaded should
- * return a value to define the module corresponding to the first argument's
- * name.
- */
- define = function (name, deps, callback) {
- var node, context;
-
- //Allow for anonymous functions
- if (typeof name !== 'string') {
- //Adjust args appropriately
- callback = deps;
- deps = name;
- name = null;
- }
-
- //This module may not have dependencies
- if (!isArray(deps)) {
- callback = deps;
- deps = [];
- }
-
- //If no name, and callback is a function, then figure out if it a
- //CommonJS thing with dependencies.
- if (!deps.length && isFunction(callback)) {
- //Remove comments from the callback string,
- //look for require calls, and pull them into the dependencies,
- //but only if there are function args.
- if (callback.length) {
- callback
- .toString()
- .replace(commentRegExp, '')
- .replace(cjsRequireRegExp, function (match, dep) {
- deps.push(dep);
- });
-
- //May be a CommonJS thing even without require calls, but still
- //could use exports, and module. Avoid doing exports and module
- //work though if it just needs require.
- //REQUIRES the function to expect the CommonJS variables in the
- //order listed below.
- deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
- }
- }
-
- //If in IE 6-8 and hit an anonymous define() call, do the interactive
- //work.
- if (useInteractive) {
- node = currentlyAddingScript || getInteractiveScript();
- if (node) {
- if (!name) {
- name = node.getAttribute('data-requiremodule');
- }
- context = contexts[node.getAttribute('data-requirecontext')];
- }
- }
-
- //Always save off evaluating the def call until the script onload handler.
- //This allows multiple modules to be in a file without prematurely
- //tracing dependencies, and allows for anonymous module support,
- //where the module name is not known until the script onload event
- //occurs. If no context, use the global queue, and get it processed
- //in the onscript load callback.
- (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
- };
-
- define.amd = {
- jQuery: true
- };
-
-
- /**
- * Executes the text. Normally just uses eval, but can be modified
- * to use a better, environment-specific call. Only used for transpiling
- * loader plugins, not for plain JS modules.
- * @param {String} text the text to execute/evaluate.
- */
- req.exec = function (text) {
- /*jslint evil: true */
- return eval(text);
- };
-
- //Set up with config info.
- req(cfg);
- }(this));
-
-
- if (env === 'rhino') {
- /**
- * @license RequireJS rhino Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint */
- /*global require: false, java: false, load: false */
-
- (function () {
- 'use strict';
- require.load = function (context, moduleName, url) {
-
- load(url);
-
- //Support anonymous modules.
- context.completeLoad(moduleName);
- };
-
- }());
- } else if (env === 'node') {
- this.requirejsVars = {
- require: require,
- requirejs: require,
- define: define,
- nodeRequire: nodeRequire
- };
- require.nodeRequire = nodeRequire;
-
- /**
- * @license RequireJS node Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint regexp: false */
- /*global require: false, define: false, requirejsVars: false, process: false */
-
- /**
- * This adapter assumes that x.js has loaded it and set up
- * some variables. This adapter just allows limited RequireJS
- * usage from within the requirejs directory. The general
- * node adapater is r.js.
- */
-
- (function () {
- 'use strict';
-
- var nodeReq = requirejsVars.nodeRequire,
- req = requirejsVars.require,
- def = requirejsVars.define,
- fs = nodeReq('fs'),
- path = nodeReq('path'),
- vm = nodeReq('vm'),
- //In Node 0.7+ existsSync is on fs.
- exists = fs.existsSync || path.existsSync;
-
- //Supply an implementation that allows synchronous get of a module.
- req.get = function (context, moduleName, relModuleMap) {
- if (moduleName === "require" || moduleName === "exports" || moduleName === "module") {
- req.onError(new Error("Explicit require of " + moduleName + " is not allowed."));
- }
-
- var ret,
- moduleMap = context.makeModuleMap(moduleName, relModuleMap);
-
- //Normalize module name, if it contains . or ..
- moduleName = moduleMap.id;
-
- if (context.defined.hasOwnProperty(moduleName)) {
- ret = context.defined[moduleName];
- } else {
- if (ret === undefined) {
- //Try to dynamically fetch it.
- req.load(context, moduleName, moduleMap.url);
- //The above call is sync, so can do the next thing safely.
- ret = context.defined[moduleName];
- }
- }
-
- return ret;
- };
-
- //Add wrapper around the code so that it gets the requirejs
- //API instead of the Node API, and it is done lexically so
- //that it survives later execution.
- req.makeNodeWrapper = function (contents) {
- return '(function (require, requirejs, define) { ' +
- contents +
- '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));';
- };
-
- req.load = function (context, moduleName, url) {
- var contents, err;
-
- if (exists(url)) {
- contents = fs.readFileSync(url, 'utf8');
-
- contents = req.makeNodeWrapper(contents);
- try {
- vm.runInThisContext(contents, fs.realpathSync(url));
- } catch (e) {
- err = new Error('Evaluating ' + url + ' as module "' +
- moduleName + '" failed with error: ' + e);
- err.originalError = e;
- err.moduleName = moduleName;
- err.fileName = url;
- return req.onError(err);
- }
- } else {
- def(moduleName, function () {
- //Get the original name, since relative requires may be
- //resolved differently in node (issue #202)
- var originalName = context.registry[moduleName] &&
- context.registry[moduleName].map.originalName;
-
- try {
- return (context.config.nodeRequire || req.nodeRequire)(originalName);
- } catch (e) {
- err = new Error('Calling node\'s require("' +
- originalName + '") failed with error: ' + e);
- err.originalError = e;
- err.moduleName = originalName;
- return req.onError(err);
- }
- });
- }
-
- //Support anonymous modules.
- context.completeLoad(moduleName);
- };
-
- //Override to provide the function wrapper for define/require.
- req.exec = function (text) {
- /*jslint evil: true */
- text = req.makeNodeWrapper(text);
- return eval(text);
- };
- }());
-
- }
-
- //Support a default file name to execute. Useful for hosted envs
- //like Joyent where it defaults to a server.js as the only executed
- //script. But only do it if this is not an optimization run.
- if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) {
- fileName = 'main.js';
- }
-
- /**
- * Loads the library files that can be used for the optimizer, or for other
- * tasks.
- */
- function loadLib() {
- /**
- * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint strict: false */
- /*global Packages: false, process: false, window: false, navigator: false,
- document: false, define: false */
-
- /**
- * A plugin that modifies any /env/ path to be the right path based on
- * the host environment. Right now only works for Node, Rhino and browser.
- */
- (function () {
- var pathRegExp = /(\/|^)env\/|\{env\}/,
- env = 'unknown';
-
- if (typeof Packages !== 'undefined') {
- env = 'rhino';
- } else if (typeof process !== 'undefined') {
- env = 'node';
- } else if (typeof window !== "undefined" && navigator && document) {
- env = 'browser';
- }
-
- define('env', {
- load: function (name, req, load, config) {
- //Allow override in the config.
- if (config.env) {
- env = config.env;
- }
-
- name = name.replace(pathRegExp, function (match, prefix) {
- if (match.indexOf('{') === -1) {
- return prefix + env + '/';
- } else {
- return env;
- }
- });
-
- req([name], function (mod) {
- load(mod);
- });
- }
- });
- }());
- if(env === 'node') {
- /**
- * @license RequireJS Copyright (c) 2012, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint strict: false */
- /*global define: false, load: false */
-
- //Needed so that rhino/assert can return a stub for uglify's consolidator.js
- define('node/assert', ['assert'], function (assert) {
- return assert;
- });
-
- }
-
- if(env === 'rhino') {
- /**
- * @license RequireJS Copyright (c) 2012, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint strict: false */
- /*global define: false, load: false */
-
- //Just a stub for use with uglify's consolidator.js
- define('rhino/assert', function () {
- return {};
- });
-
- }
-
- if(env === 'node') {
- /**
- * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint strict: false */
- /*global define: false, process: false */
-
- define('node/args', function () {
- //Do not return the "node" or "r.js" arguments
- var args = process.argv.slice(2);
-
- //Ignore any command option used for rq.js
- if (args[0] && args[0].indexOf('-' === 0)) {
- args = args.slice(1);
- }
-
- return args;
- });
-
- }
-
- if(env === 'rhino') {
- /**
- * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint strict: false */
- /*global define: false, process: false */
-
- var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
-
- define('rhino/args', function () {
- var args = jsLibRhinoArgs;
-
- //Ignore any command option used for rq.js
- if (args[0] && args[0].indexOf('-' === 0)) {
- args = args.slice(1);
- }
-
- return args;
- });
-
- }
-
- if(env === 'node') {
- /**
- * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint strict: false */
- /*global define: false, console: false */
-
- define('node/load', ['fs'], function (fs) {
- function load(fileName) {
- var contents = fs.readFileSync(fileName, 'utf8');
- process.compile(contents, fileName);
- }
-
- return load;
- });
-
- }
-
- if(env === 'rhino') {
- /**
- * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint strict: false */
- /*global define: false, load: false */
-
- define('rhino/load', function () {
- return load;
- });
-
- }
-
- if(env === 'node') {
- /**
- * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint plusplus: false, octal:false, strict: false */
- /*global define: false, process: false */
-
- define('node/file', ['fs', 'path'], function (fs, path) {
-
- var isWindows = process.platform === 'win32',
- windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
- file;
-
- function frontSlash(path) {
- return path.replace(/\\/g, '/');
- }
-
- function exists(path) {
- if (isWindows && path.charAt(path.length - 1) === '/' &&
- path.charAt(path.length - 2) !== ':') {
- path = path.substring(0, path.length - 1);
- }
-
- try {
- fs.statSync(path);
- return true;
- } catch (e) {
- return false;
- }
- }
-
- function mkDir(dir) {
- if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {
- fs.mkdirSync(dir, 511);
- }
- }
-
- function mkFullDir(dir) {
- var parts = dir.split('/'),
- currDir = '',
- first = true;
-
- parts.forEach(function (part) {
- //First part may be empty string if path starts with a slash.
- currDir += part + '/';
- first = false;
-
- if (part) {
- mkDir(currDir);
- }
- });
- }
-
- file = {
- backSlashRegExp: /\\/g,
- exclusionRegExp: /^\./,
- getLineSeparator: function () {
- return '/';
- },
-
- exists: function (fileName) {
- return exists(fileName);
- },
-
- parent: function (fileName) {
- var parts = fileName.split('/');
- parts.pop();
- return parts.join('/');
- },
-
- /**
- * Gets the absolute file path as a string, normalized
- * to using front slashes for path separators.
- * @param {String} fileName
- */
- absPath: function (fileName) {
- return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));
- },
-
- normalize: function (fileName) {
- return frontSlash(path.normalize(fileName));
- },
-
- isFile: function (path) {
- return fs.statSync(path).isFile();
- },
-
- isDirectory: function (path) {
- return fs.statSync(path).isDirectory();
- },
-
- getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {
- //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
- //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
- //and it will be treated as the "include" case.
- //Ignores files/directories that start with a period (.) unless exclusionRegExp
- //is set to another value.
- var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
- i, stat, filePath, ok, dirFiles, fileName;
-
- topDir = startDir;
-
- regExpInclude = regExpFilters.include || regExpFilters;
- regExpExclude = regExpFilters.exclude || null;
-
- if (file.exists(topDir)) {
- dirFileArray = fs.readdirSync(topDir);
- for (i = 0; i < dirFileArray.length; i++) {
- fileName = dirFileArray[i];
- filePath = path.join(topDir, fileName);
- stat = fs.statSync(filePath);
- if (stat.isFile()) {
- if (makeUnixPaths) {
- //Make sure we have a JS string.
- if (filePath.indexOf("/") === -1) {
- filePath = frontSlash(filePath);
- }
- }
-
- ok = true;
- if (regExpInclude) {
- ok = filePath.match(regExpInclude);
- }
- if (ok && regExpExclude) {
- ok = !filePath.match(regExpExclude);
- }
-
- if (ok && (!file.exclusionRegExp ||
- !file.exclusionRegExp.test(fileName))) {
- files.push(filePath);
- }
- } else if (stat.isDirectory() &&
- (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {
- dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);
- files.push.apply(files, dirFiles);
- }
- }
- }
-
- return files; //Array
- },
-
- copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
- //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
- //file should be copied. Returns a list file name strings of the destinations that were copied.
- regExpFilter = regExpFilter || /\w/;
-
- //Normalize th directory names, but keep front slashes.
- //path module on windows now returns backslashed paths.
- srcDir = frontSlash(path.normalize(srcDir));
- destDir = frontSlash(path.normalize(destDir));
-
- var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
- copiedFiles = [], i, srcFileName, destFileName;
-
- for (i = 0; i < fileNames.length; i++) {
- srcFileName = fileNames[i];
- destFileName = srcFileName.replace(srcDir, destDir);
-
- if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
- copiedFiles.push(destFileName);
- }
- }
-
- return copiedFiles.length ? copiedFiles : null; //Array or null
- },
-
- copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
- //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
- //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
- var parentDir;
-
- //logger.trace("Src filename: " + srcFileName);
- //logger.trace("Dest filename: " + destFileName);
-
- //If onlyCopyNew is true, then compare dates and only copy if the src is newer
- //than dest.
- if (onlyCopyNew) {
- if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {
- return false; //Boolean
- }
- }
-
- //Make sure destination dir exists.
- parentDir = path.dirname(destFileName);
- if (!file.exists(parentDir)) {
- mkFullDir(parentDir);
- }
-
- fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');
-
- return true; //Boolean
- },
-
- /**
- * Renames a file. May fail if "to" already exists or is on another drive.
- */
- renameFile: function (from, to) {
- return fs.renameSync(from, to);
- },
-
- /**
- * Reads a *text* file.
- */
- readFile: function (/*String*/path, /*String?*/encoding) {
- if (encoding === 'utf-8') {
- encoding = 'utf8';
- }
- if (!encoding) {
- encoding = 'utf8';
- }
-
- var text = fs.readFileSync(path, encoding);
-
- //Hmm, would not expect to get A BOM, but it seems to happen,
- //remove it just in case.
- if (text.indexOf('\uFEFF') === 0) {
- text = text.substring(1, text.length);
- }
-
- return text;
- },
-
- saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
- //summary: saves a *text* file using UTF-8 encoding.
- file.saveFile(fileName, fileContents, "utf8");
- },
-
- saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
- //summary: saves a *text* file.
- var parentDir;
-
- if (encoding === 'utf-8') {
- encoding = 'utf8';
- }
- if (!encoding) {
- encoding = 'utf8';
- }
-
- //Make sure destination directories exist.
- parentDir = path.dirname(fileName);
- if (!file.exists(parentDir)) {
- mkFullDir(parentDir);
- }
-
- fs.writeFileSync(fileName, fileContents, encoding);
- },
-
- deleteFile: function (/*String*/fileName) {
- //summary: deletes a file or directory if it exists.
- var files, i, stat;
- if (file.exists(fileName)) {
- stat = fs.statSync(fileName);
- if (stat.isDirectory()) {
- files = fs.readdirSync(fileName);
- for (i = 0; i < files.length; i++) {
- this.deleteFile(path.join(fileName, files[i]));
- }
- fs.rmdirSync(fileName);
- } else {
- fs.unlinkSync(fileName);
- }
- }
- },
-
-
- /**
- * Deletes any empty directories under the given directory.
- */
- deleteEmptyDirs: function (startDir) {
- var dirFileArray, i, fileName, filePath, stat;
-
- if (file.exists(startDir)) {
- dirFileArray = fs.readdirSync(startDir);
- for (i = 0; i < dirFileArray.length; i++) {
- fileName = dirFileArray[i];
- filePath = path.join(startDir, fileName);
- stat = fs.statSync(filePath);
- if (stat.isDirectory()) {
- file.deleteEmptyDirs(filePath);
- }
- }
-
- //If directory is now empty, remove it.
- if (fs.readdirSync(startDir).length === 0) {
- file.deleteFile(startDir);
- }
- }
- }
- };
-
- return file;
-
- });
-
- }
-
- if(env === 'rhino') {
- /**
- * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
- //Helper functions to deal with file I/O.
-
- /*jslint plusplus: false, strict: true */
- /*global java: false, define: false */
-
- define('rhino/file', function () {
- var file = {
- backSlashRegExp: /\\/g,
-
- exclusionRegExp: /^\./,
-
- getLineSeparator: function () {
- return file.lineSeparator;
- },
-
- lineSeparator: java.lang.System.getProperty("line.separator"), //Java String
-
- exists: function (fileName) {
- return (new java.io.File(fileName)).exists();
- },
-
- parent: function (fileName) {
- return file.absPath((new java.io.File(fileName)).getParentFile());
- },
-
- normalize: function (fileName) {
- return file.absPath(fileName);
- },
-
- isFile: function (path) {
- return (new java.io.File(path)).isFile();
- },
-
- isDirectory: function (path) {
- return (new java.io.File(path)).isDirectory();
- },
-
- /**
- * Gets the absolute file path as a string, normalized
- * to using front slashes for path separators.
- * @param {java.io.File||String} file
- */
- absPath: function (fileObj) {
- if (typeof fileObj === "string") {
- fileObj = new java.io.File(fileObj);
- }
- return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
- },
-
- getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {
- //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
- //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
- //and it will be treated as the "include" case.
- //Ignores files/directories that start with a period (.) unless exclusionRegExp
- //is set to another value.
- var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
- i, fileObj, filePath, ok, dirFiles;
-
- topDir = startDir;
- if (!startDirIsJavaObject) {
- topDir = new java.io.File(startDir);
- }
-
- regExpInclude = regExpFilters.include || regExpFilters;
- regExpExclude = regExpFilters.exclude || null;
-
- if (topDir.exists()) {
- dirFileArray = topDir.listFiles();
- for (i = 0; i < dirFileArray.length; i++) {
- fileObj = dirFileArray[i];
- if (fileObj.isFile()) {
- filePath = fileObj.getPath();
- if (makeUnixPaths) {
- //Make sure we have a JS string.
- filePath = String(filePath);
- if (filePath.indexOf("/") === -1) {
- filePath = filePath.replace(/\\/g, "/");
- }
- }
-
- ok = true;
- if (regExpInclude) {
- ok = filePath.match(regExpInclude);
- }
- if (ok && regExpExclude) {
- ok = !filePath.match(regExpExclude);
- }
-
- if (ok && (!file.exclusionRegExp ||
- !file.exclusionRegExp.test(fileObj.getName()))) {
- files.push(filePath);
- }
- } else if (fileObj.isDirectory() &&
- (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {
- dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
- files.push.apply(files, dirFiles);
- }
- }
- }
-
- return files; //Array
- },
-
- copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
- //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
- //file should be copied. Returns a list file name strings of the destinations that were copied.
- regExpFilter = regExpFilter || /\w/;
-
- var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
- copiedFiles = [], i, srcFileName, destFileName;
-
- for (i = 0; i < fileNames.length; i++) {
- srcFileName = fileNames[i];
- destFileName = srcFileName.replace(srcDir, destDir);
-
- if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
- copiedFiles.push(destFileName);
- }
- }
-
- return copiedFiles.length ? copiedFiles : null; //Array or null
- },
-
- copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
- //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
- //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
- var destFile = new java.io.File(destFileName), srcFile, parentDir,
- srcChannel, destChannel;
-
- //logger.trace("Src filename: " + srcFileName);
- //logger.trace("Dest filename: " + destFileName);
-
- //If onlyCopyNew is true, then compare dates and only copy if the src is newer
- //than dest.
- if (onlyCopyNew) {
- srcFile = new java.io.File(srcFileName);
- if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {
- return false; //Boolean
- }
- }
-
- //Make sure destination dir exists.
- parentDir = destFile.getParentFile();
- if (!parentDir.exists()) {
- if (!parentDir.mkdirs()) {
- throw "Could not create directory: " + parentDir.getCanonicalPath();
- }
- }
-
- //Java's version of copy file.
- srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
- destChannel = new java.io.FileOutputStream(destFileName).getChannel();
- destChannel.transferFrom(srcChannel, 0, srcChannel.size());
- srcChannel.close();
- destChannel.close();
-
- return true; //Boolean
- },
-
- /**
- * Renames a file. May fail if "to" already exists or is on another drive.
- */
- renameFile: function (from, to) {
- return (new java.io.File(from)).renameTo((new java.io.File(to)));
- },
-
- readFile: function (/*String*/path, /*String?*/encoding) {
- //A file read function that can deal with BOMs
- encoding = encoding || "utf-8";
- var fileObj = new java.io.File(path),
- input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),
- stringBuffer, line;
- try {
- stringBuffer = new java.lang.StringBuffer();
- line = input.readLine();
-
- // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
- // http://www.unicode.org/faq/utf_bom.html
-
- // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
- // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
- if (line && line.length() && line.charAt(0) === 0xfeff) {
- // Eat the BOM, since we've already found the encoding on this file,
- // and we plan to concatenating this buffer with others; the BOM should
- // only appear at the top of a file.
- line = line.substring(1);
- }
- while (line !== null) {
- stringBuffer.append(line);
- stringBuffer.append(file.lineSeparator);
- line = input.readLine();
- }
- //Make sure we return a JavaScript string and not a Java string.
- return String(stringBuffer.toString()); //String
- } finally {
- input.close();
- }
- },
-
- saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
- //summary: saves a file using UTF-8 encoding.
- file.saveFile(fileName, fileContents, "utf-8");
- },
-
- saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
- //summary: saves a file.
- var outFile = new java.io.File(fileName), outWriter, parentDir, os;
-
- parentDir = outFile.getAbsoluteFile().getParentFile();
- if (!parentDir.exists()) {
- if (!parentDir.mkdirs()) {
- throw "Could not create directory: " + parentDir.getAbsolutePath();
- }
- }
-
- if (encoding) {
- outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
- } else {
- outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
- }
-
- os = new java.io.BufferedWriter(outWriter);
- try {
- os.write(fileContents);
- } finally {
- os.close();
- }
- },
-
- deleteFile: function (/*String*/fileName) {
- //summary: deletes a file or directory if it exists.
- var fileObj = new java.io.File(fileName), files, i;
- if (fileObj.exists()) {
- if (fileObj.isDirectory()) {
- files = fileObj.listFiles();
- for (i = 0; i < files.length; i++) {
- this.deleteFile(files[i]);
- }
- }
- fileObj["delete"]();
- }
- },
-
- /**
- * Deletes any empty directories under the given directory.
- * The startDirIsJavaObject is private to this implementation's
- * recursion needs.
- */
- deleteEmptyDirs: function (startDir, startDirIsJavaObject) {
- var topDir = startDir,
- dirFileArray, i, fileObj;
-
- if (!startDirIsJavaObject) {
- topDir = new java.io.File(startDir);
- }
-
- if (topDir.exists()) {
- dirFileArray = topDir.listFiles();
- for (i = 0; i < dirFileArray.length; i++) {
- fileObj = dirFileArray[i];
- if (fileObj.isDirectory()) {
- file.deleteEmptyDirs(fileObj, true);
- }
- }
-
- //If the directory is empty now, delete it.
- if (topDir.listFiles().length === 0) {
- file.deleteFile(String(topDir.getPath()));
- }
- }
- }
- };
-
- return file;
- });
-
- }
-
- if(env === 'node') {
- /*global process */
- define('node/quit', function () {
- 'use strict';
- return function (code) {
- return process.exit(code);
- };
- });
- }
-
- if(env === 'rhino') {
- /*global quit */
- define('rhino/quit', function () {
- 'use strict';
- return function (code) {
- return quit(code);
- };
- });
-
- }
- /**
- * @license Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint plusplus: true */
- /*global define */
-
- define('lang', function () {
- 'use strict';
-
- var lang = {
- backSlashRegExp: /\\/g,
- ostring: Object.prototype.toString,
-
- isArray: Array.isArray || function (it) {
- return lang.ostring.call(it) === "[object Array]";
- },
-
- isFunction: function(it) {
- return lang.ostring.call(it) === "[object Function]";
- },
-
- isRegExp: function(it) {
- return it && it instanceof RegExp;
- },
-
- _mixin: function(dest, source, override){
- var name;
- for (name in source) {
- if(source.hasOwnProperty(name)
- && (override || !dest.hasOwnProperty(name))) {
- dest[name] = source[name];
- }
- }
-
- return dest; // Object
- },
-
- /**
- * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,
- * then the source objects properties are force copied over to dest.
- */
- mixin: function(dest){
- var parameters = Array.prototype.slice.call(arguments),
- override, i, l;
-
- if (!dest) { dest = {}; }
-
- if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {
- override = parameters.pop();
- }
-
- for (i = 1, l = parameters.length; i < l; i++) {
- lang._mixin(dest, parameters[i], override);
- }
- return dest; // Object
- },
-
- delegate: (function () {
- // boodman/crockford delegation w/ cornford optimization
- function TMP() {}
- return function (obj, props) {
- TMP.prototype = obj;
- var tmp = new TMP();
- TMP.prototype = null;
- if (props) {
- lang.mixin(tmp, props);
- }
- return tmp; // Object
- };
- }()),
-
- /**
- * Helper function for iterating over an array. If the func returns
- * a true value, it will break out of the loop.
- */
- each: function each(ary, func) {
- if (ary) {
- var i;
- for (i = 0; i < ary.length; i += 1) {
- if (func(ary[i], i, ary)) {
- break;
- }
- }
- }
- },
-
- /**
- * Cycles over properties in an object and calls a function for each
- * property value. If the function returns a truthy value, then the
- * iteration is stopped.
- */
- eachProp: function eachProp(obj, func) {
- var prop;
- for (prop in obj) {
- if (obj.hasOwnProperty(prop)) {
- if (func(obj[prop], prop)) {
- break;
- }
- }
- }
- },
-
- //Similar to Function.prototype.bind, but the "this" object is specified
- //first, since it is easier to read/figure out what "this" will be.
- bind: function bind(obj, fn) {
- return function () {
- return fn.apply(obj, arguments);
- };
- },
-
- //Escapes a content string to be be a string that has characters escaped
- //for inclusion as part of a JS string.
- jsEscape: function (content) {
- return content.replace(/(["'\\])/g, '\\$1')
- .replace(/[\f]/g, "\\f")
- .replace(/[\b]/g, "\\b")
- .replace(/[\n]/g, "\\n")
- .replace(/[\t]/g, "\\t")
- .replace(/[\r]/g, "\\r");
- }
- };
- return lang;
- });
-
- if(env === 'node') {
- /**
- * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint strict: false */
- /*global define: false, console: false */
-
- define('node/print', function () {
- function print(msg) {
- console.log(msg);
- }
-
- return print;
- });
-
- }
-
- if(env === 'rhino') {
- /**
- * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint strict: false */
- /*global define: false, print: false */
-
- define('rhino/print', function () {
- return print;
- });
-
- }
- /**
- * @license RequireJS Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/jrburke/requirejs for details
- */
-
- /*jslint nomen: false, strict: false */
- /*global define: false */
-
- define('logger', ['env!env/print'], function (print) {
- var logger = {
- TRACE: 0,
- INFO: 1,
- WARN: 2,
- ERROR: 3,
- SILENT: 4,
- level: 0,
- logPrefix: "",
-
- logLevel: function( level ) {
- this.level = level;
- },
-
- trace: function (message) {
- if (this.level <= this.TRACE) {
- this._print(message);
- }
- },
-
- info: function (message) {
- if (this.level <= this.INFO) {
- this._print(message);
- }
- },
-
- warn: function (message) {
- if (this.level <= this.WARN) {
- this._print(message);
- }
- },
-
- error: function (message) {
- if (this.level <= this.ERROR) {
- this._print(message);
- }
- },
-
- _print: function (message) {
- this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message);
- },
-
- _sysPrint: function (message) {
- print(message);
- }
- };
-
- return logger;
- });
- //Just a blank file to use when building the optimizer with the optimizer,
- //so that the build does not attempt to inline some env modules,
- //like Node's fs and path.
-
- //Just a blank file to use when building the optimizer with the optimizer,
- //so that the build does not attempt to inline some env modules,
- //like Node's fs and path.
-
- //Commit 465a4eae86c7bae191b1ee427571543ace777117 on July 19, 2012
- define('esprima', ['exports'], function(exports) {
- /*
- Copyright (C) 2012 Ariya Hidayat
- Copyright (C) 2012 Mathias Bynens
- Copyright (C) 2012 Joost-Wim Boekesteijn
- Copyright (C) 2012 Kris Kowal
- Copyright (C) 2012 Yusuke Suzuki
- Copyright (C) 2012 Arpad Borsos
- Copyright (C) 2011 Ariya Hidayat
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY
- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
- /*jslint bitwise:true plusplus:true */
- /*global esprima:true, exports:true,
- throwError: true, createLiteral: true, generateStatement: true,
- parseAssignmentExpression: true, parseBlock: true, parseExpression: true,
- parseFunctionDeclaration: true, parseFunctionExpression: true,
- parseFunctionSourceElements: true, parseVariableIdentifier: true,
- parseLeftHandSideExpression: true,
- parseStatement: true, parseSourceElement: true */
-
- (function (exports) {
- 'use strict';
-
- var Token,
- TokenName,
- Syntax,
- PropertyKind,
- Messages,
- Regex,
- source,
- strict,
- index,
- lineNumber,
- lineStart,
- length,
- buffer,
- state,
- extra;
-
- Token = {
- BooleanLiteral: 1,
- EOF: 2,
- Identifier: 3,
- Keyword: 4,
- NullLiteral: 5,
- NumericLiteral: 6,
- Punctuator: 7,
- StringLiteral: 8
- };
-
- TokenName = {};
- TokenName[Token.BooleanLiteral] = 'Boolean';
- TokenName[Token.EOF] = '';
- TokenName[Token.Identifier] = 'Identifier';
- TokenName[Token.Keyword] = 'Keyword';
- TokenName[Token.NullLiteral] = 'Null';
- TokenName[Token.NumericLiteral] = 'Numeric';
- TokenName[Token.Punctuator] = 'Punctuator';
- TokenName[Token.StringLiteral] = 'String';
-
- Syntax = {
- AssignmentExpression: 'AssignmentExpression',
- ArrayExpression: 'ArrayExpression',
- BlockStatement: 'BlockStatement',
- BinaryExpression: 'BinaryExpression',
- BreakStatement: 'BreakStatement',
- CallExpression: 'CallExpression',
- CatchClause: 'CatchClause',
- ConditionalExpression: 'ConditionalExpression',
- ContinueStatement: 'ContinueStatement',
- DoWhileStatement: 'DoWhileStatement',
- DebuggerStatement: 'DebuggerStatement',
- EmptyStatement: 'EmptyStatement',
- ExpressionStatement: 'ExpressionStatement',
- ForStatement: 'ForStatement',
- ForInStatement: 'ForInStatement',
- FunctionDeclaration: 'FunctionDeclaration',
- FunctionExpression: 'FunctionExpression',
- Identifier: 'Identifier',
- IfStatement: 'IfStatement',
- Literal: 'Literal',
- LabeledStatement: 'LabeledStatement',
- LogicalExpression: 'LogicalExpression',
- MemberExpression: 'MemberExpression',
- NewExpression: 'NewExpression',
- ObjectExpression: 'ObjectExpression',
- Program: 'Program',
- Property: 'Property',
- ReturnStatement: 'ReturnStatement',
- SequenceExpression: 'SequenceExpression',
- SwitchStatement: 'SwitchStatement',
- SwitchCase: 'SwitchCase',
- ThisExpression: 'ThisExpression',
- ThrowStatement: 'ThrowStatement',
- TryStatement: 'TryStatement',
- UnaryExpression: 'UnaryExpression',
- UpdateExpression: 'UpdateExpression',
- VariableDeclaration: 'VariableDeclaration',
- VariableDeclarator: 'VariableDeclarator',
- WhileStatement: 'WhileStatement',
- WithStatement: 'WithStatement'
- };
-
- PropertyKind = {
- Data: 1,
- Get: 2,
- Set: 4
- };
-
- // Error messages should be identical to V8.
- Messages = {
- UnexpectedToken: 'Unexpected token %0',
- UnexpectedNumber: 'Unexpected number',
- UnexpectedString: 'Unexpected string',
- UnexpectedIdentifier: 'Unexpected identifier',
- UnexpectedReserved: 'Unexpected reserved word',
- UnexpectedEOS: 'Unexpected end of input',
- NewlineAfterThrow: 'Illegal newline after throw',
- InvalidRegExp: 'Invalid regular expression',
- UnterminatedRegExp: 'Invalid regular expression: missing /',
- InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
- InvalidLHSInForIn: 'Invalid left-hand side in for-in',
- NoCatchOrFinally: 'Missing catch or finally after try',
- UnknownLabel: 'Undefined label \'%0\'',
- Redeclaration: '%0 \'%1\' has already been declared',
- IllegalContinue: 'Illegal continue statement',
- IllegalBreak: 'Illegal break statement',
- IllegalReturn: 'Illegal return statement',
- StrictModeWith: 'Strict mode code may not include a with statement',
- StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
- StrictVarName: 'Variable name may not be eval or arguments in strict mode',
- StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
- StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
- StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
- StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
- StrictDelete: 'Delete of an unqualified identifier in strict mode.',
- StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
- AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
- AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
- StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
- StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
- StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
- StrictReservedWord: 'Use of future reserved word in strict mode'
- };
-
- // See also tools/generate-unicode-regex.py.
- Regex = {
- NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
- NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')
- };
-
- // Ensure the condition is true, otherwise throw an error.
- // This is only to have a better contract semantic, i.e. another safety net
- // to catch a logic error. The condition shall be fulfilled in normal case.
- // Do NOT use this to enforce a certain condition on any user input.
-
- function assert(condition, message) {
- if (!condition) {
- throw new Error('ASSERT: ' + message);
- }
- }
-
- function sliceSource(from, to) {
- return source.slice(from, to);
- }
-
- if (typeof 'esprima'[0] === 'undefined') {
- sliceSource = function sliceArraySource(from, to) {
- return source.slice(from, to).join('');
- };
- }
-
- function isDecimalDigit(ch) {
- return '0123456789'.indexOf(ch) >= 0;
- }
-
- function isHexDigit(ch) {
- return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
- }
-
- function isOctalDigit(ch) {
- return '01234567'.indexOf(ch) >= 0;
- }
-
-
- // 7.2 White Space
-
- function isWhiteSpace(ch) {
- return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') ||
- (ch === '\u000C') || (ch === '\u00A0') ||
- (ch.charCodeAt(0) >= 0x1680 &&
- '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0);
- }
-
- // 7.3 Line Terminators
-
- function isLineTerminator(ch) {
- return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
- }
-
- // 7.6 Identifier Names and Identifiers
-
- function isIdentifierStart(ch) {
- return (ch === '$') || (ch === '_') || (ch === '\\') ||
- (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
- ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch));
- }
-
- function isIdentifierPart(ch) {
- return (ch === '$') || (ch === '_') || (ch === '\\') ||
- (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
- ((ch >= '0') && (ch <= '9')) ||
- ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch));
- }
-
- // 7.6.1.2 Future Reserved Words
-
- function isFutureReservedWord(id) {
- switch (id) {
-
- // Future reserved words.
- case 'class':
- case 'enum':
- case 'export':
- case 'extends':
- case 'import':
- case 'super':
- return true;
- }
-
- return false;
- }
-
- function isStrictModeReservedWord(id) {
- switch (id) {
-
- // Strict Mode reserved words.
- case 'implements':
- case 'interface':
- case 'package':
- case 'private':
- case 'protected':
- case 'public':
- case 'static':
- case 'yield':
- case 'let':
- return true;
- }
-
- return false;
- }
-
- function isRestrictedWord(id) {
- return id === 'eval' || id === 'arguments';
- }
-
- // 7.6.1.1 Keywords
-
- function isKeyword(id) {
- var keyword = false;
- switch (id.length) {
- case 2:
- keyword = (id === 'if') || (id === 'in') || (id === 'do');
- break;
- case 3:
- keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
- break;
- case 4:
- keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with');
- break;
- case 5:
- keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw');
- break;
- case 6:
- keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch');
- break;
- case 7:
- keyword = (id === 'default') || (id === 'finally');
- break;
- case 8:
- keyword = (id === 'function') || (id === 'continue') || (id === 'debugger');
- break;
- case 10:
- keyword = (id === 'instanceof');
- break;
- }
-
- if (keyword) {
- return true;
- }
-
- switch (id) {
- // Future reserved words.
- // 'const' is specialized as Keyword in V8.
- case 'const':
- return true;
-
- // For compatiblity to SpiderMonkey and ES.next
- case 'yield':
- case 'let':
- return true;
- }
-
- if (strict && isStrictModeReservedWord(id)) {
- return true;
- }
-
- return isFutureReservedWord(id);
- }
-
- // Return the next character and move forward.
-
- function nextChar() {
- return source[index++];
- }
-
- // 7.4 Comments
-
- function skipComment() {
- var ch, blockComment, lineComment;
-
- blockComment = false;
- lineComment = false;
-
- while (index < length) {
- ch = source[index];
-
- if (lineComment) {
- ch = nextChar();
- if (isLineTerminator(ch)) {
- lineComment = false;
- if (ch === '\r' && source[index] === '\n') {
- ++index;
- }
- ++lineNumber;
- lineStart = index;
- }
- } else if (blockComment) {
- if (isLineTerminator(ch)) {
- if (ch === '\r' && source[index + 1] === '\n') {
- ++index;
- }
- ++lineNumber;
- ++index;
- lineStart = index;
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- } else {
- ch = nextChar();
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- if (ch === '*') {
- ch = source[index];
- if (ch === '/') {
- ++index;
- blockComment = false;
- }
- }
- }
- } else if (ch === '/') {
- ch = source[index + 1];
- if (ch === '/') {
- index += 2;
- lineComment = true;
- } else if (ch === '*') {
- index += 2;
- blockComment = true;
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- } else {
- break;
- }
- } else if (isWhiteSpace(ch)) {
- ++index;
- } else if (isLineTerminator(ch)) {
- ++index;
- if (ch === '\r' && source[index] === '\n') {
- ++index;
- }
- ++lineNumber;
- lineStart = index;
- } else {
- break;
- }
- }
- }
-
- function scanHexEscape(prefix) {
- var i, len, ch, code = 0;
-
- len = (prefix === 'u') ? 4 : 2;
- for (i = 0; i < len; ++i) {
- if (index < length && isHexDigit(source[index])) {
- ch = nextChar();
- code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
- } else {
- return '';
- }
- }
- return String.fromCharCode(code);
- }
-
- function scanIdentifier() {
- var ch, start, id, restore;
-
- ch = source[index];
- if (!isIdentifierStart(ch)) {
- return;
- }
-
- start = index;
- if (ch === '\\') {
- ++index;
- if (source[index] !== 'u') {
- return;
- }
- ++index;
- restore = index;
- ch = scanHexEscape('u');
- if (ch) {
- if (ch === '\\' || !isIdentifierStart(ch)) {
- return;
- }
- id = ch;
- } else {
- index = restore;
- id = 'u';
- }
- } else {
- id = nextChar();
- }
-
- while (index < length) {
- ch = source[index];
- if (!isIdentifierPart(ch)) {
- break;
- }
- if (ch === '\\') {
- ++index;
- if (source[index] !== 'u') {
- return;
- }
- ++index;
- restore = index;
- ch = scanHexEscape('u');
- if (ch) {
- if (ch === '\\' || !isIdentifierPart(ch)) {
- return;
- }
- id += ch;
- } else {
- index = restore;
- id += 'u';
- }
- } else {
- id += nextChar();
- }
- }
-
- // There is no keyword or literal with only one character.
- // Thus, it must be an identifier.
- if (id.length === 1) {
- return {
- type: Token.Identifier,
- value: id,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- if (isKeyword(id)) {
- return {
- type: Token.Keyword,
- value: id,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- // 7.8.1 Null Literals
-
- if (id === 'null') {
- return {
- type: Token.NullLiteral,
- value: id,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- // 7.8.2 Boolean Literals
-
- if (id === 'true' || id === 'false') {
- return {
- type: Token.BooleanLiteral,
- value: id,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- return {
- type: Token.Identifier,
- value: id,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- // 7.7 Punctuators
-
- function scanPunctuator() {
- var start = index,
- ch1 = source[index],
- ch2,
- ch3,
- ch4;
-
- // Check for most common single-character punctuators.
-
- if (ch1 === ';' || ch1 === '{' || ch1 === '}') {
- ++index;
- return {
- type: Token.Punctuator,
- value: ch1,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- if (ch1 === ',' || ch1 === '(' || ch1 === ')') {
- ++index;
- return {
- type: Token.Punctuator,
- value: ch1,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- // Dot (.) can also start a floating-point number, hence the need
- // to check the next character.
-
- ch2 = source[index + 1];
- if (ch1 === '.' && !isDecimalDigit(ch2)) {
- return {
- type: Token.Punctuator,
- value: nextChar(),
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- // Peek more characters.
-
- ch3 = source[index + 2];
- ch4 = source[index + 3];
-
- // 4-character punctuator: >>>=
-
- if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
- if (ch4 === '=') {
- index += 4;
- return {
- type: Token.Punctuator,
- value: '>>>=',
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
- }
-
- // 3-character punctuators: === !== >>> <<= >>=
-
- if (ch1 === '=' && ch2 === '=' && ch3 === '=') {
- index += 3;
- return {
- type: Token.Punctuator,
- value: '===',
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- if (ch1 === '!' && ch2 === '=' && ch3 === '=') {
- index += 3;
- return {
- type: Token.Punctuator,
- value: '!==',
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
- index += 3;
- return {
- type: Token.Punctuator,
- value: '>>>',
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
- index += 3;
- return {
- type: Token.Punctuator,
- value: '<<=',
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
- index += 3;
- return {
- type: Token.Punctuator,
- value: '>>=',
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- // 2-character punctuators: <= >= == != ++ -- << >> && ||
- // += -= *= %= &= |= ^= /=
-
- if (ch2 === '=') {
- if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
- index += 2;
- return {
- type: Token.Punctuator,
- value: ch1 + ch2,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
- }
-
- if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) {
- if ('+-<>&|'.indexOf(ch2) >= 0) {
- index += 2;
- return {
- type: Token.Punctuator,
- value: ch1 + ch2,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
- }
-
- // The remaining 1-character punctuators.
-
- if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) {
- return {
- type: Token.Punctuator,
- value: nextChar(),
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
- }
-
- // 7.8.3 Numeric Literals
-
- function scanNumericLiteral() {
- var number, start, ch;
-
- ch = source[index];
- assert(isDecimalDigit(ch) || (ch === '.'),
- 'Numeric literal must start with a decimal digit or a decimal point');
-
- start = index;
- number = '';
- if (ch !== '.') {
- number = nextChar();
- ch = source[index];
-
- // Hex number starts with '0x'.
- // Octal number starts with '0'.
- if (number === '0') {
- if (ch === 'x' || ch === 'X') {
- number += nextChar();
- while (index < length) {
- ch = source[index];
- if (!isHexDigit(ch)) {
- break;
- }
- number += nextChar();
- }
-
- if (number.length <= 2) {
- // only 0x
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
-
- if (index < length) {
- ch = source[index];
- if (isIdentifierStart(ch)) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- }
- return {
- type: Token.NumericLiteral,
- value: parseInt(number, 16),
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- } else if (isOctalDigit(ch)) {
- number += nextChar();
- while (index < length) {
- ch = source[index];
- if (!isOctalDigit(ch)) {
- break;
- }
- number += nextChar();
- }
-
- if (index < length) {
- ch = source[index];
- if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- }
- return {
- type: Token.NumericLiteral,
- value: parseInt(number, 8),
- octal: true,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- // decimal number starts with '0' such as '09' is illegal.
- if (isDecimalDigit(ch)) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- }
-
- while (index < length) {
- ch = source[index];
- if (!isDecimalDigit(ch)) {
- break;
- }
- number += nextChar();
- }
- }
-
- if (ch === '.') {
- number += nextChar();
- while (index < length) {
- ch = source[index];
- if (!isDecimalDigit(ch)) {
- break;
- }
- number += nextChar();
- }
- }
-
- if (ch === 'e' || ch === 'E') {
- number += nextChar();
-
- ch = source[index];
- if (ch === '+' || ch === '-') {
- number += nextChar();
- }
-
- ch = source[index];
- if (isDecimalDigit(ch)) {
- number += nextChar();
- while (index < length) {
- ch = source[index];
- if (!isDecimalDigit(ch)) {
- break;
- }
- number += nextChar();
- }
- } else {
- ch = 'character ' + ch;
- if (index >= length) {
- ch = '';
- }
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- }
-
- if (index < length) {
- ch = source[index];
- if (isIdentifierStart(ch)) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- }
-
- return {
- type: Token.NumericLiteral,
- value: parseFloat(number),
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- // 7.8.4 String Literals
-
- function scanStringLiteral() {
- var str = '', quote, start, ch, code, unescaped, restore, octal = false;
-
- quote = source[index];
- assert((quote === '\'' || quote === '"'),
- 'String literal must starts with a quote');
-
- start = index;
- ++index;
-
- while (index < length) {
- ch = nextChar();
-
- if (ch === quote) {
- quote = '';
- break;
- } else if (ch === '\\') {
- ch = nextChar();
- if (!isLineTerminator(ch)) {
- switch (ch) {
- case 'n':
- str += '\n';
- break;
- case 'r':
- str += '\r';
- break;
- case 't':
- str += '\t';
- break;
- case 'u':
- case 'x':
- restore = index;
- unescaped = scanHexEscape(ch);
- if (unescaped) {
- str += unescaped;
- } else {
- index = restore;
- str += ch;
- }
- break;
- case 'b':
- str += '\b';
- break;
- case 'f':
- str += '\f';
- break;
- case 'v':
- str += '\v';
- break;
-
- default:
- if (isOctalDigit(ch)) {
- code = '01234567'.indexOf(ch);
-
- // \0 is not octal escape sequence
- if (code !== 0) {
- octal = true;
- }
-
- if (index < length && isOctalDigit(source[index])) {
- octal = true;
- code = code * 8 + '01234567'.indexOf(nextChar());
-
- // 3 digits are only allowed when string starts
- // with 0, 1, 2, 3
- if ('0123'.indexOf(ch) >= 0 &&
- index < length &&
- isOctalDigit(source[index])) {
- code = code * 8 + '01234567'.indexOf(nextChar());
- }
- }
- str += String.fromCharCode(code);
- } else {
- str += ch;
- }
- break;
- }
- } else {
- ++lineNumber;
- if (ch === '\r' && source[index] === '\n') {
- ++index;
- }
- }
- } else if (isLineTerminator(ch)) {
- break;
- } else {
- str += ch;
- }
- }
-
- if (quote !== '') {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
-
- return {
- type: Token.StringLiteral,
- value: str,
- octal: octal,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [start, index]
- };
- }
-
- function scanRegExp() {
- var str = '', ch, start, pattern, flags, value, classMarker = false, restore;
-
- buffer = null;
- skipComment();
-
- start = index;
- ch = source[index];
- assert(ch === '/', 'Regular expression literal must start with a slash');
- str = nextChar();
-
- while (index < length) {
- ch = nextChar();
- str += ch;
- if (classMarker) {
- if (ch === ']') {
- classMarker = false;
- }
- } else {
- if (ch === '\\') {
- ch = nextChar();
- // ECMA-262 7.8.5
- if (isLineTerminator(ch)) {
- throwError({}, Messages.UnterminatedRegExp);
- }
- str += ch;
- } else if (ch === '/') {
- break;
- } else if (ch === '[') {
- classMarker = true;
- } else if (isLineTerminator(ch)) {
- throwError({}, Messages.UnterminatedRegExp);
- }
- }
- }
-
- if (str.length === 1) {
- throwError({}, Messages.UnterminatedRegExp);
- }
-
- // Exclude leading and trailing slash.
- pattern = str.substr(1, str.length - 2);
-
- flags = '';
- while (index < length) {
- ch = source[index];
- if (!isIdentifierPart(ch)) {
- break;
- }
-
- ++index;
- if (ch === '\\' && index < length) {
- ch = source[index];
- if (ch === 'u') {
- ++index;
- restore = index;
- ch = scanHexEscape('u');
- if (ch) {
- flags += ch;
- str += '\\u';
- for (; restore < index; ++restore) {
- str += source[restore];
- }
- } else {
- index = restore;
- flags += 'u';
- str += '\\u';
- }
- } else {
- str += '\\';
- }
- } else {
- flags += ch;
- str += ch;
- }
- }
-
- try {
- value = new RegExp(pattern, flags);
- } catch (e) {
- throwError({}, Messages.InvalidRegExp);
- }
-
- return {
- literal: str,
- value: value,
- range: [start, index]
- };
- }
-
- function isIdentifierName(token) {
- return token.type === Token.Identifier ||
- token.type === Token.Keyword ||
- token.type === Token.BooleanLiteral ||
- token.type === Token.NullLiteral;
- }
-
- function advance() {
- var ch, token;
-
- skipComment();
-
- if (index >= length) {
- return {
- type: Token.EOF,
- lineNumber: lineNumber,
- lineStart: lineStart,
- range: [index, index]
- };
- }
-
- token = scanPunctuator();
- if (typeof token !== 'undefined') {
- return token;
- }
-
- ch = source[index];
-
- if (ch === '\'' || ch === '"') {
- return scanStringLiteral();
- }
-
- if (ch === '.' || isDecimalDigit(ch)) {
- return scanNumericLiteral();
- }
-
- token = scanIdentifier();
- if (typeof token !== 'undefined') {
- return token;
- }
-
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
-
- function lex() {
- var token;
-
- if (buffer) {
- index = buffer.range[1];
- lineNumber = buffer.lineNumber;
- lineStart = buffer.lineStart;
- token = buffer;
- buffer = null;
- return token;
- }
-
- buffer = null;
- return advance();
- }
-
- function lookahead() {
- var pos, line, start;
-
- if (buffer !== null) {
- return buffer;
- }
-
- pos = index;
- line = lineNumber;
- start = lineStart;
- buffer = advance();
- index = pos;
- lineNumber = line;
- lineStart = start;
-
- return buffer;
- }
-
- // Return true if there is a line terminator before the next token.
-
- function peekLineTerminator() {
- var pos, line, start, found;
-
- pos = index;
- line = lineNumber;
- start = lineStart;
- skipComment();
- found = lineNumber !== line;
- index = pos;
- lineNumber = line;
- lineStart = start;
-
- return found;
- }
-
- // Throw an exception
-
- function throwError(token, messageFormat) {
- var error,
- args = Array.prototype.slice.call(arguments, 2),
- msg = messageFormat.replace(
- /%(\d)/g,
- function (whole, index) {
- return args[index] || '';
- }
- );
-
- if (typeof token.lineNumber === 'number') {
- error = new Error('Line ' + token.lineNumber + ': ' + msg);
- error.index = token.range[0];
- error.lineNumber = token.lineNumber;
- error.column = token.range[0] - lineStart + 1;
- } else {
- error = new Error('Line ' + lineNumber + ': ' + msg);
- error.index = index;
- error.lineNumber = lineNumber;
- error.column = index - lineStart + 1;
- }
-
- throw error;
- }
-
- function throwErrorTolerant() {
- var error;
- try {
- throwError.apply(null, arguments);
- } catch (e) {
- if (extra.errors) {
- extra.errors.push(e);
- } else {
- throw e;
- }
- }
- }
-
-
- // Throw an exception because of the token.
-
- function throwUnexpected(token) {
- var s;
-
- if (token.type === Token.EOF) {
- throwError(token, Messages.UnexpectedEOS);
- }
-
- if (token.type === Token.NumericLiteral) {
- throwError(token, Messages.UnexpectedNumber);
- }
-
- if (token.type === Token.StringLiteral) {
- throwError(token, Messages.UnexpectedString);
- }
-
- if (token.type === Token.Identifier) {
- throwError(token, Messages.UnexpectedIdentifier);
- }
-
- if (token.type === Token.Keyword) {
- if (isFutureReservedWord(token.value)) {
- throwError(token, Messages.UnexpectedReserved);
- } else if (strict && isStrictModeReservedWord(token.value)) {
- throwError(token, Messages.StrictReservedWord);
- }
- throwError(token, Messages.UnexpectedToken, token.value);
- }
-
- // BooleanLiteral, NullLiteral, or Punctuator.
- throwError(token, Messages.UnexpectedToken, token.value);
- }
-
- // Expect the next token to match the specified punctuator.
- // If not, an exception will be thrown.
-
- function expect(value) {
- var token = lex();
- if (token.type !== Token.Punctuator || token.value !== value) {
- throwUnexpected(token);
- }
- }
-
- // Expect the next token to match the specified keyword.
- // If not, an exception will be thrown.
-
- function expectKeyword(keyword) {
- var token = lex();
- if (token.type !== Token.Keyword || token.value !== keyword) {
- throwUnexpected(token);
- }
- }
-
- // Return true if the next token matches the specified punctuator.
-
- function match(value) {
- var token = lookahead();
- return token.type === Token.Punctuator && token.value === value;
- }
-
- // Return true if the next token matches the specified keyword
-
- function matchKeyword(keyword) {
- var token = lookahead();
- return token.type === Token.Keyword && token.value === keyword;
- }
-
- // Return true if the next token is an assignment operator
-
- function matchAssign() {
- var token = lookahead(),
- op = token.value;
-
- if (token.type !== Token.Punctuator) {
- return false;
- }
- return op === '=' ||
- op === '*=' ||
- op === '/=' ||
- op === '%=' ||
- op === '+=' ||
- op === '-=' ||
- op === '<<=' ||
- op === '>>=' ||
- op === '>>>=' ||
- op === '&=' ||
- op === '^=' ||
- op === '|=';
- }
-
- function consumeSemicolon() {
- var token, line;
-
- // Catch the very common case first.
- if (source[index] === ';') {
- lex();
- return;
- }
-
- line = lineNumber;
- skipComment();
- if (lineNumber !== line) {
- return;
- }
-
- if (match(';')) {
- lex();
- return;
- }
-
- token = lookahead();
- if (token.type !== Token.EOF && !match('}')) {
- throwUnexpected(token);
- }
- return;
- }
-
- // Return true if provided expression is LeftHandSideExpression
-
- function isLeftHandSide(expr) {
- return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
- }
-
- // 11.1.4 Array Initialiser
-
- function parseArrayInitialiser() {
- var elements = [],
- undef;
-
- expect('[');
-
- while (!match(']')) {
- if (match(',')) {
- lex();
- elements.push(undef);
- } else {
- elements.push(parseAssignmentExpression());
-
- if (!match(']')) {
- expect(',');
- }
- }
- }
-
- expect(']');
-
- return {
- type: Syntax.ArrayExpression,
- elements: elements
- };
- }
-
- // 11.1.5 Object Initialiser
-
- function parsePropertyFunction(param, first) {
- var previousStrict, body;
-
- previousStrict = strict;
- body = parseFunctionSourceElements();
- if (first && strict && isRestrictedWord(param[0].name)) {
- throwError(first, Messages.StrictParamName);
- }
- strict = previousStrict;
-
- return {
- type: Syntax.FunctionExpression,
- id: null,
- params: param,
- body: body
- };
- }
-
- function parseObjectPropertyKey() {
- var token = lex();
-
- // Note: This function is called only from parseObjectProperty(), where
- // EOF and Punctuator tokens are already filtered out.
-
- if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
- if (strict && token.octal) {
- throwError(token, Messages.StrictOctalLiteral);
- }
- return createLiteral(token);
- }
-
- return {
- type: Syntax.Identifier,
- name: token.value
- };
- }
-
- function parseObjectProperty() {
- var token, key, id, param;
-
- token = lookahead();
-
- if (token.type === Token.Identifier) {
-
- id = parseObjectPropertyKey();
-
- // Property Assignment: Getter and Setter.
-
- if (token.value === 'get' && !match(':')) {
- key = parseObjectPropertyKey();
- expect('(');
- expect(')');
- return {
- type: Syntax.Property,
- key: key,
- value: parsePropertyFunction([]),
- kind: 'get'
- };
- } else if (token.value === 'set' && !match(':')) {
- key = parseObjectPropertyKey();
- expect('(');
- token = lookahead();
- if (token.type !== Token.Identifier) {
- throwUnexpected(lex());
- }
- param = [ parseVariableIdentifier() ];
- expect(')');
- return {
- type: Syntax.Property,
- key: key,
- value: parsePropertyFunction(param, token),
- kind: 'set'
- };
- } else {
- expect(':');
- return {
- type: Syntax.Property,
- key: id,
- value: parseAssignmentExpression(),
- kind: 'init'
- };
- }
- } else if (token.type === Token.EOF || token.type === Token.Punctuator) {
- throwUnexpected(token);
- } else {
- key = parseObjectPropertyKey();
- expect(':');
- return {
- type: Syntax.Property,
- key: key,
- value: parseAssignmentExpression(),
- kind: 'init'
- };
- }
- }
-
- function parseObjectInitialiser() {
- var token, properties = [], property, name, kind, map = {}, toString = String;
-
- expect('{');
-
- while (!match('}')) {
- property = parseObjectProperty();
-
- if (property.key.type === Syntax.Identifier) {
- name = property.key.name;
- } else {
- name = toString(property.key.value);
- }
- kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
- if (Object.prototype.hasOwnProperty.call(map, name)) {
- if (map[name] === PropertyKind.Data) {
- if (strict && kind === PropertyKind.Data) {
- throwErrorTolerant({}, Messages.StrictDuplicateProperty);
- } else if (kind !== PropertyKind.Data) {
- throwError({}, Messages.AccessorDataProperty);
- }
- } else {
- if (kind === PropertyKind.Data) {
- throwError({}, Messages.AccessorDataProperty);
- } else if (map[name] & kind) {
- throwError({}, Messages.AccessorGetSet);
- }
- }
- map[name] |= kind;
- } else {
- map[name] = kind;
- }
-
- properties.push(property);
-
- if (!match('}')) {
- expect(',');
- }
- }
-
- expect('}');
-
- return {
- type: Syntax.ObjectExpression,
- properties: properties
- };
- }
-
- // 11.1 Primary Expressions
-
- function parsePrimaryExpression() {
- var expr,
- token = lookahead(),
- type = token.type;
-
- if (type === Token.Identifier) {
- return {
- type: Syntax.Identifier,
- name: lex().value
- };
- }
-
- if (type === Token.StringLiteral || type === Token.NumericLiteral) {
- if (strict && token.octal) {
- throwErrorTolerant(token, Messages.StrictOctalLiteral);
- }
- return createLiteral(lex());
- }
-
- if (type === Token.Keyword) {
- if (matchKeyword('this')) {
- lex();
- return {
- type: Syntax.ThisExpression
- };
- }
-
- if (matchKeyword('function')) {
- return parseFunctionExpression();
- }
- }
-
- if (type === Token.BooleanLiteral) {
- lex();
- token.value = (token.value === 'true');
- return createLiteral(token);
- }
-
- if (type === Token.NullLiteral) {
- lex();
- token.value = null;
- return createLiteral(token);
- }
-
- if (match('[')) {
- return parseArrayInitialiser();
- }
-
- if (match('{')) {
- return parseObjectInitialiser();
- }
-
- if (match('(')) {
- lex();
- state.lastParenthesized = expr = parseExpression();
- expect(')');
- return expr;
- }
-
- if (match('/') || match('/=')) {
- return createLiteral(scanRegExp());
- }
-
- return throwUnexpected(lex());
- }
-
- // 11.2 Left-Hand-Side Expressions
-
- function parseArguments() {
- var args = [];
-
- expect('(');
-
- if (!match(')')) {
- while (index < length) {
- args.push(parseAssignmentExpression());
- if (match(')')) {
- break;
- }
- expect(',');
- }
- }
-
- expect(')');
-
- return args;
- }
-
- function parseNonComputedProperty() {
- var token = lex();
-
- if (!isIdentifierName(token)) {
- throwUnexpected(token);
- }
-
- return {
- type: Syntax.Identifier,
- name: token.value
- };
- }
-
- function parseNonComputedMember(object) {
- return {
- type: Syntax.MemberExpression,
- computed: false,
- object: object,
- property: parseNonComputedProperty()
- };
- }
-
- function parseComputedMember(object) {
- var property, expr;
-
- expect('[');
- property = parseExpression();
- expr = {
- type: Syntax.MemberExpression,
- computed: true,
- object: object,
- property: property
- };
- expect(']');
- return expr;
- }
-
- function parseCallMember(object) {
- return {
- type: Syntax.CallExpression,
- callee: object,
- 'arguments': parseArguments()
- };
- }
-
- function parseNewExpression() {
- var expr;
-
- expectKeyword('new');
-
- expr = {
- type: Syntax.NewExpression,
- callee: parseLeftHandSideExpression(),
- 'arguments': []
- };
-
- if (match('(')) {
- expr['arguments'] = parseArguments();
- }
-
- return expr;
- }
-
- function parseLeftHandSideExpressionAllowCall() {
- var useNew, expr;
-
- useNew = matchKeyword('new');
- expr = useNew ? parseNewExpression() : parsePrimaryExpression();
-
- while (index < length) {
- if (match('.')) {
- lex();
- expr = parseNonComputedMember(expr);
- } else if (match('[')) {
- expr = parseComputedMember(expr);
- } else if (match('(')) {
- expr = parseCallMember(expr);
- } else {
- break;
- }
- }
-
- return expr;
- }
-
- function parseLeftHandSideExpression() {
- var useNew, expr;
-
- useNew = matchKeyword('new');
- expr = useNew ? parseNewExpression() : parsePrimaryExpression();
-
- while (index < length) {
- if (match('.')) {
- lex();
- expr = parseNonComputedMember(expr);
- } else if (match('[')) {
- expr = parseComputedMember(expr);
- } else {
- break;
- }
- }
-
- return expr;
- }
-
- // 11.3 Postfix Expressions
-
- function parsePostfixExpression() {
- var expr = parseLeftHandSideExpressionAllowCall();
-
- if ((match('++') || match('--')) && !peekLineTerminator()) {
- // 11.3.1, 11.3.2
- if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
- throwError({}, Messages.StrictLHSPostfix);
- }
-
- if (!isLeftHandSide(expr)) {
- throwError({}, Messages.InvalidLHSInAssignment);
- }
-
- expr = {
- type: Syntax.UpdateExpression,
- operator: lex().value,
- argument: expr,
- prefix: false
- };
- }
-
- return expr;
- }
-
- // 11.4 Unary Operators
-
- function parseUnaryExpression() {
- var token, expr;
-
- if (match('++') || match('--')) {
- token = lex();
- expr = parseUnaryExpression();
- // 11.4.4, 11.4.5
- if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
- throwError({}, Messages.StrictLHSPrefix);
- }
-
- if (!isLeftHandSide(expr)) {
- throwError({}, Messages.InvalidLHSInAssignment);
- }
-
- expr = {
- type: Syntax.UpdateExpression,
- operator: token.value,
- argument: expr,
- prefix: true
- };
- return expr;
- }
-
- if (match('+') || match('-') || match('~') || match('!')) {
- expr = {
- type: Syntax.UnaryExpression,
- operator: lex().value,
- argument: parseUnaryExpression()
- };
- return expr;
- }
-
- if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
- expr = {
- type: Syntax.UnaryExpression,
- operator: lex().value,
- argument: parseUnaryExpression()
- };
- if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
- throwErrorTolerant({}, Messages.StrictDelete);
- }
- return expr;
- }
-
- return parsePostfixExpression();
- }
-
- // 11.5 Multiplicative Operators
-
- function parseMultiplicativeExpression() {
- var expr = parseUnaryExpression();
-
- while (match('*') || match('/') || match('%')) {
- expr = {
- type: Syntax.BinaryExpression,
- operator: lex().value,
- left: expr,
- right: parseUnaryExpression()
- };
- }
-
- return expr;
- }
-
- // 11.6 Additive Operators
-
- function parseAdditiveExpression() {
- var expr = parseMultiplicativeExpression();
-
- while (match('+') || match('-')) {
- expr = {
- type: Syntax.BinaryExpression,
- operator: lex().value,
- left: expr,
- right: parseMultiplicativeExpression()
- };
- }
-
- return expr;
- }
-
- // 11.7 Bitwise Shift Operators
-
- function parseShiftExpression() {
- var expr = parseAdditiveExpression();
-
- while (match('<<') || match('>>') || match('>>>')) {
- expr = {
- type: Syntax.BinaryExpression,
- operator: lex().value,
- left: expr,
- right: parseAdditiveExpression()
- };
- }
-
- return expr;
- }
- // 11.8 Relational Operators
-
- function parseRelationalExpression() {
- var expr, previousAllowIn;
-
- previousAllowIn = state.allowIn;
- state.allowIn = true;
-
- expr = parseShiftExpression();
-
- while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) {
- expr = {
- type: Syntax.BinaryExpression,
- operator: lex().value,
- left: expr,
- right: parseShiftExpression()
- };
- }
-
- state.allowIn = previousAllowIn;
- return expr;
- }
-
- // 11.9 Equality Operators
-
- function parseEqualityExpression() {
- var expr = parseRelationalExpression();
-
- while (match('==') || match('!=') || match('===') || match('!==')) {
- expr = {
- type: Syntax.BinaryExpression,
- operator: lex().value,
- left: expr,
- right: parseRelationalExpression()
- };
- }
-
- return expr;
- }
-
- // 11.10 Binary Bitwise Operators
-
- function parseBitwiseANDExpression() {
- var expr = parseEqualityExpression();
-
- while (match('&')) {
- lex();
- expr = {
- type: Syntax.BinaryExpression,
- operator: '&',
- left: expr,
- right: parseEqualityExpression()
- };
- }
-
- return expr;
- }
-
- function parseBitwiseXORExpression() {
- var expr = parseBitwiseANDExpression();
-
- while (match('^')) {
- lex();
- expr = {
- type: Syntax.BinaryExpression,
- operator: '^',
- left: expr,
- right: parseBitwiseANDExpression()
- };
- }
-
- return expr;
- }
-
- function parseBitwiseORExpression() {
- var expr = parseBitwiseXORExpression();
-
- while (match('|')) {
- lex();
- expr = {
- type: Syntax.BinaryExpression,
- operator: '|',
- left: expr,
- right: parseBitwiseXORExpression()
- };
- }
-
- return expr;
- }
-
- // 11.11 Binary Logical Operators
-
- function parseLogicalANDExpression() {
- var expr = parseBitwiseORExpression();
-
- while (match('&&')) {
- lex();
- expr = {
- type: Syntax.LogicalExpression,
- operator: '&&',
- left: expr,
- right: parseBitwiseORExpression()
- };
- }
-
- return expr;
- }
-
- function parseLogicalORExpression() {
- var expr = parseLogicalANDExpression();
-
- while (match('||')) {
- lex();
- expr = {
- type: Syntax.LogicalExpression,
- operator: '||',
- left: expr,
- right: parseLogicalANDExpression()
- };
- }
-
- return expr;
- }
-
- // 11.12 Conditional Operator
-
- function parseConditionalExpression() {
- var expr, previousAllowIn, consequent;
-
- expr = parseLogicalORExpression();
-
- if (match('?')) {
- lex();
- previousAllowIn = state.allowIn;
- state.allowIn = true;
- consequent = parseAssignmentExpression();
- state.allowIn = previousAllowIn;
- expect(':');
-
- expr = {
- type: Syntax.ConditionalExpression,
- test: expr,
- consequent: consequent,
- alternate: parseAssignmentExpression()
- };
- }
-
- return expr;
- }
-
- // 11.13 Assignment Operators
-
- function parseAssignmentExpression() {
- var expr;
-
- expr = parseConditionalExpression();
-
- if (matchAssign()) {
- // LeftHandSideExpression
- if (!isLeftHandSide(expr)) {
- throwError({}, Messages.InvalidLHSInAssignment);
- }
-
- // 11.13.1
- if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
- throwError({}, Messages.StrictLHSAssignment);
- }
-
- expr = {
- type: Syntax.AssignmentExpression,
- operator: lex().value,
- left: expr,
- right: parseAssignmentExpression()
- };
- }
-
- return expr;
- }
-
- // 11.14 Comma Operator
-
- function parseExpression() {
- var expr = parseAssignmentExpression();
-
- if (match(',')) {
- expr = {
- type: Syntax.SequenceExpression,
- expressions: [ expr ]
- };
-
- while (index < length) {
- if (!match(',')) {
- break;
- }
- lex();
- expr.expressions.push(parseAssignmentExpression());
- }
-
- }
- return expr;
- }
-
- // 12.1 Block
-
- function parseStatementList() {
- var list = [],
- statement;
-
- while (index < length) {
- if (match('}')) {
- break;
- }
- statement = parseSourceElement();
- if (typeof statement === 'undefined') {
- break;
- }
- list.push(statement);
- }
-
- return list;
- }
-
- function parseBlock() {
- var block;
-
- expect('{');
-
- block = parseStatementList();
-
- expect('}');
-
- return {
- type: Syntax.BlockStatement,
- body: block
- };
- }
-
- // 12.2 Variable Statement
-
- function parseVariableIdentifier() {
- var token = lex();
-
- if (token.type !== Token.Identifier) {
- throwUnexpected(token);
- }
-
- return {
- type: Syntax.Identifier,
- name: token.value
- };
- }
-
- function parseVariableDeclaration(kind) {
- var id = parseVariableIdentifier(),
- init = null;
-
- // 12.2.1
- if (strict && isRestrictedWord(id.name)) {
- throwErrorTolerant({}, Messages.StrictVarName);
- }
-
- if (kind === 'const') {
- expect('=');
- init = parseAssignmentExpression();
- } else if (match('=')) {
- lex();
- init = parseAssignmentExpression();
- }
-
- return {
- type: Syntax.VariableDeclarator,
- id: id,
- init: init
- };
- }
-
- function parseVariableDeclarationList(kind) {
- var list = [];
-
- while (index < length) {
- list.push(parseVariableDeclaration(kind));
- if (!match(',')) {
- break;
- }
- lex();
- }
-
- return list;
- }
-
- function parseVariableStatement() {
- var declarations;
-
- expectKeyword('var');
-
- declarations = parseVariableDeclarationList();
-
- consumeSemicolon();
-
- return {
- type: Syntax.VariableDeclaration,
- declarations: declarations,
- kind: 'var'
- };
- }
-
- // kind may be `const` or `let`
- // Both are experimental and not in the specification yet.
- // see http://wiki.ecmascript.org/doku.php?id=harmony:const
- // and http://wiki.ecmascript.org/doku.php?id=harmony:let
- function parseConstLetDeclaration(kind) {
- var declarations;
-
- expectKeyword(kind);
-
- declarations = parseVariableDeclarationList(kind);
-
- consumeSemicolon();
-
- return {
- type: Syntax.VariableDeclaration,
- declarations: declarations,
- kind: kind
- };
- }
-
- // 12.3 Empty Statement
-
- function parseEmptyStatement() {
- expect(';');
-
- return {
- type: Syntax.EmptyStatement
- };
- }
-
- // 12.4 Expression Statement
-
- function parseExpressionStatement() {
- var expr = parseExpression();
-
- consumeSemicolon();
-
- return {
- type: Syntax.ExpressionStatement,
- expression: expr
- };
- }
-
- // 12.5 If statement
-
- function parseIfStatement() {
- var test, consequent, alternate;
-
- expectKeyword('if');
-
- expect('(');
-
- test = parseExpression();
-
- expect(')');
-
- consequent = parseStatement();
-
- if (matchKeyword('else')) {
- lex();
- alternate = parseStatement();
- } else {
- alternate = null;
- }
-
- return {
- type: Syntax.IfStatement,
- test: test,
- consequent: consequent,
- alternate: alternate
- };
- }
-
- // 12.6 Iteration Statements
-
- function parseDoWhileStatement() {
- var body, test, oldInIteration;
-
- expectKeyword('do');
-
- oldInIteration = state.inIteration;
- state.inIteration = true;
-
- body = parseStatement();
-
- state.inIteration = oldInIteration;
-
- expectKeyword('while');
-
- expect('(');
-
- test = parseExpression();
-
- expect(')');
-
- if (match(';')) {
- lex();
- }
-
- return {
- type: Syntax.DoWhileStatement,
- body: body,
- test: test
- };
- }
-
- function parseWhileStatement() {
- var test, body, oldInIteration;
-
- expectKeyword('while');
-
- expect('(');
-
- test = parseExpression();
-
- expect(')');
-
- oldInIteration = state.inIteration;
- state.inIteration = true;
-
- body = parseStatement();
-
- state.inIteration = oldInIteration;
-
- return {
- type: Syntax.WhileStatement,
- test: test,
- body: body
- };
- }
-
- function parseForVariableDeclaration() {
- var token = lex();
-
- return {
- type: Syntax.VariableDeclaration,
- declarations: parseVariableDeclarationList(),
- kind: token.value
- };
- }
-
- function parseForStatement() {
- var init, test, update, left, right, body, oldInIteration;
-
- init = test = update = null;
-
- expectKeyword('for');
-
- expect('(');
-
- if (match(';')) {
- lex();
- } else {
- if (matchKeyword('var') || matchKeyword('let')) {
- state.allowIn = false;
- init = parseForVariableDeclaration();
- state.allowIn = true;
-
- if (init.declarations.length === 1 && matchKeyword('in')) {
- lex();
- left = init;
- right = parseExpression();
- init = null;
- }
- } else {
- state.allowIn = false;
- init = parseExpression();
- state.allowIn = true;
-
- if (matchKeyword('in')) {
- // LeftHandSideExpression
- if (!isLeftHandSide(init)) {
- throwError({}, Messages.InvalidLHSInForIn);
- }
-
- lex();
- left = init;
- right = parseExpression();
- init = null;
- }
- }
-
- if (typeof left === 'undefined') {
- expect(';');
- }
- }
-
- if (typeof left === 'undefined') {
-
- if (!match(';')) {
- test = parseExpression();
- }
- expect(';');
-
- if (!match(')')) {
- update = parseExpression();
- }
- }
-
- expect(')');
-
- oldInIteration = state.inIteration;
- state.inIteration = true;
-
- body = parseStatement();
-
- state.inIteration = oldInIteration;
-
- if (typeof left === 'undefined') {
- return {
- type: Syntax.ForStatement,
- init: init,
- test: test,
- update: update,
- body: body
- };
- }
-
- return {
- type: Syntax.ForInStatement,
- left: left,
- right: right,
- body: body,
- each: false
- };
- }
-
- // 12.7 The continue statement
-
- function parseContinueStatement() {
- var token, label = null;
-
- expectKeyword('continue');
-
- // Optimize the most common form: 'continue;'.
- if (source[index] === ';') {
- lex();
-
- if (!state.inIteration) {
- throwError({}, Messages.IllegalContinue);
- }
-
- return {
- type: Syntax.ContinueStatement,
- label: null
- };
- }
-
- if (peekLineTerminator()) {
- if (!state.inIteration) {
- throwError({}, Messages.IllegalContinue);
- }
-
- return {
- type: Syntax.ContinueStatement,
- label: null
- };
- }
-
- token = lookahead();
- if (token.type === Token.Identifier) {
- label = parseVariableIdentifier();
-
- if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
- throwError({}, Messages.UnknownLabel, label.name);
- }
- }
-
- consumeSemicolon();
-
- if (label === null && !state.inIteration) {
- throwError({}, Messages.IllegalContinue);
- }
-
- return {
- type: Syntax.ContinueStatement,
- label: label
- };
- }
-
- // 12.8 The break statement
-
- function parseBreakStatement() {
- var token, label = null;
-
- expectKeyword('break');
-
- // Optimize the most common form: 'break;'.
- if (source[index] === ';') {
- lex();
-
- if (!(state.inIteration || state.inSwitch)) {
- throwError({}, Messages.IllegalBreak);
- }
-
- return {
- type: Syntax.BreakStatement,
- label: null
- };
- }
-
- if (peekLineTerminator()) {
- if (!(state.inIteration || state.inSwitch)) {
- throwError({}, Messages.IllegalBreak);
- }
-
- return {
- type: Syntax.BreakStatement,
- label: null
- };
- }
-
- token = lookahead();
- if (token.type === Token.Identifier) {
- label = parseVariableIdentifier();
-
- if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
- throwError({}, Messages.UnknownLabel, label.name);
- }
- }
-
- consumeSemicolon();
-
- if (label === null && !(state.inIteration || state.inSwitch)) {
- throwError({}, Messages.IllegalBreak);
- }
-
- return {
- type: Syntax.BreakStatement,
- label: label
- };
- }
-
- // 12.9 The return statement
-
- function parseReturnStatement() {
- var token, argument = null;
-
- expectKeyword('return');
-
- if (!state.inFunctionBody) {
- throwErrorTolerant({}, Messages.IllegalReturn);
- }
-
- // 'return' followed by a space and an identifier is very common.
- if (source[index] === ' ') {
- if (isIdentifierStart(source[index + 1])) {
- argument = parseExpression();
- consumeSemicolon();
- return {
- type: Syntax.ReturnStatement,
- argument: argument
- };
- }
- }
-
- if (peekLineTerminator()) {
- return {
- type: Syntax.ReturnStatement,
- argument: null
- };
- }
-
- if (!match(';')) {
- token = lookahead();
- if (!match('}') && token.type !== Token.EOF) {
- argument = parseExpression();
- }
- }
-
- consumeSemicolon();
-
- return {
- type: Syntax.ReturnStatement,
- argument: argument
- };
- }
-
- // 12.10 The with statement
-
- function parseWithStatement() {
- var object, body;
-
- if (strict) {
- throwErrorTolerant({}, Messages.StrictModeWith);
- }
-
- expectKeyword('with');
-
- expect('(');
-
- object = parseExpression();
-
- expect(')');
-
- body = parseStatement();
-
- return {
- type: Syntax.WithStatement,
- object: object,
- body: body
- };
- }
-
- // 12.10 The swith statement
-
- function parseSwitchCase() {
- var test,
- consequent = [],
- statement;
-
- if (matchKeyword('default')) {
- lex();
- test = null;
- } else {
- expectKeyword('case');
- test = parseExpression();
- }
- expect(':');
-
- while (index < length) {
- if (match('}') || matchKeyword('default') || matchKeyword('case')) {
- break;
- }
- statement = parseStatement();
- if (typeof statement === 'undefined') {
- break;
- }
- consequent.push(statement);
- }
-
- return {
- type: Syntax.SwitchCase,
- test: test,
- consequent: consequent
- };
- }
-
- function parseSwitchStatement() {
- var discriminant, cases, oldInSwitch;
-
- expectKeyword('switch');
-
- expect('(');
-
- discriminant = parseExpression();
-
- expect(')');
-
- expect('{');
-
- if (match('}')) {
- lex();
- return {
- type: Syntax.SwitchStatement,
- discriminant: discriminant
- };
- }
-
- cases = [];
-
- oldInSwitch = state.inSwitch;
- state.inSwitch = true;
-
- while (index < length) {
- if (match('}')) {
- break;
- }
- cases.push(parseSwitchCase());
- }
-
- state.inSwitch = oldInSwitch;
-
- expect('}');
-
- return {
- type: Syntax.SwitchStatement,
- discriminant: discriminant,
- cases: cases
- };
- }
-
- // 12.13 The throw statement
-
- function parseThrowStatement() {
- var argument;
-
- expectKeyword('throw');
-
- if (peekLineTerminator()) {
- throwError({}, Messages.NewlineAfterThrow);
- }
-
- argument = parseExpression();
-
- consumeSemicolon();
-
- return {
- type: Syntax.ThrowStatement,
- argument: argument
- };
- }
-
- // 12.14 The try statement
-
- function parseCatchClause() {
- var param;
-
- expectKeyword('catch');
-
- expect('(');
- if (!match(')')) {
- param = parseExpression();
- // 12.14.1
- if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
- throwErrorTolerant({}, Messages.StrictCatchVariable);
- }
- }
- expect(')');
-
- return {
- type: Syntax.CatchClause,
- param: param,
- guard: null,
- body: parseBlock()
- };
- }
-
- function parseTryStatement() {
- var block, handlers = [], finalizer = null;
-
- expectKeyword('try');
-
- block = parseBlock();
-
- if (matchKeyword('catch')) {
- handlers.push(parseCatchClause());
- }
-
- if (matchKeyword('finally')) {
- lex();
- finalizer = parseBlock();
- }
-
- if (handlers.length === 0 && !finalizer) {
- throwError({}, Messages.NoCatchOrFinally);
- }
-
- return {
- type: Syntax.TryStatement,
- block: block,
- handlers: handlers,
- finalizer: finalizer
- };
- }
-
- // 12.15 The debugger statement
-
- function parseDebuggerStatement() {
- expectKeyword('debugger');
-
- consumeSemicolon();
-
- return {
- type: Syntax.DebuggerStatement
- };
- }
-
- // 12 Statements
-
- function parseStatement() {
- var token = lookahead(),
- expr,
- labeledBody;
-
- if (token.type === Token.EOF) {
- throwUnexpected(token);
- }
-
- if (token.type === Token.Punctuator) {
- switch (token.value) {
- case ';':
- return parseEmptyStatement();
- case '{':
- return parseBlock();
- case '(':
- return parseExpressionStatement();
- default:
- break;
- }
- }
-
- if (token.type === Token.Keyword) {
- switch (token.value) {
- case 'break':
- return parseBreakStatement();
- case 'continue':
- return parseContinueStatement();
- case 'debugger':
- return parseDebuggerStatement();
- case 'do':
- return parseDoWhileStatement();
- case 'for':
- return parseForStatement();
- case 'function':
- return parseFunctionDeclaration();
- case 'if':
- return parseIfStatement();
- case 'return':
- return parseReturnStatement();
- case 'switch':
- return parseSwitchStatement();
- case 'throw':
- return parseThrowStatement();
- case 'try':
- return parseTryStatement();
- case 'var':
- return parseVariableStatement();
- case 'while':
- return parseWhileStatement();
- case 'with':
- return parseWithStatement();
- default:
- break;
- }
- }
-
- expr = parseExpression();
-
- // 12.12 Labelled Statements
- if ((expr.type === Syntax.Identifier) && match(':')) {
- lex();
-
- if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) {
- throwError({}, Messages.Redeclaration, 'Label', expr.name);
- }
-
- state.labelSet[expr.name] = true;
- labeledBody = parseStatement();
- delete state.labelSet[expr.name];
-
- return {
- type: Syntax.LabeledStatement,
- label: expr,
- body: labeledBody
- };
- }
-
- consumeSemicolon();
-
- return {
- type: Syntax.ExpressionStatement,
- expression: expr
- };
- }
-
- // 13 Function Definition
-
- function parseFunctionSourceElements() {
- var sourceElement, sourceElements = [], token, directive, firstRestricted,
- oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody;
-
- expect('{');
-
- while (index < length) {
- token = lookahead();
- if (token.type !== Token.StringLiteral) {
- break;
- }
-
- sourceElement = parseSourceElement();
- sourceElements.push(sourceElement);
- if (sourceElement.expression.type !== Syntax.Literal) {
- // this is not directive
- break;
- }
- directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
- if (directive === 'use strict') {
- strict = true;
- if (firstRestricted) {
- throwError(firstRestricted, Messages.StrictOctalLiteral);
- }
- } else {
- if (!firstRestricted && token.octal) {
- firstRestricted = token;
- }
- }
- }
-
- oldLabelSet = state.labelSet;
- oldInIteration = state.inIteration;
- oldInSwitch = state.inSwitch;
- oldInFunctionBody = state.inFunctionBody;
-
- state.labelSet = {};
- state.inIteration = false;
- state.inSwitch = false;
- state.inFunctionBody = true;
-
- while (index < length) {
- if (match('}')) {
- break;
- }
- sourceElement = parseSourceElement();
- if (typeof sourceElement === 'undefined') {
- break;
- }
- sourceElements.push(sourceElement);
- }
-
- expect('}');
-
- state.labelSet = oldLabelSet;
- state.inIteration = oldInIteration;
- state.inSwitch = oldInSwitch;
- state.inFunctionBody = oldInFunctionBody;
-
- return {
- type: Syntax.BlockStatement,
- body: sourceElements
- };
- }
-
- function parseFunctionDeclaration() {
- var id, param, params = [], body, token, firstRestricted, message, previousStrict, paramSet;
-
- expectKeyword('function');
- token = lookahead();
- id = parseVariableIdentifier();
- if (strict) {
- if (isRestrictedWord(token.value)) {
- throwError(token, Messages.StrictFunctionName);
- }
- } else {
- if (isRestrictedWord(token.value)) {
- firstRestricted = token;
- message = Messages.StrictFunctionName;
- } else if (isStrictModeReservedWord(token.value)) {
- firstRestricted = token;
- message = Messages.StrictReservedWord;
- }
- }
-
- expect('(');
-
- if (!match(')')) {
- paramSet = {};
- while (index < length) {
- token = lookahead();
- param = parseVariableIdentifier();
- if (strict) {
- if (isRestrictedWord(token.value)) {
- throwError(token, Messages.StrictParamName);
- }
- if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
- throwError(token, Messages.StrictParamDupe);
- }
- } else if (!firstRestricted) {
- if (isRestrictedWord(token.value)) {
- firstRestricted = token;
- message = Messages.StrictParamName;
- } else if (isStrictModeReservedWord(token.value)) {
- firstRestricted = token;
- message = Messages.StrictReservedWord;
- } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
- firstRestricted = token;
- message = Messages.StrictParamDupe;
- }
- }
- params.push(param);
- paramSet[param.name] = true;
- if (match(')')) {
- break;
- }
- expect(',');
- }
- }
-
- expect(')');
-
- previousStrict = strict;
- body = parseFunctionSourceElements();
- if (strict && firstRestricted) {
- throwError(firstRestricted, message);
- }
- strict = previousStrict;
-
- return {
- type: Syntax.FunctionDeclaration,
- id: id,
- params: params,
- body: body
- };
- }
-
- function parseFunctionExpression() {
- var token, id = null, firstRestricted, message, param, params = [], body, previousStrict, paramSet;
-
- expectKeyword('function');
-
- if (!match('(')) {
- token = lookahead();
- id = parseVariableIdentifier();
- if (strict) {
- if (isRestrictedWord(token.value)) {
- throwError(token, Messages.StrictFunctionName);
- }
- } else {
- if (isRestrictedWord(token.value)) {
- firstRestricted = token;
- message = Messages.StrictFunctionName;
- } else if (isStrictModeReservedWord(token.value)) {
- firstRestricted = token;
- message = Messages.StrictReservedWord;
- }
- }
- }
-
- expect('(');
-
- if (!match(')')) {
- paramSet = {};
- while (index < length) {
- token = lookahead();
- param = parseVariableIdentifier();
- if (strict) {
- if (isRestrictedWord(token.value)) {
- throwError(token, Messages.StrictParamName);
- }
- if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
- throwError(token, Messages.StrictParamDupe);
- }
- } else if (!firstRestricted) {
- if (isRestrictedWord(token.value)) {
- firstRestricted = token;
- message = Messages.StrictParamName;
- } else if (isStrictModeReservedWord(token.value)) {
- firstRestricted = token;
- message = Messages.StrictReservedWord;
- } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
- firstRestricted = token;
- message = Messages.StrictParamDupe;
- }
- }
- params.push(param);
- paramSet[param.name] = true;
- if (match(')')) {
- break;
- }
- expect(',');
- }
- }
-
- expect(')');
-
- previousStrict = strict;
- body = parseFunctionSourceElements();
- if (strict && firstRestricted) {
- throwError(firstRestricted, message);
- }
- strict = previousStrict;
-
- return {
- type: Syntax.FunctionExpression,
- id: id,
- params: params,
- body: body
- };
- }
-
- // 14 Program
-
- function parseSourceElement() {
- var token = lookahead();
-
- if (token.type === Token.Keyword) {
- switch (token.value) {
- case 'const':
- case 'let':
- return parseConstLetDeclaration(token.value);
- case 'function':
- return parseFunctionDeclaration();
- default:
- return parseStatement();
- }
- }
-
- if (token.type !== Token.EOF) {
- return parseStatement();
- }
- }
-
- function parseSourceElements() {
- var sourceElement, sourceElements = [], token, directive, firstRestricted;
-
- while (index < length) {
- token = lookahead();
- if (token.type !== Token.StringLiteral) {
- break;
- }
-
- sourceElement = parseSourceElement();
- sourceElements.push(sourceElement);
- if (sourceElement.expression.type !== Syntax.Literal) {
- // this is not directive
- break;
- }
- directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
- if (directive === 'use strict') {
- strict = true;
- if (firstRestricted) {
- throwError(firstRestricted, Messages.StrictOctalLiteral);
- }
- } else {
- if (!firstRestricted && token.octal) {
- firstRestricted = token;
- }
- }
- }
-
- while (index < length) {
- sourceElement = parseSourceElement();
- if (typeof sourceElement === 'undefined') {
- break;
- }
- sourceElements.push(sourceElement);
- }
- return sourceElements;
- }
-
- function parseProgram() {
- var program;
- strict = false;
- program = {
- type: Syntax.Program,
- body: parseSourceElements()
- };
- return program;
- }
-
- // The following functions are needed only when the option to preserve
- // the comments is active.
-
- function addComment(start, end, type, value) {
- assert(typeof start === 'number', 'Comment must have valid position');
-
- // Because the way the actual token is scanned, often the comments
- // (if any) are skipped twice during the lexical analysis.
- // Thus, we need to skip adding a comment if the comment array already
- // handled it.
- if (extra.comments.length > 0) {
- if (extra.comments[extra.comments.length - 1].range[1] > start) {
- return;
- }
- }
-
- extra.comments.push({
- range: [start, end],
- type: type,
- value: value
- });
- }
-
- function scanComment() {
- var comment, ch, start, blockComment, lineComment;
-
- comment = '';
- blockComment = false;
- lineComment = false;
-
- while (index < length) {
- ch = source[index];
-
- if (lineComment) {
- ch = nextChar();
- if (index >= length) {
- lineComment = false;
- comment += ch;
- addComment(start, index, 'Line', comment);
- } else if (isLineTerminator(ch)) {
- lineComment = false;
- addComment(start, index, 'Line', comment);
- if (ch === '\r' && source[index] === '\n') {
- ++index;
- }
- ++lineNumber;
- lineStart = index;
- comment = '';
- } else {
- comment += ch;
- }
- } else if (blockComment) {
- if (isLineTerminator(ch)) {
- if (ch === '\r' && source[index + 1] === '\n') {
- ++index;
- comment += '\r\n';
- } else {
- comment += ch;
- }
- ++lineNumber;
- ++index;
- lineStart = index;
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- } else {
- ch = nextChar();
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- comment += ch;
- if (ch === '*') {
- ch = source[index];
- if (ch === '/') {
- comment = comment.substr(0, comment.length - 1);
- blockComment = false;
- ++index;
- addComment(start, index, 'Block', comment);
- comment = '';
- }
- }
- }
- } else if (ch === '/') {
- ch = source[index + 1];
- if (ch === '/') {
- start = index;
- index += 2;
- lineComment = true;
- } else if (ch === '*') {
- start = index;
- index += 2;
- blockComment = true;
- if (index >= length) {
- throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
- }
- } else {
- break;
- }
- } else if (isWhiteSpace(ch)) {
- ++index;
- } else if (isLineTerminator(ch)) {
- ++index;
- if (ch === '\r' && source[index] === '\n') {
- ++index;
- }
- ++lineNumber;
- lineStart = index;
- } else {
- break;
- }
- }
- }
-
- function collectToken() {
- var token = extra.advance(),
- range,
- value;
-
- if (token.type !== Token.EOF) {
- range = [token.range[0], token.range[1]];
- value = sliceSource(token.range[0], token.range[1]);
- extra.tokens.push({
- type: TokenName[token.type],
- value: value,
- range: range
- });
- }
-
- return token;
- }
-
- function collectRegex() {
- var pos, regex, token;
-
- skipComment();
-
- pos = index;
- regex = extra.scanRegExp();
-
- // Pop the previous token, which is likely '/' or '/='
- if (extra.tokens.length > 0) {
- token = extra.tokens[extra.tokens.length - 1];
- if (token.range[0] === pos && token.type === 'Punctuator') {
- if (token.value === '/' || token.value === '/=') {
- extra.tokens.pop();
- }
- }
- }
-
- extra.tokens.push({
- type: 'RegularExpression',
- value: regex.literal,
- range: [pos, index]
- });
-
- return regex;
- }
-
- function createLiteral(token) {
- return {
- type: Syntax.Literal,
- value: token.value
- };
- }
-
- function createRawLiteral(token) {
- return {
- type: Syntax.Literal,
- value: token.value,
- raw: sliceSource(token.range[0], token.range[1])
- };
- }
-
- function wrapTrackingFunction(range, loc) {
-
- return function (parseFunction) {
-
- function isBinary(node) {
- return node.type === Syntax.LogicalExpression ||
- node.type === Syntax.BinaryExpression;
- }
-
- function visit(node) {
- if (isBinary(node.left)) {
- visit(node.left);
- }
- if (isBinary(node.right)) {
- visit(node.right);
- }
-
- if (range && typeof node.range === 'undefined') {
- node.range = [node.left.range[0], node.right.range[1]];
- }
- if (loc && typeof node.loc === 'undefined') {
- node.loc = {
- start: node.left.loc.start,
- end: node.right.loc.end
- };
- }
- }
-
- return function () {
- var node, rangeInfo, locInfo;
-
- skipComment();
- rangeInfo = [index, 0];
- locInfo = {
- start: {
- line: lineNumber,
- column: index - lineStart
- }
- };
-
- node = parseFunction.apply(null, arguments);
- if (typeof node !== 'undefined') {
-
- if (range) {
- rangeInfo[1] = index;
- node.range = rangeInfo;
- }
-
- if (loc) {
- locInfo.end = {
- line: lineNumber,
- column: index - lineStart
- };
- node.loc = locInfo;
- }
-
- if (isBinary(node)) {
- visit(node);
- }
-
- if (node.type === Syntax.MemberExpression) {
- if (typeof node.object.range !== 'undefined') {
- node.range[0] = node.object.range[0];
- }
- if (typeof node.object.loc !== 'undefined') {
- node.loc.start = node.object.loc.start;
- }
- }
-
- if (node.type === Syntax.CallExpression) {
- if (typeof node.callee.range !== 'undefined') {
- node.range[0] = node.callee.range[0];
- }
- if (typeof node.callee.loc !== 'undefined') {
- node.loc.start = node.callee.loc.start;
- }
- }
- return node;
- }
- };
-
- };
- }
-
- function patch() {
-
- var wrapTracking;
-
- if (extra.comments) {
- extra.skipComment = skipComment;
- skipComment = scanComment;
- }
-
- if (extra.raw) {
- extra.createLiteral = createLiteral;
- createLiteral = createRawLiteral;
- }
-
- if (extra.range || extra.loc) {
-
- wrapTracking = wrapTrackingFunction(extra.range, extra.loc);
-
- extra.parseAdditiveExpression = parseAdditiveExpression;
- extra.parseAssignmentExpression = parseAssignmentExpression;
- extra.parseBitwiseANDExpression = parseBitwiseANDExpression;
- extra.parseBitwiseORExpression = parseBitwiseORExpression;
- extra.parseBitwiseXORExpression = parseBitwiseXORExpression;
- extra.parseBlock = parseBlock;
- extra.parseFunctionSourceElements = parseFunctionSourceElements;
- extra.parseCallMember = parseCallMember;
- extra.parseCatchClause = parseCatchClause;
- extra.parseComputedMember = parseComputedMember;
- extra.parseConditionalExpression = parseConditionalExpression;
- extra.parseConstLetDeclaration = parseConstLetDeclaration;
- extra.parseEqualityExpression = parseEqualityExpression;
- extra.parseExpression = parseExpression;
- extra.parseForVariableDeclaration = parseForVariableDeclaration;
- extra.parseFunctionDeclaration = parseFunctionDeclaration;
- extra.parseFunctionExpression = parseFunctionExpression;
- extra.parseLogicalANDExpression = parseLogicalANDExpression;
- extra.parseLogicalORExpression = parseLogicalORExpression;
- extra.parseMultiplicativeExpression = parseMultiplicativeExpression;
- extra.parseNewExpression = parseNewExpression;
- extra.parseNonComputedMember = parseNonComputedMember;
- extra.parseNonComputedProperty = parseNonComputedProperty;
- extra.parseObjectProperty = parseObjectProperty;
- extra.parseObjectPropertyKey = parseObjectPropertyKey;
- extra.parsePostfixExpression = parsePostfixExpression;
- extra.parsePrimaryExpression = parsePrimaryExpression;
- extra.parseProgram = parseProgram;
- extra.parsePropertyFunction = parsePropertyFunction;
- extra.parseRelationalExpression = parseRelationalExpression;
- extra.parseStatement = parseStatement;
- extra.parseShiftExpression = parseShiftExpression;
- extra.parseSwitchCase = parseSwitchCase;
- extra.parseUnaryExpression = parseUnaryExpression;
- extra.parseVariableDeclaration = parseVariableDeclaration;
- extra.parseVariableIdentifier = parseVariableIdentifier;
-
- parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression);
- parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression);
- parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression);
- parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression);
- parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression);
- parseBlock = wrapTracking(extra.parseBlock);
- parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements);
- parseCallMember = wrapTracking(extra.parseCallMember);
- parseCatchClause = wrapTracking(extra.parseCatchClause);
- parseComputedMember = wrapTracking(extra.parseComputedMember);
- parseConditionalExpression = wrapTracking(extra.parseConditionalExpression);
- parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration);
- parseEqualityExpression = wrapTracking(extra.parseEqualityExpression);
- parseExpression = wrapTracking(extra.parseExpression);
- parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration);
- parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration);
- parseFunctionExpression = wrapTracking(extra.parseFunctionExpression);
- parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression);
- parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression);
- parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression);
- parseNewExpression = wrapTracking(extra.parseNewExpression);
- parseNonComputedMember = wrapTracking(extra.parseNonComputedMember);
- parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty);
- parseObjectProperty = wrapTracking(extra.parseObjectProperty);
- parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey);
- parsePostfixExpression = wrapTracking(extra.parsePostfixExpression);
- parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression);
- parseProgram = wrapTracking(extra.parseProgram);
- parsePropertyFunction = wrapTracking(extra.parsePropertyFunction);
- parseRelationalExpression = wrapTracking(extra.parseRelationalExpression);
- parseStatement = wrapTracking(extra.parseStatement);
- parseShiftExpression = wrapTracking(extra.parseShiftExpression);
- parseSwitchCase = wrapTracking(extra.parseSwitchCase);
- parseUnaryExpression = wrapTracking(extra.parseUnaryExpression);
- parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration);
- parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier);
- }
-
- if (typeof extra.tokens !== 'undefined') {
- extra.advance = advance;
- extra.scanRegExp = scanRegExp;
-
- advance = collectToken;
- scanRegExp = collectRegex;
- }
- }
-
- function unpatch() {
- if (typeof extra.skipComment === 'function') {
- skipComment = extra.skipComment;
- }
-
- if (extra.raw) {
- createLiteral = extra.createLiteral;
- }
-
- if (extra.range || extra.loc) {
- parseAdditiveExpression = extra.parseAdditiveExpression;
- parseAssignmentExpression = extra.parseAssignmentExpression;
- parseBitwiseANDExpression = extra.parseBitwiseANDExpression;
- parseBitwiseORExpression = extra.parseBitwiseORExpression;
- parseBitwiseXORExpression = extra.parseBitwiseXORExpression;
- parseBlock = extra.parseBlock;
- parseFunctionSourceElements = extra.parseFunctionSourceElements;
- parseCallMember = extra.parseCallMember;
- parseCatchClause = extra.parseCatchClause;
- parseComputedMember = extra.parseComputedMember;
- parseConditionalExpression = extra.parseConditionalExpression;
- parseConstLetDeclaration = extra.parseConstLetDeclaration;
- parseEqualityExpression = extra.parseEqualityExpression;
- parseExpression = extra.parseExpression;
- parseForVariableDeclaration = extra.parseForVariableDeclaration;
- parseFunctionDeclaration = extra.parseFunctionDeclaration;
- parseFunctionExpression = extra.parseFunctionExpression;
- parseLogicalANDExpression = extra.parseLogicalANDExpression;
- parseLogicalORExpression = extra.parseLogicalORExpression;
- parseMultiplicativeExpression = extra.parseMultiplicativeExpression;
- parseNewExpression = extra.parseNewExpression;
- parseNonComputedMember = extra.parseNonComputedMember;
- parseNonComputedProperty = extra.parseNonComputedProperty;
- parseObjectProperty = extra.parseObjectProperty;
- parseObjectPropertyKey = extra.parseObjectPropertyKey;
- parsePrimaryExpression = extra.parsePrimaryExpression;
- parsePostfixExpression = extra.parsePostfixExpression;
- parseProgram = extra.parseProgram;
- parsePropertyFunction = extra.parsePropertyFunction;
- parseRelationalExpression = extra.parseRelationalExpression;
- parseStatement = extra.parseStatement;
- parseShiftExpression = extra.parseShiftExpression;
- parseSwitchCase = extra.parseSwitchCase;
- parseUnaryExpression = extra.parseUnaryExpression;
- parseVariableDeclaration = extra.parseVariableDeclaration;
- parseVariableIdentifier = extra.parseVariableIdentifier;
- }
-
- if (typeof extra.scanRegExp === 'function') {
- advance = extra.advance;
- scanRegExp = extra.scanRegExp;
- }
- }
-
- function stringToArray(str) {
- var length = str.length,
- result = [],
- i;
- for (i = 0; i < length; ++i) {
- result[i] = str.charAt(i);
- }
- return result;
- }
-
- function parse(code, options) {
- var program, toString;
-
- toString = String;
- if (typeof code !== 'string' && !(code instanceof String)) {
- code = toString(code);
- }
-
- source = code;
- index = 0;
- lineNumber = (source.length > 0) ? 1 : 0;
- lineStart = 0;
- length = source.length;
- buffer = null;
- state = {
- allowIn: true,
- labelSet: {},
- lastParenthesized: null,
- inFunctionBody: false,
- inIteration: false,
- inSwitch: false
- };
-
- extra = {};
- if (typeof options !== 'undefined') {
- extra.range = (typeof options.range === 'boolean') && options.range;
- extra.loc = (typeof options.loc === 'boolean') && options.loc;
- extra.raw = (typeof options.raw === 'boolean') && options.raw;
- if (typeof options.tokens === 'boolean' && options.tokens) {
- extra.tokens = [];
- }
- if (typeof options.comment === 'boolean' && options.comment) {
- extra.comments = [];
- }
- if (typeof options.tolerant === 'boolean' && options.tolerant) {
- extra.errors = [];
- }
- }
-
- if (length > 0) {
- if (typeof source[0] === 'undefined') {
- // Try first to convert to a string. This is good as fast path
- // for old IE which understands string indexing for string
- // literals only and not for string object.
- if (code instanceof String) {
- source = code.valueOf();
- }
-
- // Force accessing the characters via an array.
- if (typeof source[0] === 'undefined') {
- source = stringToArray(code);
- }
- }
- }
-
- patch();
- try {
- program = parseProgram();
- if (typeof extra.comments !== 'undefined') {
- program.comments = extra.comments;
- }
- if (typeof extra.tokens !== 'undefined') {
- program.tokens = extra.tokens;
- }
- if (typeof extra.errors !== 'undefined') {
- program.errors = extra.errors;
- }
- } catch (e) {
- throw e;
- } finally {
- unpatch();
- extra = {};
- }
-
- return program;
- }
-
- // Sync with package.json.
- exports.version = '1.0.0-dev';
-
- exports.parse = parse;
-
- // Deep copy.
- exports.Syntax = (function () {
- var name, types = {};
-
- if (typeof Object.create === 'function') {
- types = Object.create(null);
- }
-
- for (name in Syntax) {
- if (Syntax.hasOwnProperty(name)) {
- types[name] = Syntax[name];
- }
- }
-
- if (typeof Object.freeze === 'function') {
- Object.freeze(types);
- }
-
- return types;
- }());
-
- }(typeof exports === 'undefined' ? (esprima = {}) : exports));
- /* vim: set sw=4 ts=4 et tw=80 : */
-
- });define('uglifyjs/consolidator', ["require", "exports", "module", "./parse-js", "./process"], function(require, exports, module) {
- /**
- * @preserve Copyright 2012 Robert Gust-Bardon