gloader/ 40755 0 0 0 11220474221 7520 5ustar 0 0 gloader/0.1.0-rc1/ 40755 0 0 0 11220474222 10640 5ustar 0 0 CONTRIBUTORS100644 0 0 0 11220474223 7770 0ustar 0 0 LICENCE100644 0 0 23676 11220474223 7225 0ustar 0 0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS README100644 0 0 11162 11220474223 7103 0ustar 0 0 Using Gloader ---- Overview ==== Gloader is a JavaScript module loader that was create as part of the BBC Glow project. It can however be used with any JavaScript library that follows the same Glow module pattern. Gloader's Idea of a "Module" ==== JavaScript does not intrinsiclly support code modules, but we can define our own modules in code. Basically we are striving to have a chunk of related code in a self-contained package, a "module". Module need to describe themselves with some meta information, including: what library they belong to, which version number describes them, and what other modules they depend on. Finally a module needs to define some function that when executed will create the module object; this function is called the "builder". Gloader's Idea of a "Library" ==== A group of related modules are held together under a single library. In fact the library is itself a module, but what makes it unique is that it can contain other modules. Every library must have exactly one library module. An Example of a Library Module ==== As explained previously a library is actually a special kind of module, and you must have exactly one library module. Bearing that in mind, when creating a library you should start with the library module. It will follow a pattern that looks like this: gloader.library({ name: "myLibrary", version: "1.0.0", builder: function () { // this is where you create your library module var myLibrary = {}; // <-- can be anything return myLibrary; } }); It is conventional that you use a variable-like name for your library but in fact the `name` can be any string: It can contain any combination of characters except for the forward-slash character "/", which has special meaning to gloader. Likewise the `version` identifier is be a string that can contain any chraracters except for the forward-slash. however if you follow the convention of using a pattern like: `..` you will gain special functionality from gloader in which it can automatically manage version updates for you (this is discussed further on). The `builder` function actually creates your library module. You can execute any code you like inside the builder, but it is recommended that you create a function scoped object, by using the `var` keyword as shown, and then returning a reference to it at the end of the builder. Following this pattern will allow gloader to "sandbox" your library so that people can eventually have multiple versions of a single library defined on the same page. Notice that there are no dependencies defined. That's becuase a library is expected to stand alone: it cannot be dependednt on any other library or module to run. An Example of a Module ==== Once you have a library you can attach modules to it. The process of defining a module is very similar to that of a library: gloader.module({ name: 'myLibrary.myModule', library: ['myLibrary', '1.0.0'], builder: function(myLibrary) { myLibrary.myModule = {}; } }); The differences are that a module must define what library (lbrary name and library version) it belongs to. Notice that a module does not have it's own version identifier, instead modules always inherit their vesrions from their library. Therefore this module, named "myLibrary.myModule", is version "1.0.0". As with the library module definition, the module definition has a builder function, however the builder for a module will always receive a single argument: the same object returned by the library's builder. This, presumably, will be the library object and you can then attach your module to that object. Dependencies ==== Any module definitio can optionally list other modules as dependencies. For example, if you were to define a second module that depended on the module we defined in the previous section, it would be written like so: gloader.module({ name: 'myLibrary.myOtherModule', library: ['myLibrary', '1.0.0'], depends: [ ['myLibrary', '1.0.0', 'myLibrary.myModule'] ], builder: function(myLibrary) { myLibrary.myOtherModule = {}; } }); The `depends` option is an array of arrays: the inner arrays define the dependent library name, library version, and zero or more modules from that library. Variations on that woulr be written like so: // only need the library depends: [ ['myLibrary', '1.0.0'] ] // need several modules from the same library depends: [ ['myLibrary', '1.0.0', 'myLibrary.myModule', 'myLibrary.Etc'] ] // several modules from the several libraries depends: [ ['myLibrary', '1.0.0', 'myLibrary.myModule', 'myLibrary.Etc'], ['otherLibrary', '1.2.0', 'otherLibrary.myModule', 'otherLibrary.Etc'] ] gloader/0.1.0-rc1/gloader.debug.js100644 0 0 65650 11220474221 14030 0ustar 0 0 /* Copyright 2009 British Broadcasting Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** A module loader for Glow. */ (function(){ if (window.gloader) return; window.gloader = { _requests: [], // {gloader.Request} _modules: {}, // modId: {gloader.Module|undefined} _expects: {}, // modId: {Number} - module definitions that are expected but were not requested _extras: {}, // modId: {Object} - module definitions provided but not yet requested _errors: [], // {String} - used for testing purposes util: { /** Determine if a filepath could be the name of this file. */ getGloaderFile: function(filepath) { // the gloader file can have a few name variations, but will always start with "gloader" and end with ".js" (excluding possible querystring) if (filepath && /(^|^.*[\/\\])(gloader(\.[^\/\\]+)?\.js)(\?|$)/i.test(filepath)) { return { dir: RegExp.$1, name: RegExp.$2 }; } return undefined; // the filepath is not possibly this file } }, /** Locations of all known module files. */ map: { /** Locations of known javascript files. */ js: {}, // modId: URL /** Locations of known stylesheet files. */ css: {}, // modId: URL /** Interpolate values in the given library definition. */ parse: function(libraryName, libraryVersions) { /*debug*///console.log("gloader.map.parse("+libraryName+", "+libraryVersions+")"); // create an empty library object to be returned at the end var lib = {name: libraryName, versions: []}; // keep track of the properties set in previous version definitions // like: {$someName: "someValue"} var scope = {}; // required scope properties // order controls order of interpolation // e.g. a $base can contain a {$version}, but not visa versa // $name means the library's name var scopeProps = ["$name", "$version", "$base"]; scopeProps.has = function(what) { // just a quick convenience method for (var i = 0; i < this.length; i++) { if (what == this[i]) return true; } return false; } // include user defined properties if (gloader.mapProps && gloader.mapProps[lib.name]) { for (var p in gloader.mapProps[lib.name]) { if (!scopeProps.has(p)) { // scopeProps items will be unique scopeProps.push(p); } } } // initialize the scope object for (var p = 0; p < scopeProps.length; p++) { scope[scopeProps[p]] = undefined; } scope.$name = lib.name; // set user-defined properties in scope if (gloader.mapProps && gloader.mapProps[lib.name]) { for (var p in gloader.mapProps[lib.name]) { scope[p] = gloader.mapProps[lib.name][p]; } } // loop over each version definition for (var i = 0; i < libraryVersions.length; i++) { var version = libraryVersions[i]; // add to or delete from the scope any version properties, for (var v in version) { // a value of type null means: "delete" from scope if (version[v] === null) { delete version[v]; delete scope[v]; } // a non-null value means: "add" (or overwrite) to scope else { if (v.indexOf("$") === 0) scope[v] = version[v]; // $values must be strings else if (typeof version[v] == "string") { version[v] = [version[v]]; // other values must be arrays scope[v] = version[v].slice(0); // copy } else if (typeof version[v].push != "undefined") { // already an array? scope[v] = version[v].slice(0); // copy; } else throw new Error("invalid type: "+typeof version[v]); } } // fill in any undefined version properties that were defined before for (var s in scope) { if (typeof version[s] == "undefined") { if (s.indexOf("$") === 0) version[s] = scope[s]; else version[s] = scope[s].slice(0); // copy } } // interpolate all {$var} strings in all version properties with $prop values for (var p = 0; p < scopeProps.length; p++) { var prop = scopeProps[p]; for (var vp = 0; vp < p; vp++) { var vprop = scopeProps[vp]; if (typeof version[vprop] == "undefined") version[prop] = scope[prop]; // this version does not redefine this property var patt = new RegExp('\\{\\'+vprop+'\\}', "g"); version[prop] = version[prop].replace(patt, version[vprop]); } } // interpolate all {$var} strings in all version items with $prop values for (vi in version) { if (vi.indexOf("$") === 0 ) continue; // these have already been interped for (var vii = 0; vii < version[vi].length; vii++) { for (var p = 0; p < scopeProps.length; p++) { var prop = scopeProps[p]; var patt = new RegExp('\\{\\'+prop+'\\}', "g"); version[vi][vii] = ""+version[vi][vii].replace(patt, ""+version[prop]); } } } lib.versions.push(version); } return lib; }, /** Populate this map with some library data. @param {String} libraryName The name of the library you are adding. @param {Object} ... One or more objects that define the files in the various versions of this library. */ add: function() { /*debug*///console.log("gloader.map.add("+arguments+")"); // note trick to convert arguments into an array (less the first item) var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } var lib = gloader.map.parse(arguments[0], args); // populate the js and css tables with the interpolated key/values: modId => src for (var i = 0; i < lib.versions.length; i++) { var version = lib.versions[i]; for (var p in version) { if (p.charAt(0) == "$") continue; // for gloader use only // modId like: libraryName/versionId/moduleName var modId = version.$name+"/"+version.$version+"/"+p; // note: can overwrite gloader.map.js[modId] = version[p][0]; gloader.map.css[modId] = version[p][1]; } } }, /** A map from elsewhere is included in this one. This must be synchronous. */ include: function(src) { /*debug*///console.log("gloader.map.include("+src+")"); if (gloader.map._include[src]) { // is already included so can skip doing so again return false } else { document.write('\n'); gloader.map._include[src] = true; return true; } }, _include: {}, // memoize /** Get the value of the latest minor version number of a library. */ latest: function(libName, v) { /*debug*///console.log("gloader.map.latest("+libName+", "+v+")"); if (gloader.map.$latest[libName+"/"+v]) { return gloader.map.$latest[libName+"/"+v]; } var result = v; var parts = v.split("."); // if the version is not fully specified if (parts.length < 3) { // if the version is in the format maj[.min] if ( parts[0] == parseInt(parts[0]) && (typeof parts[1] == "undefined" || parts[1] == parseInt(parts[1])) ) { var invalid = new RegExp("[a-zA-Z\-]"), latest = [parts[0], null, null], mod; for (mod in gloader.map.js) { var modParts = mod.split("/"); if (modParts[0] == libName && modParts[2] == libName && !invalid.test(modParts[1])) { var modVParts = modParts[1].split("."); if (modVParts[0] == parts[0]) { // same major if ( ( typeof parts[1] == "undefined" // no particular minor version was requested && // and either... ( latest[1] <= modVParts[1] // the current latest minor version is not more recent as this module || // or ( latest[1] == modVParts[1] // and the current latest minor version matches this module's minor version && latest[2] <= modVParts[2] // and the latest bug version is not more recent as this module's bug version ) ) ) || // or ( typeof parts[1] != "undefined" // a particular minor version was requested && parts[1] == modVParts[1] // and the requested minor version matches this module's minor version && latest[2] <= modVParts[2] // and the latest bug version is not more recent as this module's bug version ) ) { latest[1] = modVParts[1]; latest[2] = modVParts[2]; } } } } if (latest[2] != null) result = latest.join("."); } } gloader.map.$latest[libName+"/"+v] = result; return result; }, $latest: {} // memoize }, /** Give values to states that gloader can refer to. */ settings: { ns: "bbc.glow.gloader", get: function(name) { /*debug*///console.log("get("+name+")"); var n = " "+gloader.settings.ns+"."+name+"=" var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { if ((" "+cookies[i]).indexOf(n) > -1) { return unescape(cookies[i].split("=")[1]); } } }, set: function(name, value, path) { /*debug*///console.log("set("+name+", "+value+")"); var n = gloader.settings.ns+"."+name; document.cookie = n + "=" + escape(value) + "; path="+((path)? path : "/")+";"; }, clear: function(name, path) { /*debug*///console.log("clear("+name+")"); var d = new Date(); d.setTime(d.getTime() - 1); var n = gloader.settings.ns+"."+name; document.cookie = n + "=; path="+((path)? path : "/")+"; expires=Thu, 01-Jan-70 00:00:01 GMT;"; } }, // javascript:(function(){gloader.loadOverride()})(); loadOverride: function(version) { var current = gloader.settings.get("override"); version = version || prompt("Enter version", current ? current : ""); if (version === "") gloader.settings.clear("override"); else if (version !== null) gloader.settings.set("override", version); location.reload(); }, // javascript:(function(){gloader.loadDebug()})(); loadDebug: function() { gloader.settings.set("debug", "1"); location.reload(); }, // javascript:(function(){gloader.unloadDebug()})(); unloadDebug: function() { gloader.settings.clear("debug"); location.reload(); }, expect: function(srcFile) { /*debug*///console.log("expecting modules in "+srcFile); srcFile = ""+srcFile; var modsInFile = []; var modId; for (modId in gloader.map.js) { if (gloader.map.js[modId] == srcFile) { modsInFile.push(modId); gloader._expects[modId] = (gloader._expects[modId] || 0)+1; } } }, /** The user makes a request. */ load: function() { /*debug*///console.log("gloader.load(...)"); var r = {}; if (typeof arguments[arguments.length-1].length == "undefined") { r = arguments[arguments.length-1]; arguments.length--; } var newRequest = new gloader.Request(r); gloader._requests.push(newRequest); var mods = []; var override = gloader.settings.get("override"); for (var i = 0; i < arguments.length; i++) { if (override && arguments[i][0] == "glow") { // warn the user what we've done if (typeof console != "undefined" && console.log) console.log("Overriding version '"+arguments[i][1]+"' of glow to version '"+override+"'"); arguments[i][1] = override; } mods.push(arguments[i]); } var ids = gloader.toIds(mods); newRequest.args = []; for (var i = 0; i < ids.length; i++) { newRequest.include(ids[i]); if (ids[i].match(/\/[^.]+$/)) { newRequest.args.push(ids[i]); } } // if all the requested modules are already loaded we can short-circuit var waitCount = newRequest.waits.length; for (var i = 0; i < newRequest.waits.length; i++) { if ( gloader._modules[newRequest.waits[i]] && gloader._modules[newRequest.waits[i]].status == gloader.Module.IMPLEMENTED ) waitCount--; } if (waitCount > 0) { newRequest.status = gloader.Request.WAITING; gloader.request(ids, newRequest.async); gloader.resolve(); } else { /*debug*///console.info("skipping the download"); newRequest.complete(); } // ====> opera 9.2 always exits here, it evalualtes *all* code inline. }, /** We need some module files to complete a request. */ request: function(mIds, async) { /*debug*///console.log("gloader.request(["+mIds.join(",")+"], "+async+")"); for (var i = 0; i < mIds.length; i++) { if (gloader._extras[mIds[i]]) { // module was provided before it was requested gloader._modules[mIds[i]] = new gloader.Module(mIds[i]); var extra = gloader._extras[mIds[i]]; delete gloader._extras[mIds[i]]; gloader.provide(extra); } else if (!gloader._modules[mIds[i]]) { gloader._modules[mIds[i]] = new gloader.Module(mIds[i]); gloader._modules[mIds[i]].status = gloader.Module.REQUESTED; } } for (var m in gloader._modules) { if (gloader._modules[m].status < gloader.Module.IMPLEMENTED || gloader._modules[m].css) { gloader._modules[m].css = null; // the module was already fetched (asynchronously) and hasn't // yet arrived, but now is requested again synchronously, // in this case we must force the fetch to happen twice var force = (!async && gloader._modules[m].async == true && gloader._modules[m].status >= gloader.Module.FETCHED); gloader.fetch(gloader._modules[m], async, force); } } }, /** Inject a module file into this web page. */ fetch: function(m, async, force) { /*debug*///console.log("gloader.fetch("+m.id+", "+async+")"); gloader._modules[m.id].async = async; var cssSrc = gloader.map.css[m.id]; if (force || (cssSrc && !gloader._fetched[cssSrc])) { /*debug*///console.log("injecting css file: "+cssSrc); gloader._fetched[cssSrc] = 1; if (document) { var headElement; if (headElement = document.getElementsByTagName('head')[0]) { var link; if (link = document.createElement('link')) { link.href = cssSrc; link.rel = 'stylesheet'; link.type = 'text/css'; link.className = 'gloaded'; headElement.appendChild(link); } } else { document.write(''); } } } if (!force && gloader._modules[m.id].status >= gloader.Module.FETCHED) return false; gloader._modules[m.id].status = gloader.Module.FETCHED; var jsSrc = gloader.map.js[m.id]; if (!jsSrc) { var msg = "The gloader map is missing a JavaScript filepath for the module: "+m.id; var maps = []; for (var included_map in gloader.map._include) maps.push(included_map); msg += ".\rMaps included are: "+maps.join(", ")+"."; gloader._errors.push(msg); throw new Error(msg); } if (force || (jsSrc && !gloader._fetched[jsSrc])) { /*debug*///console.log("fetching js file: "+jsSrc); gloader._fetched[jsSrc] = 1; // given the source file, we should expect all the modules in that source file gloader.expect(jsSrc); if (async) { /*debug*///console.log("inject: "+jsSrc); var headElement = document.getElementsByTagName('head')[0]; var scriptElement = document.createElement('script'); scriptElement.type = 'text/javascript'; scriptElement.src = jsSrc; headElement.appendChild(scriptElement); } else { /*debug*///console.log("write: "+jsSrc); document.write('\n'); } } }, _fetched: { }, /** A module file has arrived (been provided). @param {object} m The module definition from the remote source file. */ provide: function(m) { /*debug*///console.log("gloader.provide("+m.library[0]+"/"+m.library[1]+"/"+m.name+")"); m.id = m.library[0]+"/"+m.library[1]+"/"+m.name; // modifying the module definition from the remote file if (!gloader._modules[m.id]) { // we got more modules than we requested gloader._extras[m.id] = m; return; } gloader._modules[m.id].status = gloader.Module.PROVIDED; gloader._modules[m.id].builder = m.builder; gloader._modules[m.id].builder.args = []; var d = gloader._modules[m.id].depends = (m.depends)? gloader.toIds(m.depends) : []; if (d.length > 0) { var includes = []; for (var i = 0; i < d.length; i++) { var requests = gloader.getRequests(m); var include = {async: true, ids: []}; for (var j = 0; j < requests.length; j++) { requests[j].include(d[i]); include.ids.push(d[i]); if (requests[j].async === false) { // are there any requests for this module that are sync? include.async = false; } } includes.push(include); if (d[i].match(/\/[^.]+$/)) { gloader._modules[m.id].builder.args.push(d[i]); } } for (var i = 0; i < includes.length; i++) { gloader.request(includes[i].ids, includes[i].async); } } else { // module is provided and has no depends gloader.implement(m); } gloader.resolve(); // ====> firefox, et al exit here. }, // check: are we expecting this module? warn user if they are including // a module via an inline script tag while gloader is defined _greet: function(modId) { if (gloader._expects[modId] > 0) { // were we expecting this module or not gloader._expects[modId]--; } else { var msg = "Unexpected module provided to gloader: "+modId; gloader._errors.push(msg); throw(msg); } }, /** Wrapper for provide() with some specialisation for modules. */ module: function(modDef) { /*debug*///console.log("gloader.module("+modDef.name+")"); var modId = modDef.library[0]+"/"+modDef.library[1]+"/"+modDef.name; gloader._greet(modId); if (!modDef.depends) modDef.depends = []; modDef.depends.unshift(modDef.library); // modules implicitly depend on their own library gloader.provide(modDef); }, /** Wrapper for provide() with some specialisation for libraries. */ library: function(modDef) { /*debug*///console.log("gloader.library("+modDef.name+")"); var modId = modDef.name+"/"+modDef.version+"/"+modDef.name; gloader._greet(modId); if (!modDef.depends) modDef.depends = []; modDef.library = [modDef.name, modDef.version]; // a library module is a member of its own library gloader.provide(modDef); }, /** All dependents for a given module are available now. We can implement the module. */ implement: function(module) { /*debug*///console.log("gloader.implement("+module.id+"), module.status is "+gloader._modules[module.id].status); if (gloader._modules[module.id].status != gloader.Module.PROVIDED) return; gloader._modules[module.id].status = gloader.Module.IMPLEMENTED; for (var i = 0; i < gloader._modules[module.id].builder.args.length; i++) { var argName = gloader._modules[module.id].builder.args[i]; gloader._modules[module.id].builder.args[i] = gloader._modules[module.builder.args[i]].implementation; gloader._modules[module.id].builder.args[i].name = argName; } gloader._modules[module.id].implementation = gloader._modules[module.id].builder.apply(null, gloader._modules[module.id].builder.args); for (var i = 0; i < gloader._requests.length; i++) { gloader._requests[i].release(module.id); } }, /** Follow chain of modules and dependents being released. */ resolve: function() { /*debug*///console.log("gloader.resolve()"); MODULES: for (var m in gloader._modules) { var module = gloader._modules[m]; if (module.status == gloader.Module.PROVIDED) { for (var j = 0; j < module.depends.length; j++) { var dModule = gloader._modules[module.depends[j]]; if (!dModule || dModule.status != gloader.Module.IMPLEMENTED) { continue MODULES; } } gloader.implement(module); gloader.resolve(); } } }, /** Find all requests to which a given module belong. */ getRequests: function(m) { /*debug*///console.log("gloader.getRequests("+m.id+")"); var requests = []; REQUESTS: for (var i = 0; i < gloader._requests.length; i++) { var request = gloader._requests[i]; for (var j = 0; j < request.waits.length; j++) { if (request.waits[j] == m.id) { requests.push(request); break REQUESTS; } } } return requests; }, /** Turn a nested array of module defs into a flat array of id strings. */ toIds: function(lib) { var result = []; for (var i = 0; i < lib.length; i++) { var mods = lib[i]; var libName = mods.shift(); // modifies array mods refers to var libVersion = mods.shift(); var libId = libName+"/"+gloader.map.latest(libName, libVersion); result.push(libId+"/"+libName); for (var j = 0; j < mods.length; j++) { result.push(libId+"/"+mods[j]); } } return result; } }; /** A request, made by the user, for one or more modules to be loaded. @constructor */ gloader.Request = function(r) { /*debug*///console.log("gloader.Request("+r+")"); this.waits = []; this.status = gloader.Request.INITIAL; // normalize synonyms if (r.onLoad) r.onload = r.onLoad; if (r.onTimeout) r.ontimeout = r.onTimeout; // is this module implicitly meant to set global variables (no sandbox)? if (!r.async && !r.onload) { this.setGlobal = true; } this.async = (typeof r.async != "undefined")? r.async : false; this.onload = r.onload; if (r.ontimeout) { if (typeof r.timeout == "undefined") r.timeout = 20000; // 20 seconds this.timeoutRef = setTimeout(r.ontimeout, r.timeout); } } gloader.Request.INITIAL = -1; gloader.Request.WAITING = 0; gloader.Request.COMPLETED = 1; /** Need to wait for another module before we can complete. */ gloader.Request.prototype.include = function(mId) { /*debug*///console.log("gloader.Request#include("+mId+")"); for (var i = 0; i < this.waits.length; i++) { if (this.waits[i] == mId) return; } this.waits.push(mId); } /** Some module we are waiting for has become available, check if we can complete. */ gloader.Request.prototype.release = function(mId) { /*debug*///console.log("gloader.Request#release("+mId+")"); var implementCount = 0; for (var i = 0; i < this.waits.length; i++) { var wModule = gloader._modules[this.waits[i]]; if (wModule && wModule.status == gloader.Module.IMPLEMENTED) { implementCount++; } } if (implementCount == this.waits.length) { this.complete(); } } /** All modules for a request are available now. We can complete the request. */ gloader.Request.prototype.complete = function() { /*debug*///console.log("gloader.Request#complete()"); if (this.setGlobal) { for (var i = 0; i < this.waits.length; i++) { var gModule = gloader._modules[this.waits[i]]; window[gModule.name] = gloader._modules[this.waits[i]].implementation } } if (this.status == gloader.Request.COMPLETED) return; this.status = gloader.Request.COMPLETED; if (this.timeoutRef) clearTimeout(this.timeoutRef); for (var i = 0; i < this.args.length; i++) { this.args[i] = gloader._modules[this.args[i]].implementation; } if (this.onload) this.onload.apply(null, this.args); } /** Represents a module that can be in any state of loaded. @constructor */ gloader.Module = function(mId) { this.id = mId; this.name = mId.split("/").pop(); this.status = gloader.Module.INITIAL; this.css = gloader.map.css[mId]; } gloader.Module.INITIAL = -1; gloader.Module.REQUESTED = 0; gloader.Module.FETCHED = 1; gloader.Module.PROVIDED = 2; gloader.Module.IMPLEMENTED = 3; // for modules that need to detect dom readiness, but get loaded too late... gloader.isReady = false; (function(){ var d = document; if (/*@cc_on!@*/false) { // polling for no errors if (typeof window.frameElement != 'undefined') { // we can't use doScroll to test if we're in an iframe... d.attachEvent("onreadystatechange", function() { if (d.readyState == "complete") { d.detachEvent("onreadystatechange", arguments.callee); gloader.isReady = true; } }); } else { (function () { try { // throws errors until after ondocumentready d.documentElement.doScroll('left'); } catch (e) { setTimeout(arguments.callee, 50); return; } // no errors gloader.isReady = true; })(); } } else if (typeof d.readyState != 'undefined') { var f = function() { /loaded|complete/.test(d.readyState) ? gloader.isReady = true : setTimeout(f, 10); }; f(); } else { var callback = function () { if (arguments.callee.fired) { return; } arguments.callee.fired = true; if (gloader) gloader.isReady = true; }; d.addEventListener("DOMContentLoaded", callback, false); var oldOnload = window.onload; window.onload = function () { if (oldOnload) { oldOnload(); } callback(); }; } })(); gloader.map.setProperties = function(libraryName, props) { /*debug*///console.log("gloader.map.setProperties("+libraryName+", "+props.toSource()+")"); if (typeof gloader.mapProps == "undefined") gloader.mapProps = {}; if (typeof gloader.mapProps[libraryName] == "undefined") gloader.mapProps[libraryName] = {}; for (var p in props) { gloader.mapProps[libraryName][p] = props[p]; } } gloader.use = function(name, opts) { /*debug*///console.log("gloader.use("+lib+", "+opts+")") name = (name || "glow"); opts = (opts || {}); var properties = {}; for (var opts_name in opts) { var property_name = (opts_name.indexOf('$') == 0)? opts_name : '$'+opts_name; properties[property_name] = opts[opts_name]; } // default values properties.$debug = (properties.$debug || ""); properties.$base = (properties.$base || gloader._baseDir+name+"/{$version}/"); properties.$map = (properties.$map || gloader._baseDir+name+"/map.js"); gloader.map.setProperties( name, properties ); gloader.map.include(opts.map); }; })(); // using Resig's "degrading script" pattern. // first script tag on the page with src=gloader.js wins. (function() { var scripts = document.getElementsByTagName("script"); for (var i = 0; i < scripts.length; i++) { // does this script tag look like it is pointing to gloader? var src = scripts[i].getAttribute("src"); var filespec = gloader.util.getGloaderFile(src); if (typeof filespec != "undefined") { gloader._baseDir = filespec.dir; // is the content of this script node non-empty? is so then eval the contents var gloaderScript = scripts[i].innerHTML; if (/\S/.test(gloaderScript)) { eval(gloaderScript); } else { gloader.use(); } break; } } })();gloader/0.1.0-rc1/gloader.js100644 0 0 35360 11220474223 12740 0ustar 0 0 /* Copyright 2009 British Broadcasting Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){if(window.gloader){return;}window.gloader={_requests:[],_modules:{},_expects:{},_extras:{},_errors:[],util:{getGloaderFile:function(filepath){if(filepath&&/(^|^.*[\/\\])(gloader(\.[^\/\\]+)?\.js)(\?|$)/i.test(filepath)){return{dir:RegExp.$1,name:RegExp.$2};}return undefined;}},map:{js:{},css:{},parse:function(libraryName,libraryVersions){var lib={name:libraryName,versions:[]};var scope={};var scopeProps=["$name","$version","$base"];scopeProps.has=function(what){for(var i=0;i<\/script>\n');gloader.map._include[src]=true;return true;}},_include:{},latest:function(libName,v){if(gloader.map.$latest[libName+"/"+v]){return gloader.map.$latest[libName+"/"+v];}var result=v;var parts=v.split(".");if(parts.length<3){if(parts[0]==parseInt(parts[0])&&(typeof parts[1]=="undefined"||parts[1]==parseInt(parts[1]))){var invalid=new RegExp("[a-zA-Z-]"),latest=[parts[0],null,null],mod;for(mod in gloader.map.js){var modParts=mod.split("/");if(modParts[0]==libName&&modParts[2]==libName&&!invalid.test(modParts[1])){var modVParts=modParts[1].split(".");if(modVParts[0]==parts[0]){if((typeof parts[1]=="undefined"&&(latest[1]<=modVParts[1]||(latest[1]==modVParts[1]&&latest[2]<=modVParts[2])))||(typeof parts[1]!="undefined"&&parts[1]==modVParts[1]&&latest[2]<=modVParts[2])){latest[1]=modVParts[1];latest[2]=modVParts[2];}}}}if(latest[2]!=null){result=latest.join(".");}}}gloader.map.$latest[libName+"/"+v]=result;return result;},$latest:{}},settings:{ns:"bbc.glow.gloader",get:function(name){var n=" "+gloader.settings.ns+"."+name+"=";var cookies=document.cookie.split(";");for(var i=0;i-1){return unescape(cookies[i].split("=")[1]);}}},set:function(name,value,path){var n=gloader.settings.ns+"."+name;document.cookie=n+"="+escape(value)+"; path="+((path)?path:"/")+";";},clear:function(name,path){var d=new Date();d.setTime(d.getTime()-1);var n=gloader.settings.ns+"."+name;document.cookie=n+"=; path="+((path)?path:"/")+"; expires=Thu, 01-Jan-70 00:00:01 GMT;";}},loadOverride:function(version){var current=gloader.settings.get("override");version=version||prompt("Enter version",current?current:"");if(version===""){gloader.settings.clear("override");}else{if(version!==null){gloader.settings.set("override",version);}}location.reload();},loadDebug:function(){gloader.settings.set("debug","1");location.reload();},unloadDebug:function(){gloader.settings.clear("debug");location.reload();},expect:function(srcFile){srcFile=""+srcFile;var modsInFile=[];var modId;for(modId in gloader.map.js){if(gloader.map.js[modId]==srcFile){modsInFile.push(modId);gloader._expects[modId]=(gloader._expects[modId]||0)+1;}}},load:function(){var r={};if(typeof arguments[arguments.length-1].length=="undefined"){r=arguments[arguments.length-1];arguments.length--;}var newRequest=new gloader.Request(r);gloader._requests.push(newRequest);var mods=[];var override=gloader.settings.get("override");for(var i=0;i0){newRequest.status=gloader.Request.WAITING;gloader.request(ids,newRequest.async);gloader.resolve();}else{newRequest.complete();}},request:function(mIds,async){for(var i=0;i=gloader.Module.FETCHED);gloader.fetch(gloader._modules[m],async,force);}}},fetch:function(m,async,force){gloader._modules[m.id].async=async;var cssSrc=gloader.map.css[m.id];if(force||(cssSrc&&!gloader._fetched[cssSrc])){gloader._fetched[cssSrc]=1;if(document){var headElement;if(headElement=document.getElementsByTagName("head")[0]){var link;if(link=document.createElement("link")){link.href=cssSrc;link.rel="stylesheet";link.type="text/css";link.className="gloaded";headElement.appendChild(link);}}else{document.write('');}}}if(!force&&gloader._modules[m.id].status>=gloader.Module.FETCHED){return false;}gloader._modules[m.id].status=gloader.Module.FETCHED;var jsSrc=gloader.map.js[m.id];if(!jsSrc){var msg="The gloader map is missing a JavaScript filepath for the module: "+m.id;var maps=[];for(var included_map in gloader.map._include){maps.push(included_map);}msg+=".\rMaps included are: "+maps.join(", ")+".";gloader._errors.push(msg);throw new Error(msg);}if(force||(jsSrc&&!gloader._fetched[jsSrc])){gloader._fetched[jsSrc]=1;gloader.expect(jsSrc);if(async){var headElement=document.getElementsByTagName("head")[0];var scriptElement=document.createElement("script");scriptElement.type="text/javascript";scriptElement.src=jsSrc;headElement.appendChild(scriptElement);}else{document.write('