Repository: requirejs/alameda
Branch: master
Commit: 3d3c32c73cfb
Files: 73
Total size: 207.6 KB
Directory structure:
gitextract_3mab732j/
├── .gitignore
├── .npmignore
├── LICENSE
├── README.md
├── alameda.js
├── bower.json
├── copyrequirejstests.sh
├── package.json
├── shrinktest.sh
└── tests/
├── all.js
├── circular/
│ ├── 414/
│ │ ├── 414.html
│ │ └── 414.js
│ ├── circular.html
│ └── transpiler/
│ ├── transpiler.html
│ └── transpiler.js
├── context/
│ └── context.html
├── dataMainBaseUrl/
│ ├── dataMainBaseUrl.html
│ └── js/
│ └── sub/
│ ├── main.js
│ └── other.js
├── defineDouble/
│ └── defineDouble.html
├── doh/
│ ├── LICENSE
│ ├── README
│ ├── _browserRunner.js
│ ├── _nodeRunner.js
│ ├── _rhinoRunner.js
│ ├── _sounds/
│ │ └── LICENSE
│ ├── runner.html
│ ├── runner.js
│ └── runner.sh
├── emptyRequire/
│ └── emptyRequire.html
├── errback/
│ └── errback.html
├── hasOwnProperty/
│ └── hasOwnProperty.html
├── index.html
├── insertRequire/
│ └── insertRequire.html
├── mapConfig/
│ ├── mapConfig.html
│ ├── mapConfig.js
│ ├── mapConfigPlugin.html
│ ├── mapConfigPlugin.js
│ ├── mapConfigSpecificity.html
│ ├── mapConfigSpecificity.js
│ ├── mapConfigStar.html
│ ├── mapConfigStar.js
│ ├── mapConfigStarAdapter.html
│ └── mapConfigStarAdapter.js
├── moduleConfig/
│ ├── moduleConfig.html
│ └── moduleConfig.js
├── onNodeCreated/
│ ├── a.js
│ ├── b.js
│ └── onNodeCreated.html
├── plugins/
│ ├── coffee.html
│ ├── coffee.js
│ ├── pluginMapSameName/
│ │ ├── pluginMapSameName.html
│ │ └── pluginMapSameName.js
│ ├── plugins.html
│ ├── plugins.js
│ ├── pluginsConfig/
│ │ ├── pluginsConfig.html
│ │ └── pluginsConfig.js
│ ├── text.html
│ └── text.js
├── preserveDeps/
│ └── preserveDeps.html
├── promiseRequire/
│ ├── app.js
│ ├── bar.js
│ └── promiseRequire.html
├── relativePaths/
│ └── relativePaths.html
├── runner.js
├── server.js
├── shim/
│ ├── shim.html
│ └── shim.js
├── simple.html
├── simple.js
├── specialDeps/
│ ├── specialDeps-tests.js
│ └── specialDeps.html
└── timeoutErrors/
└── timeoutErrors.html
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
alameda.min.js
alameda.min.js.gz
copy-to-prim.sh
require.js
testBaseUrl.js
tests-requirejs
================================================
FILE: .npmignore
================================================
LICENSE
alameda.min.js
alameda.min.js.gz
copyrequirejstests.sh
copy-to-prim.sh
require.js
shrinktest.sh
testBaseUrl.js
tests
tests-requirejs
================================================
FILE: LICENSE
================================================
Copyright jQuery Foundation and other contributors, https://jquery.org/
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/requirejs/alameda
The following license applies to all parts of this software except as
documented below:
====
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
====
Copyright and related rights for sample code are waived via CC0. Sample
code is defined as all source code displayed within the prose of the
documentation.
CC0: http://creativecommons.org/publicdomain/zero/1.0/
====
Files located in the node_modules directory, and certain utilities used
to build or test the software in the tests and tests-requirejs directories, are
externally maintained libraries used by this software which have their own
licenses; we recommend you read them, as their terms may differ from the
terms above.
================================================
FILE: README.md
================================================
# alameda
An AMD loader, like [requirejs](http://requirejs.org), but with the following
implementation changes:
* Assumes Promises are available in the JS environment.
* Targets "modern" web browsers that implement standardized script.onload behavior: execute load listener right after script execution, something IE9 and below did not do.
* Assumes browser support for Array.isArray, array extras, ES5 features.
* Does not support a couple of less-used APIs (see tests section below).
These changes means alameda is around 35% smaller than requirejs, 4.1 KB vs 6.4 KB, minified+gzipped sizes.
Browser support: browsers that [natively provide Promises](http://caniuse.com/#feat=promises). If you need to support IE 10 and 11, the [alameda-prim](https://github.com/requirejs/alameda-prim) project includes a private promise shim.
You can continue to use requirejs and the r.js optimizer for other scenarios.
The r.js optimizer works well with alameda-based projects.
## Install
[Latest release information](https://github.com/requirejs/alameda/releases)
If using a package manager:
```
npm install alameda
# or
[npm | bower | volo] install requirejs/alameda
```
## API
alameda supports [the requirejs API](http://requirejs.org/docs/api.html). It even
declares `requirejs`, to make passing the requirejs tests easier. alameda also
has a good chance of becoming requirejs in a far-future requirejs version.
There are some differences with requirejs though:
### require promise
`require([])` will return a promise. The success callback passed to `require([])` should return a value if you want a value to be passed to the next .then() in the promise chain.
```javascript
require(['a', 'b'], function(a, b) {
// succes callback. Return a value for the next part in the promise chain.
return [a, b];
}).then(function(mods) {
//mods[0] is the 'a' module, mods[1] is the 'b' module in this case.
});
```
### config.defaultErrback
In requirejs and alameda, with this sort of call, the errback will be called if there is an error in either loading `['a', 'b']` or if the success callback throws an error.
```javascript
require(['a', 'b'], function(a, b) {
// success callback
}, function(err) {
// errback, called if 'a', 'b' do not load, or
// if the success callback is called.
});
```
So, the errback operates like:
```javascript
require([], function() {}).catch(function(err) {})`;
````
If you do not pass an errback into the require() call, and instead use a .then() or .catch() to deal with the error, you still may see the error surface outside. This is done because browsers do not all show unhandled errors in a promise chain, and the require() call itself does not know if an error handler was chained on the end, so it generates an error to make debugging and development easier.
However, if you are properly chaining error handlers but do not pass an errback as the third arg to the require([]) call, then you can turn off this extra error surfacing by doing:
```javascript
requirejs.config({
defaultErrback: null
});
```
If you pass a function for the `defaultErrback` value, then that will be used instead of the default "delayedError" handler used by alameda to surface the error.
## onError is context-specific
When using contexts, in requirejs, all top level errors would bubble up to requirejs.onError, but in alameda, the context's onError is called instead. Example:
```javascript
var fooReq = requirejs.config({ context: 'foo' });
requirejs.onError = function () { console.log('requirejs.onError'); };
fooReq.onError = function () { console.log('fooReq.onError'); };
fooReq(['nonexistent']);
// In alameda, fooReq.onError() is called, in requirejs, requirejs.onError is called.
```
## onResourceLoad
requirejs supports a hook into its internals, [onResourceLoad](https://github.com/requirejs/requirejs/wiki/Internal-API:-onResourceLoad). alameda supports an onResourceLoad function too, but the arguments passed to the function are objects that have different property names than the ones in requirejs.
This is the general signature, which is the same between alameda and requirejs:
```javascript
alameda.onResourceLoad = function (context, map, depArray) {};
```
The differences between property names in the different argument objects is described below. See the [onResourceLoad page](https://github.com/requirejs/requirejs/wiki/Internal-API:-onResourceLoad) for the description of the arguments.
### context
| alameda | requirejs |
| ------- | --------- |
| `id` | `contextName` |
### map
| alameda | requirejs |
| ------- | --------- |
| `pr` | `prefix` |
| `n` | `name` |
| n/a | `parentMap` |
| `url` | `url` |
| n/a | `originalName` |
| `id` | `fullName` |
### depArray
An array of `map` objects with the same properties as the `map` listing above.
## License
MIT
## Code of Conduct
[jQuery Foundation Code of Conduct](https://jquery.org/conduct/).
## Running tests
The tests are pulled from almond and requirejs. All tests should be served
through a local web server, as the text loader plugin is used for some tests,
and some browsers restrict local XHR usage when the files are served from
a `file://` URL.
### Bundled tests
To run the tests that are just part of this repo, open `tests/index.html` in
a web browser.
### requirejs tests
To run the requirejs tests, first make sure the following projects have been cloned and are **siblings** to the the alameda repo:
* https://github.com/requirejs/requirejs
* https://github.com/requirejs/domReady
* https://github.com/requirejs/text
* https://github.com/requirejs/i18n
Then do the following:
* symlink alameda.js to require.js
* ./copyrequirejstests.sh
#### requirejs tests that do not pass
* require.undef()-related tests.
* onResourceLoadNestedRequire: depends on implementing requirejs.onResourceLoad
hook used for builds/some third party tools. This API is not required for normal
module loading.
## How to get help
* Open issues in the [issue tracker](https://github.com/requirejs/alameda/issues).
* Contact the [requirejs list](https://groups.google.com/group/requirejs).
================================================
FILE: alameda.js
================================================
/**
* @license alameda 1.4.0 Copyright jQuery Foundation and other contributors.
* Released under MIT license, https://github.com/requirejs/alameda/blob/master/LICENSE
*/
// Going sloppy because loader plugin execs may depend on non-strict execution.
/*jslint sloppy: true, nomen: true, regexp: true */
/*global document, navigator, importScripts, Promise, setTimeout */
var requirejs, require, define;
(function (global, Promise, undef) {
if (!Promise) {
throw new Error('No Promise implementation available');
}
var topReq, dataMain, src, subPath,
bootstrapConfig = requirejs || require,
hasOwn = Object.prototype.hasOwnProperty,
contexts = {},
queue = [],
currDirRegExp = /^\.\//,
urlRegExp = /^\/|\:|\?|\.js$/,
commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg,
cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
jsSuffixRegExp = /\.js$/,
slice = Array.prototype.slice;
if (typeof requirejs === 'function') {
return;
}
var asap = Promise.resolve(undefined);
// Could match something like ')//comment', do not lose the prefix to comment.
function commentReplace(match, singlePrefix) {
return singlePrefix || '';
}
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
function getOwn(obj, prop) {
return obj && hasProp(obj, prop) && obj[prop];
}
function obj() {
return Object.create(null);
}
/**
* 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 === 'object' && value &&
!Array.isArray(value) && typeof value !== 'function' &&
!(value instanceof RegExp)) {
if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}
// Allow getting a global that expressed in
// dot notation, like 'a.b.c'.
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
value.split('.').forEach(function (part) {
g = g[part];
});
return g;
}
function newContext(contextName) {
var req, main, makeMap, callDep, handlers, checkingLater, load, context,
defined = obj(),
waiting = obj(),
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: {},
bundles: {},
pkgs: {},
shim: {},
config: {}
},
mapCache = obj(),
requireDeferreds = [],
deferreds = obj(),
calledDefine = obj(),
calledPlugin = obj(),
loadCount = 0,
startTime = (new Date()).getTime(),
errCount = 0,
trackedErrors = obj(),
urlFetched = obj(),
bundlesMap = obj(),
asyncResolve = Promise.resolve();
/**
* 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, length = ary.length;
for (i = 0; i < length; i++) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
// If at the start, or previous value is still ..,
// keep them so that when converted to a path it may
// still work when converted to a path, even though
// as an ID it is less than ideal. In larger point
// releases, may be better to just kick out an error.
if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
continue;
} 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 pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
foundMap, foundI, foundStarMap, starI,
baseParts = baseName && baseName.split('/'),
normalizedBaseParts = baseParts,
map = config.map,
starMap = map && map['*'];
//Adjust any relative paths.
if (name) {
name = name.split('/');
lastIndex = name.length - 1;
// If wanting node ID compatibility, strip .js from end
// of IDs. Have to do this here, and not in nameToUrl
// because node allows either .js or non .js to map
// to same file.
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
// Starts with a '.' so need the baseName
if (name[0].charAt(0) === '.' && baseParts) {
//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);
}
trimDots(name);
name = name.join('/');
}
// Apply map config if available.
if (applyMap && map && (baseParts || starMap)) {
nameParts = name.split('/');
outerLoop: 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 outerLoop;
}
}
}
}
// 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('/');
}
}
// If the name points to a package's name, use
// the package main instead.
pkgMain = getOwn(config.pkgs, name);
return pkgMain ? pkgMain : name;
}
function makeShimExports(value) {
function fn() {
var ret;
if (value.init) {
ret = value.init.apply(global, arguments);
}
return ret || (value.exports && getGlobal(value.exports));
}
return fn;
}
function takeQueue(anonId) {
var i, id, args, shim;
for (i = 0; i < queue.length; i += 1) {
// Peek to see if anon
if (typeof queue[i][0] !== 'string') {
if (anonId) {
queue[i].unshift(anonId);
anonId = undef;
} else {
// Not our anon module, stop.
break;
}
}
args = queue.shift();
id = args[0];
i -= 1;
if (!(id in defined) && !(id in waiting)) {
if (id in deferreds) {
main.apply(undef, args);
} else {
waiting[id] = args;
}
}
}
// if get to the end and still have anonId, then could be
// a shimmed dependency.
if (anonId) {
shim = getOwn(config.shim, anonId) || {};
main(anonId, shim.deps || [], shim.exportsFn);
}
}
function makeRequire(relName, topLevel) {
var req = function (deps, callback, errback, alt) {
var name, cfg;
if (topLevel) {
takeQueue();
}
if (typeof deps === "string") {
if (handlers[deps]) {
return handlers[deps](relName);
}
// Just return the module wanted. In this scenario, the
// deps arg is the module name, and second arg (if passed)
// is just the relName.
// Normalize module name, if it contains . or ..
name = makeMap(deps, relName, true).id;
if (!(name in defined)) {
throw new Error('Not loaded: ' + name);
}
return defined[name];
} else if (deps && !Array.isArray(deps)) {
// deps is a config object, not an array.
cfg = deps;
deps = undef;
if (Array.isArray(callback)) {
// callback is an array, which means it is a dependency list.
// Adjust args if there are dependencies
deps = callback;
callback = errback;
errback = alt;
}
if (topLevel) {
// Could be a new context, so call returned require
return req.config(cfg)(deps, callback, errback);
}
}
// Support require(['a'])
callback = callback || function () {
// In case used later as a promise then value, return the
// arguments as an array.
return slice.call(arguments, 0);
};
// Complete async to maintain expected execution semantics.
return asyncResolve.then(function () {
// Grab any modules that were defined after a require call.
takeQueue();
return main(undef, deps || [], callback, errback, relName);
});
};
req.isBrowser = typeof document !== 'undefined' &&
typeof navigator !== 'undefined';
req.nameToUrl = function (moduleName, ext, skipExt) {
var paths, syms, i, parentModule, url,
parentPath, bundleId,
pkgMain = getOwn(config.pkgs, moduleName);
if (pkgMain) {
moduleName = pkgMain;
}
bundleId = getOwn(bundlesMap, moduleName);
if (bundleId) {
return req.nameToUrl(bundleId, ext, skipExt);
}
// 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 (urlRegExp.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;
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('/');
parentPath = getOwn(paths, parentModule);
if (parentPath) {
// If an array, it means there are a few choices,
// Choose the one that is desired
if (Array.isArray(parentPath)) {
parentPath = parentPath[0];
}
syms.splice(0, i, parentPath);
break;
}
}
// Join the path parts together, then figure out if baseUrl is needed.
url = syms.join('/');
url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js'));
url = (url.charAt(0) === '/' ||
url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
}
return config.urlArgs && !/^blob\:/.test(url) ?
url + config.urlArgs(moduleName, url) : url;
};
/**
* 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.
*/
req.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 req.nameToUrl(normalize(moduleNamePlusExt, relName), ext, true);
};
req.defined = function (id) {
return makeMap(id, relName, true).id in defined;
};
req.specified = function (id) {
id = makeMap(id, relName, true).id;
return id in defined || id in deferreds;
};
return req;
}
function resolve(name, d, value) {
if (name) {
defined[name] = value;
if (requirejs.onResourceLoad) {
requirejs.onResourceLoad(context, d.map, d.deps);
}
}
d.finished = true;
d.resolve(value);
}
function reject(d, err) {
d.finished = true;
d.rejected = true;
d.reject(err);
}
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName, true);
};
}
function defineModule(d) {
d.factoryCalled = true;
var ret,
name = d.map.id;
try {
ret = context.execCb(name, d.factory, d.values, defined[name]);
} catch(err) {
return reject(d, err);
}
if (name) {
// Favor return value over exports. If node/cjs in play,
// then will not have a return value anyway. Favor
// module.exports assignment over exports object.
if (ret === undef) {
if (d.cjsModule) {
ret = d.cjsModule.exports;
} else if (d.usingExports) {
ret = defined[name];
}
}
} else {
// Remove the require deferred from the list to
// make cycle searching faster. Do not need to track
// it anymore either.
requireDeferreds.splice(requireDeferreds.indexOf(d), 1);
}
resolve(name, d, ret);
}
// This method is attached to every module deferred,
// so the "this" in here is the module deferred object.
function depFinished(val, i) {
if (!this.rejected && !this.depDefined[i]) {
this.depDefined[i] = true;
this.depCount += 1;
this.values[i] = val;
if (!this.depending && this.depCount === this.depMax) {
defineModule(this);
}
}
}
function makeDefer(name, calculatedMap) {
var d = {};
d.promise = new Promise(function (resolve, reject) {
d.resolve = resolve;
d.reject = function(err) {
if (!name) {
requireDeferreds.splice(requireDeferreds.indexOf(d), 1);
}
reject(err);
};
});
d.map = name ? (calculatedMap || makeMap(name)) : {};
d.depCount = 0;
d.depMax = 0;
d.values = [];
d.depDefined = [];
d.depFinished = depFinished;
if (d.map.pr) {
// Plugin resource ID, implicitly
// depends on plugin. Track it in deps
// so cycle breaking can work
d.deps = [makeMap(d.map.pr)];
}
return d;
}
function getDefer(name, calculatedMap) {
var d;
if (name) {
d = (name in deferreds) && deferreds[name];
if (!d) {
d = deferreds[name] = makeDefer(name, calculatedMap);
}
} else {
d = makeDefer();
requireDeferreds.push(d);
}
return d;
}
function makeErrback(d, name) {
return function (err) {
if (!d.rejected) {
if (!err.dynaId) {
err.dynaId = 'id' + (errCount += 1);
err.requireModules = [name];
}
reject(d, err);
}
};
}
function waitForDep(depMap, relName, d, i) {
d.depMax += 1;
// Do the fail at the end to catch errors
// in the then callback execution.
callDep(depMap, relName).then(function (val) {
d.depFinished(val, i);
}, makeErrback(d, depMap.id)).catch(makeErrback(d, d.map.id));
}
function makeLoad(id) {
var fromTextCalled;
function load(value) {
// Protect against older plugins that call load after
// calling load.fromText
if (!fromTextCalled) {
resolve(id, getDefer(id), value);
}
}
load.error = function (err) {
reject(getDefer(id), err);
};
load.fromText = function (text, textAlt) {
/*jslint evil: true */
var d = getDefer(id),
map = makeMap(makeMap(id).n),
plainId = map.id,
execError;
fromTextCalled = true;
// Set up the factory just to be a return of the value from
// plainId.
d.factory = function (p, val) {
return val;
};
// As of requirejs 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;
}
// Transfer any config to this other module.
if (hasProp(config.config, id)) {
config.config[plainId] = config.config[id];
}
try {
req.exec(text);
} catch (e) {
execError = new Error('fromText eval for ' + plainId +
' failed: ' + e);
execError.requireType = 'fromtexteval';
reject(d, execError);
}
// Execute any waiting define created by the plainId
takeQueue(plainId);
// Mark this as a dependency for the plugin
// resource
d.deps = [map];
waitForDep(map, null, d, d.deps.length);
};
return load;
}
load = typeof importScripts === 'function' ?
function (map) {
var url = map.url;
if (urlFetched[url]) {
return;
}
urlFetched[url] = true;
// Ask for the deferred so loading is triggered.
// Do this before loading, since loading is sync.
getDefer(map.id);
importScripts(url);
takeQueue(map.id);
} :
function (map) {
var script,
id = map.id,
url = map.url;
if (urlFetched[url]) {
return;
}
urlFetched[url] = true;
script = document.createElement('script');
script.setAttribute('data-requiremodule', id);
script.type = config.scriptType || 'text/javascript';
script.charset = 'utf-8';
script.async = true;
loadCount += 1;
script.addEventListener('load', function () {
loadCount -= 1;
takeQueue(id);
}, false);
script.addEventListener('error', function () {
loadCount -= 1;
var err,
pathConfig = getOwn(config.paths, id);
if (pathConfig && Array.isArray(pathConfig) &&
pathConfig.length > 1) {
script.parentNode.removeChild(script);
// Pop off the first array value, since it failed, and
// retry
pathConfig.shift();
var d = getDefer(id);
d.map = makeMap(id);
// mapCache will have returned previous map value, update the
// url, which will also update mapCache value.
d.map.url = req.nameToUrl(id);
load(d.map);
} else {
err = new Error('Load failed: ' + id + ': ' + script.src);
err.requireModules = [id];
err.requireType = 'scripterror';
reject(getDefer(id), err);
}
}, false);
script.src = url;
if (config.onNodeCreated) {
config.onNodeCreated(script, config, id, url);
}
// If the script is cached, IE10 executes the script body and the
// onload handler synchronously here. That's a spec violation,
// so be sure to do this asynchronously.
if (document.documentMode === 10) {
asap.then(function() {
document.head.appendChild(script);
});
} else {
document.head.appendChild(script);
}
};
function callPlugin(plugin, map, relName) {
plugin.load(map.n, makeRequire(relName), makeLoad(map.id), config);
}
callDep = function (map, relName) {
var args, bundleId,
name = map.id,
shim = config.shim[name];
if (name in waiting) {
args = waiting[name];
delete waiting[name];
main.apply(undef, args);
} else if (!(name in deferreds)) {
if (map.pr) {
// If a bundles config, then just load that file instead to
// resolve the plugin, as it is built into that bundle.
if ((bundleId = getOwn(bundlesMap, name))) {
map.url = req.nameToUrl(bundleId);
load(map);
} else {
return callDep(makeMap(map.pr)).then(function (plugin) {
// Redo map now that plugin is known to be loaded
var newMap = map.prn ? map : makeMap(name, relName, true),
newId = newMap.id,
shim = getOwn(config.shim, newId);
// Make sure to only call load once per resource. Many
// calls could have been queued waiting for plugin to load.
if (!(newId in calledPlugin)) {
calledPlugin[newId] = true;
if (shim && shim.deps) {
req(shim.deps, function () {
callPlugin(plugin, newMap, relName);
});
} else {
callPlugin(plugin, newMap, relName);
}
}
return getDefer(newId).promise;
});
}
} else if (shim && shim.deps) {
req(shim.deps, function () {
load(map);
});
} else {
load(map);
}
}
return getDefer(name).promise;
};
// 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];
}
/**
* Makes a name map, normalizing the name, and using a plugin
* for normalization if necessary. Grabs a ref to plugin
* too, as an optimization.
*/
makeMap = function (name, relName, applyMap) {
if (typeof name !== 'string') {
return name;
}
var plugin, url, parts, prefix, result, prefixNormalized,
cacheKey = name + ' & ' + (relName || '') + ' & ' + !!applyMap;
parts = splitPrefix(name);
prefix = parts[0];
name = parts[1];
if (!prefix && (cacheKey in mapCache)) {
return mapCache[cacheKey];
}
if (prefix) {
prefix = normalize(prefix, relName, applyMap);
plugin = (prefix in defined) && defined[prefix];
}
// Normalize according
if (prefix) {
if (plugin && plugin.normalize) {
name = plugin.normalize(name, makeNormalize(relName));
prefixNormalized = true;
} else {
// If nested plugin references, then do not try to
// normalize, as it will not normalize correctly. This
// places a restriction on resourceIds, and the longer
// term solution is not to normalize until plugins are
// loaded and all normalizations to allow for async
// loading of a loader plugin. But for now, fixes the
// common uses. Details in requirejs#1131
name = name.indexOf('!') === -1 ?
normalize(name, relName, applyMap) :
name;
}
} else {
name = normalize(name, relName, applyMap);
parts = splitPrefix(name);
prefix = parts[0];
name = parts[1];
url = req.nameToUrl(name);
}
// Using ridiculous property names for space reasons
result = {
id: prefix ? prefix + '!' + name : name, // fullName
n: name,
pr: prefix,
url: url,
prn: prefix && prefixNormalized
};
if (!prefix) {
mapCache[cacheKey] = result;
}
return result;
};
handlers = {
require: function (name) {
return makeRequire(name);
},
exports: function (name) {
var e = defined[name];
if (typeof e !== 'undefined') {
return e;
} else {
return (defined[name] = {});
}
},
module: function (name, url) {
return {
id: name,
uri: url || '',
exports: handlers.exports(name),
config: function () {
return getOwn(config.config, name) || {};
}
};
}
};
function breakCycle(d, traced, processed) {
var id = d.map.id;
traced[id] = true;
if (!d.finished && d.deps) {
d.deps.forEach(function (depMap) {
var depId = depMap.id,
dep = !hasProp(handlers, depId) && getDefer(depId, depMap);
// 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 && !dep.finished && !processed[depId]) {
if (hasProp(traced, depId)) {
d.deps.forEach(function (depMap, i) {
if (depMap.id === depId) {
d.depFinished(defined[depId], i);
}
});
} else {
breakCycle(dep, traced, processed);
}
}
});
}
processed[id] = true;
}
function check(d) {
var err, mid, dfd,
notFinished = [],
waitInterval = config.waitSeconds * 1000,
// It is possible to disable the wait interval by using waitSeconds 0.
expired = waitInterval &&
(startTime + waitInterval) < (new Date()).getTime();
if (loadCount === 0) {
// If passed in a deferred, it is for a specific require call.
// Could be a sync case that needs resolution right away.
// Otherwise, if no deferred, means it was the last ditch
// timeout-based check, so check all waiting require deferreds.
if (d) {
if (!d.finished) {
breakCycle(d, {}, {});
}
} else if (requireDeferreds.length) {
requireDeferreds.forEach(function (d) {
breakCycle(d, {}, {});
});
}
}
// 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) {
// If wait time expired, throw error of unloaded modules.
for (mid in deferreds) {
dfd = deferreds[mid];
if (!dfd.finished) {
notFinished.push(dfd.map.id);
}
}
err = new Error('Timeout for modules: ' + notFinished);
err.requireModules = notFinished;
err.requireType = 'timeout';
notFinished.forEach(function (id) {
reject(getDefer(id), err);
});
} else if (loadCount || requireDeferreds.length) {
// Something is still waiting to load. Wait for it, but only
// if a later check is not already scheduled. Using setTimeout
// because want other things in the event loop to happen,
// to help in dependency resolution, and this is really a
// last ditch check, mostly for detecting timeouts (cycles
// should come through the main() use of check()), so it can
// wait a bit before doing the final check.
if (!checkingLater) {
checkingLater = true;
setTimeout(function () {
checkingLater = false;
check();
}, 70);
}
}
}
// Used to break out of the promise try/catch chains.
function delayedError(e) {
setTimeout(function () {
if (!e.dynaId || !trackedErrors[e.dynaId]) {
trackedErrors[e.dynaId] = true;
req.onError(e);
}
});
return e;
}
main = function (name, deps, factory, errback, relName) {
if (name) {
// Only allow main calling once per module.
if (name in calledDefine) {
return;
}
calledDefine[name] = true;
}
var d = getDefer(name);
// This module may not have dependencies
if (deps && !Array.isArray(deps)) {
// deps is not an array, so probably means
// an object literal or factory function for
// the value. Adjust args.
factory = deps;
deps = [];
}
// Create fresh array instead of modifying passed in value.
deps = deps ? slice.call(deps, 0) : null;
if (!errback) {
if (hasProp(config, 'defaultErrback')) {
if (config.defaultErrback) {
errback = config.defaultErrback;
}
} else {
errback = delayedError;
}
}
if (errback) {
d.promise.catch(errback);
}
// Use name if no relName
relName = relName || name;
// Call the factory to define the module, if necessary.
if (typeof factory === 'function') {
if (!deps.length && factory.length) {
// Remove comments from the callback string,
// look for require calls, and pull them into the dependencies,
// but only if there are function args.
factory
.toString()
.replace(commentRegExp, commentReplace)
.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 = (factory.length === 1 ?
['require'] :
['require', 'exports', 'module']).concat(deps);
}
// Save info for use later.
d.factory = factory;
d.deps = deps;
d.depending = true;
deps.forEach(function (depName, i) {
var depMap;
deps[i] = depMap = makeMap(depName, relName, true);
depName = depMap.id;
// Fast path CommonJS standard dependencies.
if (depName === "require") {
d.values[i] = handlers.require(name);
} else if (depName === "exports") {
// CommonJS module spec 1.1
d.values[i] = handlers.exports(name);
d.usingExports = true;
} else if (depName === "module") {
// CommonJS module spec 1.1
d.values[i] = d.cjsModule = handlers.module(name, d.map.url);
} else if (depName === undefined) {
d.values[i] = undefined;
} else {
waitForDep(depMap, relName, d, i);
}
});
d.depending = false;
// Some modules just depend on the require, exports, modules, so
// trigger their definition here if so.
if (d.depCount === d.depMax) {
defineModule(d);
}
} else if (name) {
// May just be an object definition for the module. Only
// worry about defining if have a module name.
resolve(name, d, factory);
}
startTime = (new Date()).getTime();
if (!name) {
check(d);
}
return d.promise;
};
req = makeRequire(null, true);
/*
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
req.config = function (cfg) {
if (cfg.context && cfg.context !== contextName) {
var existingContext = getOwn(contexts, cfg.context);
if (existingContext) {
return existingContext.req.config(cfg);
} else {
return newContext(cfg.context).config(cfg);
}
}
// Since config changed, mapCache may not be valid any more.
mapCache = obj();
// Make sure the baseUrl ends in a slash.
if (cfg.baseUrl) {
if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
cfg.baseUrl += '/';
}
}
// Convert old style urlArgs string to a function.
if (typeof cfg.urlArgs === 'string') {
var urlArgs = cfg.urlArgs;
cfg.urlArgs = function(id, url) {
return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs;
};
}
// Save off the paths and packages since they require special processing,
// they are additive.
var shim = config.shim,
objs = {
paths: true,
bundles: true,
config: true,
map: true
};
eachProp(cfg, function (value, prop) {
if (objs[prop]) {
if (!config[prop]) {
config[prop] = {};
}
mixin(config[prop], value, true, true);
} else {
config[prop] = value;
}
});
// Reverse map the bundles
if (cfg.bundles) {
eachProp(cfg.bundles, function (value, prop) {
value.forEach(function (v) {
if (v !== prop) {
bundlesMap[v] = prop;
}
});
});
}
// Merge shim
if (cfg.shim) {
eachProp(cfg.shim, function (value, id) {
// Normalize the structure
if (Array.isArray(value)) {
value = {
deps: value
};
}
if ((value.exports || value.init) && !value.exportsFn) {
value.exportsFn = makeShimExports(value);
}
shim[id] = value;
});
config.shim = shim;
}
// Adjust packages if necessary.
if (cfg.packages) {
cfg.packages.forEach(function (pkgObj) {
var location, name;
pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
name = pkgObj.name;
location = pkgObj.location;
if (location) {
config.paths[name] = pkgObj.location;
}
// Save pointer to main module ID for pkg 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.
config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
.replace(currDirRegExp, '')
.replace(jsSuffixRegExp, '');
});
}
// 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) {
req(cfg.deps, cfg.callback);
}
return req;
};
req.onError = function (err) {
throw err;
};
context = {
id: contextName,
defined: defined,
waiting: waiting,
config: config,
deferreds: deferreds,
req: req,
execCb: function execCb(name, callback, args, exports) {
return callback.apply(exports, args);
}
};
contexts[contextName] = context;
return req;
}
requirejs = topReq = newContext('_');
if (typeof require !== 'function') {
require = topReq;
}
/**
* 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.
*/
topReq.exec = function (text) {
/*jslint evil: true */
return eval(text);
};
topReq.contexts = contexts;
define = function () {
queue.push(slice.call(arguments, 0));
};
define.amd = {
jQuery: true
};
if (bootstrapConfig) {
topReq.config(bootstrapConfig);
}
// data-main support.
if (topReq.isBrowser && !contexts._.config.skipDataMain) {
dataMain = document.querySelectorAll('script[data-main]')[0];
dataMain = dataMain && dataMain.getAttribute('data-main');
if (dataMain) {
// Strip off any trailing .js since dataMain is now
// like a module name.
dataMain = dataMain.replace(jsSuffixRegExp, '');
// Set final baseUrl if there is not already an explicit one,
// but only do so if the data-main value is not a loader plugin
// module ID.
if ((!bootstrapConfig || !bootstrapConfig.baseUrl) &&
dataMain.indexOf('!') === -1) {
// Pull off the directory of data-main for use as the
// baseUrl.
src = dataMain.split('/');
dataMain = src.pop();
subPath = src.length ? src.join('/') + '/' : './';
topReq.config({baseUrl: subPath});
}
topReq([dataMain]);
}
}
}(this, (typeof Promise !== 'undefined' ? Promise : undefined)));
================================================
FILE: bower.json
================================================
{
"name": "alameda",
"version": "1.4.0",
"ignore": [
".gitignore",
".npmignore",
"node_modules",
"package.json",
"README.md",
"tests",
"tests-requirejs",
"copyrequirejstests.sh",
"testBaseUrl.js"
],
"homepage": "https://github.com/requirejs/alameda",
"authors": [
"jrburke.com"
],
"description": "AMD loader, like requirejs, but with promises and for modern browsers",
"main": "alameda.js",
"license": [
"MIT"
]
}
================================================
FILE: copyrequirejstests.sh
================================================
#!/bin/bash
cp -r ../requirejs/testBaseUrl.js ./testBaseUrl.js
cp -r ../requirejs/tests ./tests-requirejs
================================================
FILE: package.json
================================================
{
"name": "alameda",
"description": "AMD loader, like requirejs, but with promises and for modern browsers",
"version": "1.4.0",
"homepage": "http://github.com/requirejs/alameda",
"author": "James Burke A set of modules have multiple cycles in them, but the require() that
uses the top module in that bundle should get a fully constructed
module set.More info. Check console for messages Test circular dependencies with alameda. More info:
17. Check console for messages Test support for transpiled modules with cycles in them More info:
356. Check console for messages Two requirejs.config calls to the same context should operate on the same context.
More info Check console for messages Makes sure alameda sets baseUrl from data-main. More info:
3. Check console for messages Make sure a double define only uses the first one.
More info Check console for messages Empty require array should still call callback.
More info Check console for messages Test the use of errbacks in a require call. While alameda does not
support calling an errback (all modules should be built in and usable),
alameda should not throw any errors if they are used. Check console for messages Check console for messages Make sure alameda can handle juse a plain require(['a']) used by
r.js's insertRequire build option. More info:
27. Check console for messages Test using the map config. Check console for messages Test using the map config with plugin value after a build. Check console for messages Test map config specificity.
More info. Check console for messages Test using '*' in the map config. Check console for messages Test using '*' with an adapter in the built map config. Check console for messages Check console for messages Check console for messages Check console for messages Test using the map config with plugins. but include a map value that
contains the original name of the plugin, to confirm the map translation
is only done once:
484 Check console for messages Check console for messages Test passing the loader config to the .load() method on the plugin, to
match the behavior of requirejs.alameda: requirejs#414: Multi-cycle Bundle Test
alameda: circular Test
alameda: Circular Transpiler Plugin Test
alameda: Context Test
alameda: dataMain baseUrl Test
alameda: Define Double Test
" +
"NUMBER OF TRIALS: " + fResults.trials.length + "
";
//Figure out the average test pass cost.
var i;
var iAvgArray = [];
var tAvgArray = [];
for(i = 0; i < fResults.trials.length; i++){
iAvgArray.push(fResults.trials[i].average);
tAvgArray.push(fResults.trials[i].executionTime);
}
results += "AVERAGE TRIAL EXECUTION TIME: " + doh.average(tAvgArray).toFixed(10) + "ms.
";
results += "MAXIMUM TEST ITERATION TIME: " + doh.max(iAvgArray).toFixed(10) + "ms.
";
results += "MINIMUM TEST ITERATION TIME: " + doh.min(iAvgArray).toFixed(10) + "ms.
";
results += "AVERAGE TEST ITERATION TIME: " + doh.average(iAvgArray).toFixed(10) + "ms.
";
results += "MEDIAN TEST ITERATION TIME: " + doh.median(iAvgArray).toFixed(10) + "ms.
";
results += "VARIANCE TEST ITERATION TIME: " + doh.variance(iAvgArray).toFixed(10) + "ms.
";
results += "STANDARD DEVIATION ON TEST ITERATION TIME: " + doh.standardDeviation(iAvgArray).toFixed(10) + "ms.
";
//Okay, attach it all in.
div.innerHTML = results;
div = document.createElement("div");
div.innerHTML = "Average Test Execution Time (in milliseconds, with median line)
";
ind.appendChild(div);
div = document.createElement("div");
dojo.style(div, "width", "600px");
dojo.style(div, "height", "250px");
ind.appendChild(div);
chartsToRender.push({
div: div,
title: "Average Test Execution Time",
data: iAvgArray
});
div = document.createElement("div");
div.innerHTML = "Average Trial Execution Time (in milliseconds, with median line)
";
ind.appendChild(div);
div = document.createElement("div");
dojo.style(div, "width", "600px");
dojo.style(div, "height", "250px");
ind.appendChild(div);
chartsToRender.push({
div: div,
title: "Average Trial Execution Time",
data: tAvgArray
});
}
}
//Lazy-render these to give the browser time and not appear locked.
var delayedRenders = function() {
if(chartsToRender.length){
var chartData = chartsToRender.shift();
plotResults(chartData.div, chartData.title, chartData.data);
}
doh.setTimeout(delayedRenders, 50);
};
doh.setTimeout(delayedRenders, 150);
}catch(e){
doh.debug(e);
}
}
or.apply(doh,arguments);
}
})(doh._report);
if(this["opera"] && opera.postError){
doh.debug = function(){
var msg = "";
for(var x=0; x
================================================
FILE: tests/doh/runner.js
================================================
// package system gunk.
//try{
// dojo.provide("doh.runner");
//}catch(e){
if(!this["doh"]){
doh = {};
}
//}
//
// Utility Functions and Classes
//
doh.selfTest = false;
doh.global = this;
doh.hitch = function(/*Object*/thisObject, /*Function|String*/method /*, ...*/){
var args = [];
for(var x=2; x
alameda Tests Via D.O.H.: The Dojo Objective Harness
Stopped
test
time
alameda: Empty Require Test
alameda: errback Test
alameda: hasOwnProperty Test
alameda tests
================================================
FILE: tests/insertRequire/insertRequire.html
================================================
alameda: insertRequire Test
alameda: Map Config Test
alameda: Map Config Plugin Built Test
alameda: Map Config Specificity Test
alameda: Map Config Star Test
alameda: Map Config Star Adapter Built Test
alameda: moduleConfig Test
alameda: onNodeCreated Test
alameda: Coffee Test
alameda: Plugin Map Same Name Test
alameda: Simple Test
alameda: Plugin Load Config Test
Check console for messages
================================================ FILE: tests/plugins/pluginsConfig/pluginsConfig.js ================================================ var expectedConfig; define('plugin/plugin',{ load: function (id, require, load, config) { expectedConfig = config; load(id); } }); require({ foo: 'bar', map: { '*': { 'plugin': 'plugin/plugin' } } }, ['plugin!foo'], function (value) { doh.register( 'pluginsConfig', [ function pluginsConfig(t){ t.is('bar', expectedConfig.foo); } ] ); doh.run(); }); ================================================ FILE: tests/plugins/text.html ================================================Check console for messages
================================================ FILE: tests/plugins/text.js ================================================ /** * @license RequireJS text 0.26.0 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, nomen: false, plusplus: false, strict: false */ /*global require: false, XMLHttpRequest: false, ActiveXObject: false, define: false, window: false, process: false, Packages: false, java: false, location: false */ (function () { var progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, bodyRegExp = /]*>\s*([\s\S]+)\s*<\/body>/im, hasLocation = typeof location !== 'undefined' && location.href, buildMap = []; define('text',[],function () { var text, get, fs; if (typeof window !== "undefined" && window.navigator && window.document) { get = function (url, callback) { var xhr = text.createXhr(); xhr.open('GET', url, true); xhr.onreadystatechange = function (evt) { //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { callback(xhr.responseText); } }; xhr.send(null); }; } else if (typeof process !== "undefined" && process.versions && !!process.versions.node) { //Using special require.nodeRequire, something added by r.js. fs = require.nodeRequire('fs'); get = function (url, callback) { callback(fs.readFileSync(url, 'utf8')); }; } else if (typeof Packages !== 'undefined') { //Why Java, why is this so awkward? get = function (url, callback) { var encoding = "utf-8", file = new java.io.File(url), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), stringBuffer, line, content = ''; 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); } stringBuffer.append(line); while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator); stringBuffer.append(line); } //Make sure we return a JavaScript string and not a Java string. content = String(stringBuffer.toString()); //String } finally { input.close(); } callback(content); }; } text = { version: '0.26.0', strip: function (content) { //Strips declarations so that external SVG and XML //documents can be added to a document without worry. Also, if the string //is an HTML document, only the part inside the body tag is returned. if (content) { content = content.replace(xmlRegExp, ""); var matches = content.match(bodyRegExp); if (matches) { content = matches[1]; } } else { content = ""; } return content; }, 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"); }, createXhr: function () { //Would love to dump the ActiveX crap in here. Need IE 6 to die first. var xhr, i, progId; if (typeof XMLHttpRequest !== "undefined") { return new XMLHttpRequest(); } else { for (i = 0; i < 3; i++) { progId = progIds[i]; try { xhr = new ActiveXObject(progId); } catch (e) {} if (xhr) { progIds = [progId]; // so faster next time break; } } } if (!xhr) { throw new Error("createXhr(): XMLHttpRequest not available"); } return xhr; }, get: get, /** * Parses a resource name into its component parts. Resource names * look like: module/name.ext!strip, where the !strip part is * optional. * @param {String} name the resource name * @returns {Object} with properties "moduleName", "ext" and "strip" * where strip is a boolean. */ parseName: function (name) { var strip = false, index = name.indexOf("."), modName = name.substring(0, index), ext = name.substring(index + 1, name.length); index = ext.indexOf("!"); if (index !== -1) { //Pull off the strip arg. strip = ext.substring(index + 1, ext.length); strip = strip === "strip"; ext = ext.substring(0, index); } return { moduleName: modName, ext: ext, strip: strip }; }, xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/, /** * Is an URL on another domain. Only works for browser use, returns * false in non-browser environments. Only used to know if an * optimized .js version of a text resource should be loaded * instead. * @param {String} url * @returns Boolean */ canUseXhr: function (url, protocol, hostname, port) { var match = text.xdRegExp.exec(url), uProtocol, uHostName, uPort; if (!match) { return true; } uProtocol = match[2]; uHostName = match[3]; uHostName = uHostName.split(':'); uPort = uHostName[1]; uHostName = uHostName[0]; return (!uProtocol || uProtocol === protocol) && (!uHostName || uHostName === hostname) && ((!uPort && !uHostName) || uPort === port); }, finishLoad: function (name, strip, content, onLoad, config) { content = strip ? text.strip(content) : content; if (config.isBuild && config.inlineText) { buildMap[name] = content; } onLoad(content); }, load: function (name, req, onLoad, config) { //Name has format: some.module.filext!strip //The strip part is optional. //if strip is present, then that means only get the string contents //inside a body tag in an HTML string. For XML/SVG content it means //removing the declarations so the content can be inserted //into the current doc without problems. var parsed = text.parseName(name), nonStripName = parsed.moduleName + '.' + parsed.ext, url = req.toUrl(nonStripName); //Load the text. Use XHR if possible and in a browser. if (!hasLocation || text.canUseXhr(url)) { text.get(url, function (content) { text.finishLoad(name, parsed.strip, content, onLoad, config); }); } else { //Need to fetch the resource across domains. Assume //the resource has been optimized into a JS module. Fetch //by the module name + extension, but do not include the //!strip part to avoid file system issues. req([nonStripName], function (content) { text.finishLoad(parsed.moduleName + '.' + parsed.ext, parsed.strip, content, onLoad, config); }); } }, write: function (pluginName, moduleName, write, config) { if (moduleName in buildMap) { var content = text.jsEscape(buildMap[moduleName]); write("define('" + pluginName + "!" + moduleName + "', function () { return '" + content + "';});\n"); } }, writeFile: function (pluginName, moduleName, req, write, config) { var parsed = text.parseName(moduleName), nonStripName = parsed.moduleName + '.' + parsed.ext, //Use a '.js' file name so that it indicates it is a //script that can be loaded across domains. fileName = req.toUrl(parsed.moduleName + '.' + parsed.ext) + '.js'; //Leverage own load() method to load plugin value, but only //write out values that do not have the strip argument, //to avoid any potential issues with ! in file names. text.load(nonStripName, req, function (value) { //Use own write() method to construct full module value. text.write(pluginName, nonStripName, function (contents) { write(fileName, contents); }, config); }, config); } }; return text; }); }()); define('text!subwidget.html!strip', function () { return 'I am in a widget
alameda should not mutate deps passed to it. More info: 35.
Check console for messages
================================================ FILE: tests/promiseRequire/app.js ================================================ define(['bar'], function (bar) { return { name: 'app', bar: bar }; }); ================================================ FILE: tests/promiseRequire/bar.js ================================================ // bar.js define('bar', function(require) { return { name: 'bar' }; }); ================================================ FILE: tests/promiseRequire/promiseRequire.html ================================================Test require([]) returning a promise. More info.
Check console for messages
================================================ FILE: tests/relativePaths/relativePaths.html ================================================Test relative dependency paths with alameda. More info: 28.
Check console for messages
================================================ FILE: tests/runner.js ================================================ var page = require('webpage').create(); page.onAlert = function () { if (page.evaluate(function () { return doh._doneForPhantom; })) { var problems = page.evaluate(function () { return doh._errorCount + doh._failureCount; }); phantom.exit(problems ? 1 : 0); } }; var first = true; page.onLoadFinished = function (status) { if (first) { first = false; page.evaluate(function () { var oldReport = doh._report; doh._report = function () { oldReport.apply(doh, arguments); this._doneForPhantom = true; alert(); }; doh.run(); }); } }; page.onConsoleMessage = function () { console.log.apply(console, arguments); }; page.open('http://localhost:1986/tests/doh/runner.html?testUrl=../all'); ================================================ FILE: tests/server.js ================================================ var connect = require('connect'); connect.createServer(connect.static(__dirname + '/..')).listen(1986); require('fs').writeFileSync(__dirname + '/pid.txt', process.pid); ================================================ FILE: tests/shim/shim.html ================================================Check console for messages
================================================ FILE: tests/shim/shim.js ================================================ //Taken from requirejs/tests/shim/built/basic-tests.js (function (root) { root.A = { name: 'a' }; }(this)); define("a", (function (global) { return function () { var ret = global.A.name; var fn = function () { window.globalA = this.A.name; }; fn.apply(global, arguments); return ret; }; }(this))); function D() { this.name = 'd'; }; define("d", function(){}); var B = { name: 'b', aValue: A.name, dValue: new D() }; define("b", function(){}); var C = { name: 'c', a: A, b: B }; define("c", ["a","b"], (function (global) { return function () { var ret = global.C; return ret; }; }(this))); var e = { nested: { e: { name: 'e' } } }; define("e", (function (global) { return function () { var ret = global.e.nested.e; return ret; }; }(this))); ================================================ FILE: tests/simple.html ================================================Check console for messages
================================================ FILE: tests/simple.js ================================================ define('foo', { name: 'foo' }); define('bar', [], function() { return { name: 'bar' } }); define('baz', ['require', 'exports', 'module', './bar'], function (require, exports, module) { var bar = require('./bar'); exports.name = 'baz'; exports.barName = bar.name; exports.callIt = function (callback) { require(['./bar'], function (bar) { callback(bar); }); } }); ================================================ FILE: tests/specialDeps/specialDeps-tests.js ================================================ define('foo', function(require, exports, module) { require('exports').name = 'foo'; require('require')('exports').related = require('module').config().related; require('require')('exports').uri = module.uri; }); require.config({ config: { foo: { related: 'bar' } } }); require(["foo"], function (foo) { doh.register( "specialDeps", [ function specialDeps(t) { t.is("foo", foo.name); t.is("bar", foo.related); t.is("./foo.js", foo.uri); } ] ); doh.run(); }); ================================================ FILE: tests/specialDeps/specialDeps.html ================================================Tests for require("require"|"exports"|"module") inside a module. More info.
Check console for messages
================================================ FILE: tests/timeoutErrors/timeoutErrors.html ================================================Tests that timeouts trigger errbacks if appropriate, require.onError if no errback is provided.
Check console for messages