diff --git a/packages/ember-cli-fastboot/lib/broccoli/fastboot-config.js b/packages/ember-cli-fastboot/lib/broccoli/fastboot-config.js index 44e93167f..2ddec553b 100644 --- a/packages/ember-cli-fastboot/lib/broccoli/fastboot-config.js +++ b/packages/ember-cli-fastboot/lib/broccoli/fastboot-config.js @@ -182,7 +182,9 @@ module.exports = class FastBootConfig extends Plugin { moduleWhitelist: this.moduleWhitelist, schemaVersion: LATEST_SCHEMA_VERSION, hostWhitelist: this.normalizeHostWhitelist(), - config: this.fastbootConfig, + // We can't drop manifest until broccoli-asset-rev also supports v5 HTML based manifest + // https://github.com/ember-cli/broccoli-asset-rev/blob/78f6047c15acb3bd348611f658b03bdd1041911f/lib/fastboot-manifest-rewrite.js + manifest: this.manifest, htmlEntrypoint: this.manifest.htmlFile } }, diff --git a/packages/ember-cli-fastboot/lib/broccoli/html-writer.js b/packages/ember-cli-fastboot/lib/broccoli/html-writer.js index 07bdff388..75faa0b24 100644 --- a/packages/ember-cli-fastboot/lib/broccoli/html-writer.js +++ b/packages/ember-cli-fastboot/lib/broccoli/html-writer.js @@ -12,6 +12,7 @@ module.exports = class BasePageWriter extends Filter { }); this._manifest = manifest; this._rootURL = getRootURL(fastbootConfig, appName); + this._fastbootConfig = fastbootConfig; this._appJsPath = outputPaths.app.js; this._expectedFiles = expectedFiles(outputPaths); } @@ -24,15 +25,46 @@ module.exports = class BasePageWriter extends Filter { processString(content) { let dom = new JSDOM(content); + this._handleConfig(dom); + this._handleScripts(dom); + return dom.serialize(); + } + + _handleConfig(dom) { + function findFistConfigMeta(dom) { + let metaTags = dom.window.document.querySelectorAll('meta'); + for (let element of metaTags) { + let name = element.getAttribute('name'); + if (name && name.endsWith('/config/environment')) { + return element; + } + } + } + let firstConfigMeta; + if (firstConfigMeta) { + firstConfigMeta = findFistConfigMeta(dom); + } else { + firstConfigMeta = dom.window.document.createTextNode('\n'); + dom.window.document.head.appendChild(firstConfigMeta); + } + let nodeRange = new NodeRange(firstConfigMeta); + for (let [name, options] of Object.entries(this._fastbootConfig)) { + nodeRange.insertJsonAsMetaTag(`${name}/config/fastboot-environment`, options); + } + } + + _handleScripts(dom) { let scriptTags = dom.window.document.querySelectorAll('script'); this._ignoreUnexpectedScripts(scriptTags); let fastbootScripts = this._findFastbootScriptToInsert(scriptTags); let appJsTag = findAppJsTag(scriptTags, this._appJsPath, this._rootURL); - insertFastbootScriptsBeforeAppJsTags(fastbootScripts, appJsTag); + if (!appJsTag) { + throw new Error('ember-cli-fastboot cannot find own app script tag'); + } - return dom.serialize(); + insertFastbootScriptsBeforeAppJsTags(fastbootScripts, appJsTag); } _findFastbootScriptToInsert(scriptTags) { @@ -79,6 +111,10 @@ function getRootURL(appName, config) { } function urlWithin(candidate, root) { + // this is a null or relative path + if (!candidate || !candidate.startsWith('/')) { + return candidate; + } let candidateURL = new URL(candidate, 'http://_the_current_origin_'); let rootURL = new URL(root, 'http://_the_current_origin_'); if (candidateURL.href.startsWith(rootURL.href)) { @@ -114,6 +150,18 @@ class NodeRange { let newTag = this.end.ownerDocument.createElement('fastboot-script'); newTag.setAttribute('src', src); this.insertNode(newTag); + this.insertNewLine(); + } + + insertJsonAsMetaTag(name, content) { + let newTag = this.end.ownerDocument.createElement('meta'); + newTag.setAttribute('name', name); + newTag.setAttribute('content', encodeURIComponent(JSON.stringify(content))); + this.insertNode(newTag); + this.insertNewLine(); + } + + insertNewLine() { this.insertNode(this.end.ownerDocument.createTextNode('\n')); } diff --git a/packages/fastboot/src/fastboot-schema.js b/packages/fastboot/src/fastboot-schema.js index c513f9c83..91fcede9c 100644 --- a/packages/fastboot/src/fastboot-schema.js +++ b/packages/fastboot/src/fastboot-schema.js @@ -79,8 +79,7 @@ function loadConfig(distPath) { ({ appName, config, html, scripts } = loadManifest(distPath, pkg.fastboot, schemaVersion)); } else { appName = pkg.name; - config = pkg.fastboot.config; - ({ html, scripts } = htmlEntrypoint(appName, distPath, pkg.fastboot.htmlEntrypoint, config)); + ({ config, html, scripts } = htmlEntrypoint(appName, distPath, pkg.fastboot.htmlEntrypoint)); } let sandboxRequire = buildWhitelistedRequire( diff --git a/packages/fastboot/src/html-entrypoint.js b/packages/fastboot/src/html-entrypoint.js index 12d6191e4..5f01bb032 100644 --- a/packages/fastboot/src/html-entrypoint.js +++ b/packages/fastboot/src/html-entrypoint.js @@ -4,11 +4,35 @@ const { JSDOM } = require('jsdom'); const fs = require('fs'); const path = require('path'); -function htmlEntrypoint(appName, distPath, htmlPath, config = {}) { +function htmlEntrypoint(appName, distPath, htmlPath) { let html = fs.readFileSync(path.join(distPath, htmlPath), 'utf8'); let dom = new JSDOM(html); - let scripts = []; + function mergeContent(metaElement, config, configName) { + let name = metaElement.getAttribute('name'); + if (name && name.endsWith(configName)) { + let content = JSON.parse(decodeURIComponent(metaElement.getAttribute('content'))); + content.APP = Object.assign({ autoboot: false }, content.APP); + config[name.slice(0, -1 * configName.length)] = content; + return true; + } + return false; + } + let fastbootConfig = {}; + let config = {}; + for (let element of dom.window.document.querySelectorAll('meta')) { + mergeContent(element, config, '/config/environment'); + let fastbootMerged = mergeContent(element, fastbootConfig, '/config/fastboot-environment'); + if (fastbootMerged) { + element.remove(); + } + } + let isFastbootConfigBuilt = Object.keys(fastbootConfig).length > 0; + if (isFastbootConfigBuilt) { + config = fastbootConfig; + } + + let scripts = []; let rootURL = getRootURL(appName, config); for (let element of dom.window.document.querySelectorAll('script,fastboot-script')) { @@ -24,7 +48,7 @@ function htmlEntrypoint(appName, distPath, htmlPath, config = {}) { } } - return { html: dom.serialize(), scripts }; + return { config, html: dom.serialize(), scripts }; } function extractSrc(element) { diff --git a/packages/fastboot/test/fastboot-test.js b/packages/fastboot/test/fastboot-test.js index 9e79a9c11..140f407da 100644 --- a/packages/fastboot/test/fastboot-test.js +++ b/packages/fastboot/test/fastboot-test.js @@ -455,18 +455,4 @@ describe('FastBoot', function() { usedPrebuiltSandbox: true, }); }); - - it('htmlEntrypoint works', function() { - var fastboot = new FastBoot({ - distPath: fixture('html-entrypoint'), - }); - - return fastboot - .visit('/') - .then(r => r.html()) - .then(html => { - expect(html).to.match(/Welcome to Ember/); - expect(html).to.not.match(/fastboot-script/); - }); - }); }); diff --git a/packages/fastboot/test/fixtures/html-entrypoint/assets/fastboot-test.js b/packages/fastboot/test/fixtures/html-entrypoint/assets/fastboot-test.js deleted file mode 100644 index 386277636..000000000 --- a/packages/fastboot/test/fixtures/html-entrypoint/assets/fastboot-test.js +++ /dev/null @@ -1,350 +0,0 @@ -"use strict"; - -/* jshint ignore:start */ - - - -/* jshint ignore:end */ - -define('fastboot-test/app', ['exports', 'ember', 'fastboot-test/resolver', 'ember-load-initializers', 'fastboot-test/config/environment'], function (exports, _ember, _fastbootTestResolver, _emberLoadInitializers, _fastbootTestConfigEnvironment) { - - var App = undefined; - - _ember['default'].MODEL_FACTORY_INJECTIONS = true; - - App = _ember['default'].Application.extend({ - modulePrefix: _fastbootTestConfigEnvironment['default'].modulePrefix, - podModulePrefix: _fastbootTestConfigEnvironment['default'].podModulePrefix, - Resolver: _fastbootTestResolver['default'] - }); - - (0, _emberLoadInitializers['default'])(App, _fastbootTestConfigEnvironment['default'].modulePrefix); - - exports['default'] = App; -}); -define('fastboot-test/components/app-version', ['exports', 'ember-cli-app-version/components/app-version', 'fastboot-test/config/environment'], function (exports, _emberCliAppVersionComponentsAppVersion, _fastbootTestConfigEnvironment) { - - var name = _fastbootTestConfigEnvironment['default'].APP.name; - var version = _fastbootTestConfigEnvironment['default'].APP.version; - - exports['default'] = _emberCliAppVersionComponentsAppVersion['default'].extend({ - version: version, - name: name - }); -}); -define('fastboot-test/controllers/array', ['exports', 'ember'], function (exports, _ember) { - exports['default'] = _ember['default'].Controller; -}); -define('fastboot-test/controllers/object', ['exports', 'ember'], function (exports, _ember) { - exports['default'] = _ember['default'].Controller; -}); -define('fastboot-test/helpers/pluralize', ['exports', 'ember-inflector/lib/helpers/pluralize'], function (exports, _emberInflectorLibHelpersPluralize) { - exports['default'] = _emberInflectorLibHelpersPluralize['default']; -}); -define('fastboot-test/helpers/singularize', ['exports', 'ember-inflector/lib/helpers/singularize'], function (exports, _emberInflectorLibHelpersSingularize) { - exports['default'] = _emberInflectorLibHelpersSingularize['default']; -}); -define('fastboot-test/initializers/app-version', ['exports', 'ember-cli-app-version/initializer-factory', 'fastboot-test/config/environment'], function (exports, _emberCliAppVersionInitializerFactory, _fastbootTestConfigEnvironment) { - exports['default'] = { - name: 'App Version', - initialize: (0, _emberCliAppVersionInitializerFactory['default'])(_fastbootTestConfigEnvironment['default'].APP.name, _fastbootTestConfigEnvironment['default'].APP.version) - }; -}); -define('fastboot-test/initializers/container-debug-adapter', ['exports', 'ember-resolver/container-debug-adapter'], function (exports, _emberResolverContainerDebugAdapter) { - exports['default'] = { - name: 'container-debug-adapter', - - initialize: function initialize() { - var app = arguments[1] || arguments[0]; - - app.register('container-debug-adapter:main', _emberResolverContainerDebugAdapter['default']); - app.inject('container-debug-adapter:main', 'namespace', 'application:main'); - } - }; -}); -define('fastboot-test/initializers/data-adapter', ['exports', 'ember'], function (exports, _ember) { - - /* - This initializer is here to keep backwards compatibility with code depending - on the `data-adapter` initializer (before Ember Data was an addon). - - Should be removed for Ember Data 3.x - */ - - exports['default'] = { - name: 'data-adapter', - before: 'store', - initialize: _ember['default'].K - }; -}); -define('fastboot-test/initializers/ember-data', ['exports', 'ember-data/setup-container', 'ember-data/-private/core'], function (exports, _emberDataSetupContainer, _emberDataPrivateCore) { - - /* - - This code initializes Ember-Data onto an Ember application. - - If an Ember.js developer defines a subclass of DS.Store on their application, - as `App.StoreService` (or via a module system that resolves to `service:store`) - this code will automatically instantiate it and make it available on the - router. - - Additionally, after an application's controllers have been injected, they will - each have the store made available to them. - - For example, imagine an Ember.js application with the following classes: - - App.StoreService = DS.Store.extend({ - adapter: 'custom' - }); - - App.PostsController = Ember.ArrayController.extend({ - // ... - }); - - When the application is initialized, `App.ApplicationStore` will automatically be - instantiated, and the instance of `App.PostsController` will have its `store` - property set to that instance. - - Note that this code will only be run if the `ember-application` package is - loaded. If Ember Data is being used in an environment other than a - typical application (e.g., node.js where only `ember-runtime` is available), - this code will be ignored. - */ - - exports['default'] = { - name: 'ember-data', - initialize: _emberDataSetupContainer['default'] - }; -}); -define('fastboot-test/initializers/export-application-global', ['exports', 'ember', 'fastboot-test/config/environment'], function (exports, _ember, _fastbootTestConfigEnvironment) { - exports.initialize = initialize; - - function initialize() { - var application = arguments[1] || arguments[0]; - if (_fastbootTestConfigEnvironment['default'].exportApplicationGlobal !== false) { - var value = _fastbootTestConfigEnvironment['default'].exportApplicationGlobal; - var globalName; - - if (typeof value === 'string') { - globalName = value; - } else { - globalName = _ember['default'].String.classify(_fastbootTestConfigEnvironment['default'].modulePrefix); - } - - if (!window[globalName]) { - window[globalName] = application; - - application.reopen({ - willDestroy: function willDestroy() { - this._super.apply(this, arguments); - delete window[globalName]; - } - }); - } - } - } - - exports['default'] = { - name: 'export-application-global', - - initialize: initialize - }; -}); -define('fastboot-test/initializers/fastboot/ajax', ['exports'], function (exports) { - /* globals najax */ - - var nodeAjax = function nodeAjax(options) { - najax(options); - }; - - exports['default'] = { - name: 'ajax-service', - - initialize: function initialize(application) { - application.register('ajax:node', nodeAjax, { instantiate: false }); - application.inject('adapter', '_ajaxRequest', 'ajax:node'); - } - }; -}); -define("fastboot-test/initializers/fastboot/dom-helper-patches", ["exports"], function (exports) { - /*globals Ember, URL*/ - exports["default"] = { - name: "dom-helper-patches", - - initialize: function initialize(App) { - // TODO: remove me - Ember.HTMLBars.DOMHelper.prototype.protocolForURL = function (url) { - var protocol = URL.parse(url).protocol; - return protocol == null ? ':' : protocol; - }; - - // TODO: remove me https://github.com/tildeio/htmlbars/pull/425 - Ember.HTMLBars.DOMHelper.prototype.parseHTML = function (html) { - return this.document.createRawHTMLSection(html); - }; - } - }; -}); -define('fastboot-test/initializers/injectStore', ['exports', 'ember'], function (exports, _ember) { - - /* - This initializer is here to keep backwards compatibility with code depending - on the `injectStore` initializer (before Ember Data was an addon). - - Should be removed for Ember Data 3.x - */ - - exports['default'] = { - name: 'injectStore', - before: 'store', - initialize: _ember['default'].K - }; -}); -define('fastboot-test/initializers/store', ['exports', 'ember'], function (exports, _ember) { - - /* - This initializer is here to keep backwards compatibility with code depending - on the `store` initializer (before Ember Data was an addon). - - Should be removed for Ember Data 3.x - */ - - exports['default'] = { - name: 'store', - after: 'ember-data', - initialize: _ember['default'].K - }; -}); -define('fastboot-test/initializers/transforms', ['exports', 'ember'], function (exports, _ember) { - - /* - This initializer is here to keep backwards compatibility with code depending - on the `transforms` initializer (before Ember Data was an addon). - - Should be removed for Ember Data 3.x - */ - - exports['default'] = { - name: 'transforms', - before: 'store', - initialize: _ember['default'].K - }; -}); -define("fastboot-test/instance-initializers/ember-data", ["exports", "ember-data/-private/instance-initializers/initialize-store-service"], function (exports, _emberDataPrivateInstanceInitializersInitializeStoreService) { - exports["default"] = { - name: "ember-data", - initialize: _emberDataPrivateInstanceInitializersInitializeStoreService["default"] - }; -}); -define('fastboot-test/resolver', ['exports', 'ember-resolver'], function (exports, _emberResolver) { - exports['default'] = _emberResolver['default']; -}); -define('fastboot-test/router', ['exports', 'ember', 'fastboot-test/config/environment'], function (exports, _ember, _fastbootTestConfigEnvironment) { - - var Router = _ember['default'].Router.extend({ - location: _fastbootTestConfigEnvironment['default'].locationType - }); - - Router.map(function () {}); - - exports['default'] = Router; -}); -define('fastboot-test/services/ajax', ['exports', 'ember-ajax/services/ajax'], function (exports, _emberAjaxServicesAjax) { - Object.defineProperty(exports, 'default', { - enumerable: true, - get: function get() { - return _emberAjaxServicesAjax['default']; - } - }); -}); -define("fastboot-test/services/fastboot", ["exports", "ember"], function (exports, _ember) { - - var alias = _ember["default"].computed.alias; - - exports["default"] = _ember["default"].Service.extend({ - cookies: alias('_fastbootInfo.cookies') - }); -}); -define("fastboot-test/templates/application", ["exports"], function (exports) { - exports["default"] = Ember.HTMLBars.template((function () { - return { - meta: { - "fragmentReason": { - "name": "missing-wrapper", - "problems": ["multiple-nodes", "wrong-type"] - }, - "revision": "Ember@2.4.1", - "loc": { - "source": null, - "start": { - "line": 1, - "column": 0 - }, - "end": { - "line": 4, - "column": 0 - } - }, - "moduleName": "fastboot-test/templates/application.hbs" - }, - isEmpty: false, - arity: 0, - cachedFragment: null, - hasRendered: false, - buildFragment: function buildFragment(dom) { - var el0 = dom.createDocumentFragment(); - var el1 = dom.createElement("h2"); - dom.setAttribute(el1, "id", "title"); - var el2 = dom.createTextNode("Welcome to Ember"); - dom.appendChild(el1, el2); - dom.appendChild(el0, el1); - var el1 = dom.createTextNode("\n\n"); - dom.appendChild(el0, el1); - var el1 = dom.createComment(""); - dom.appendChild(el0, el1); - var el1 = dom.createTextNode("\n"); - dom.appendChild(el0, el1); - return el0; - }, - buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { - var morphs = new Array(1); - morphs[0] = dom.createMorphAt(fragment, 2, 2, contextualElement); - return morphs; - }, - statements: [["content", "outlet", ["loc", [null, [3, 0], [3, 10]]]]], - locals: [], - templates: [] - }; - })()); -}); -/* jshint ignore:start */ - - - -/* jshint ignore:end */ - -/* jshint ignore:start */ - -define('fastboot-test/config/environment', ['ember'], function(Ember) { - return FastBoot.config(); -}); - -/* jshint ignore:end */ - -/* jshint ignore:start */ - - -define('~fastboot/app-factory', ['fastboot-test/app', 'fastboot-test/config/environment'], function(App, config) { - App = App['default']; - config = config['default']; - - return { - 'default': function() { - return App.create(config.APP); - } - }; -}); - - -/* jshint ignore:end */ -//# sourceMappingURL=fastboot-test.map diff --git a/packages/fastboot/test/fixtures/html-entrypoint/assets/vendor.js b/packages/fastboot/test/fixtures/html-entrypoint/assets/vendor.js deleted file mode 100644 index 6256cde98..000000000 --- a/packages/fastboot/test/fixtures/html-entrypoint/assets/vendor.js +++ /dev/null @@ -1,83722 +0,0 @@ -/* jshint ignore:start */ - -window.EmberENV = {"FEATURES":{}}; -var runningTests = false; - - - -/* jshint ignore:end */ - -;var loader, define, requireModule, require, requirejs; - -(function(global) { - 'use strict'; - - // Save off the original values of these globals, so we can restore them if someone asks us to - var oldGlobals = { - loader: loader, - define: define, - requireModule: requireModule, - require: require, - requirejs: requirejs - }; - - loader = { - noConflict: function(aliases) { - var oldName, newName; - - for (oldName in aliases) { - if (aliases.hasOwnProperty(oldName)) { - if (oldGlobals.hasOwnProperty(oldName)) { - newName = aliases[oldName]; - - global[newName] = global[oldName]; - global[oldName] = oldGlobals[oldName]; - } - } - } - } - }; - - var _isArray; - if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - _isArray = Array.isArray; - } - - var registry = {}; - var seen = {}; - var FAILED = false; - var LOADED = true; - - var uuid = 0; - - function unsupportedModule(length) { - throw new Error('an unsupported module was defined, expected `define(name, deps, module)` instead got: `' + - length + '` arguments to define`'); - } - - var defaultDeps = ['require', 'exports', 'module']; - - function Module(name, deps, callback) { - this.id = uuid++; - this.name = name; - this.deps = !deps.length && callback.length ? defaultDeps : deps; - this.module = { exports: {} }; - this.callback = callback; - this.state = undefined; - this._require = undefined; - this.finalized = false; - this.hasExportsAsDep = false; - } - - Module.prototype.makeDefaultExport = function() { - var exports = this.module.exports; - if (exports !== null && - (typeof exports === 'object' || typeof exports === 'function') && - exports['default'] === undefined) { - exports['default'] = exports; - } - }; - - Module.prototype.exports = function(reifiedDeps) { - if (this.finalized) { - return this.module.exports; - } else { - if (loader.wrapModules) { - this.callback = loader.wrapModules(this.name, this.callback); - } - var result = this.callback.apply(this, reifiedDeps); - if (!(this.hasExportsAsDep && result === undefined)) { - this.module.exports = result; - } - this.makeDefaultExport(); - this.finalized = true; - return this.module.exports; - } - }; - - Module.prototype.unsee = function() { - this.finalized = false; - this.state = undefined; - this.module = { exports: {}}; - }; - - Module.prototype.reify = function() { - var deps = this.deps; - var length = deps.length; - var reified = new Array(length); - var dep; - - for (var i = 0, l = length; i < l; i++) { - dep = deps[i]; - if (dep === 'exports') { - this.hasExportsAsDep = true; - reified[i] = this.module.exports; - } else if (dep === 'require') { - reified[i] = this.makeRequire(); - } else if (dep === 'module') { - reified[i] = this.module; - } else { - reified[i] = findModule(resolve(dep, this.name), this.name).module.exports; - } - } - - return reified; - }; - - Module.prototype.makeRequire = function() { - var name = this.name; - - return this._require || (this._require = function(dep) { - return require(resolve(dep, name)); - }); - }; - - Module.prototype.build = function() { - if (this.state === FAILED) { return; } - this.state = FAILED; - this.exports(this.reify()); - this.state = LOADED; - }; - - define = function(name, deps, callback) { - if (arguments.length < 2) { - unsupportedModule(arguments.length); - } - - if (!_isArray(deps)) { - callback = deps; - deps = []; - } - - registry[name] = new Module(name, deps, callback); - }; - - // we don't support all of AMD - // define.amd = {}; - // we will support petals... - define.petal = { }; - - function Alias(path) { - this.name = path; - } - - define.alias = function(path) { - return new Alias(path); - }; - - function missingModule(name, referrer) { - throw new Error('Could not find module `' + name + '` imported from `' + referrer + '`'); - } - - requirejs = require = requireModule = function(name) { - return findModule(name, '(require)').module.exports; - }; - - function findModule(name, referrer) { - var mod = registry[name] || registry[name + '/index']; - - while (mod && mod.callback instanceof Alias) { - name = mod.callback.name; - mod = registry[name]; - } - - if (!mod) { missingModule(name, referrer); } - - mod.build(); - return mod; - } - - function resolve(child, name) { - if (child.charAt(0) !== '.') { return child; } - - var parts = child.split('/'); - var nameParts = name.split('/'); - var parentBase = nameParts.slice(0, -1); - - for (var i = 0, l = parts.length; i < l; i++) { - var part = parts[i]; - - if (part === '..') { - if (parentBase.length === 0) { - throw new Error('Cannot access parent module of root'); - } - parentBase.pop(); - } else if (part === '.') { - continue; - } else { parentBase.push(part); } - } - - return parentBase.join('/'); - } - - requirejs.entries = requirejs._eak_seen = registry; - requirejs.unsee = function(moduleName) { - findModule(moduleName, '(unsee)').unsee(); - }; - - requirejs.clear = function() { - requirejs.entries = requirejs._eak_seen = registry = {}; - seen = {}; - }; -})(this); - -;/*! - * jQuery JavaScript Library v2.2.1 - * http://jquery.com/ - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * - * Copyright jQuery Foundation and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2016-02-22T19:11Z - */ - -(function( global, factory ) { - - if ( typeof module === "object" && typeof module.exports === "object" ) { - // For CommonJS and CommonJS-like environments where a proper `window` - // is present, execute the factory and get jQuery. - // For environments that do not have a `window` with a `document` - // (such as Node.js), expose a factory as module.exports. - // This accentuates the need for the creation of a real `window`. - // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info. - module.exports = global.document ? - factory( global, true ) : - function( w ) { - if ( !w.document ) { - throw new Error( "jQuery requires a window with a document" ); - } - return factory( w ); - }; - } else { - factory( global ); - } - -// Pass this if window is not defined yet -}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { - -// Support: Firefox 18+ -// Can't be in strict mode, several libs including ASP.NET trace -// the stack via arguments.caller.callee and Firefox dies if -// you try to trace through "use strict" call chains. (#13335) -//"use strict"; -var arr = []; - -var document = window.document; - -var slice = arr.slice; - -var concat = arr.concat; - -var push = arr.push; - -var indexOf = arr.indexOf; - -var class2type = {}; - -var toString = class2type.toString; - -var hasOwn = class2type.hasOwnProperty; - -var support = {}; - - - -var - version = "2.2.1", - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - - // The jQuery object is actually just the init constructor 'enhanced' - // Need init if jQuery is called (just allow error to be thrown if not included) - return new jQuery.fn.init( selector, context ); - }, - - // Support: Android<4.1 - // Make sure we trim BOM and NBSP - rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, - - // Matches dashed string for camelizing - rmsPrefix = /^-ms-/, - rdashAlpha = /-([\da-z])/gi, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return letter.toUpperCase(); - }; - -jQuery.fn = jQuery.prototype = { - - // The current version of jQuery being used - jquery: version, - - constructor: jQuery, - - // Start with an empty selector - selector: "", - - // The default length of a jQuery object is 0 - length: 0, - - toArray: function() { - return slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num != null ? - - // Return just the one element from the set - ( num < 0 ? this[ num + this.length ] : this[ num ] ) : - - // Return all the elements in a clean array - slice.call( this ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - ret.context = this.context; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - each: function( callback ) { - return jQuery.each( this, callback ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map( this, function( elem, i ) { - return callback.call( elem, i, elem ); - } ) ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); - }, - - end: function() { - return this.prevObject || this.constructor(); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: arr.sort, - splice: arr.splice -}; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[ 0 ] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - - // Skip the boolean and the target - target = arguments[ i ] || {}; - i++; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { - target = {}; - } - - // Extend jQuery itself if only one argument is passed - if ( i === length ) { - target = this; - i--; - } - - for ( ; i < length; i++ ) { - - // Only deal with non-null/undefined values - if ( ( options = arguments[ i ] ) != null ) { - - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject( copy ) || - ( copyIsArray = jQuery.isArray( copy ) ) ) ) { - - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray( src ) ? src : []; - - } else { - clone = src && jQuery.isPlainObject( src ) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend( { - - // Unique for each copy of jQuery on the page - expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), - - // Assume jQuery is ready without the ready module - isReady: true, - - error: function( msg ) { - throw new Error( msg ); - }, - - noop: function() {}, - - isFunction: function( obj ) { - return jQuery.type( obj ) === "function"; - }, - - isArray: Array.isArray, - - isWindow: function( obj ) { - return obj != null && obj === obj.window; - }, - - isNumeric: function( obj ) { - - // parseFloat NaNs numeric-cast false positives (null|true|false|"") - // ...but misinterprets leading-number strings, particularly hex literals ("0x...") - // subtraction forces infinities to NaN - // adding 1 corrects loss of precision from parseFloat (#15100) - var realStringObj = obj && obj.toString(); - return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0; - }, - - isPlainObject: function( obj ) { - - // Not plain objects: - // - Any object or value whose internal [[Class]] property is not "[object Object]" - // - DOM nodes - // - window - if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - if ( obj.constructor && - !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { - return false; - } - - // If the function hasn't returned already, we're confident that - // |obj| is a plain object, created by {} or constructed with new Object - return true; - }, - - isEmptyObject: function( obj ) { - var name; - for ( name in obj ) { - return false; - } - return true; - }, - - type: function( obj ) { - if ( obj == null ) { - return obj + ""; - } - - // Support: Android<4.0, iOS<6 (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call( obj ) ] || "object" : - typeof obj; - }, - - // Evaluates a script in a global context - globalEval: function( code ) { - var script, - indirect = eval; - - code = jQuery.trim( code ); - - if ( code ) { - - // If the code includes a valid, prologue position - // strict mode pragma, execute code by injecting a - // script tag into the document. - if ( code.indexOf( "use strict" ) === 1 ) { - script = document.createElement( "script" ); - script.text = code; - document.head.appendChild( script ).parentNode.removeChild( script ); - } else { - - // Otherwise, avoid the DOM node creation, insertion - // and removal by using an indirect global eval - - indirect( code ); - } - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Support: IE9-11+ - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - }, - - each: function( obj, callback ) { - var length, i = 0; - - if ( isArrayLike( obj ) ) { - length = obj.length; - for ( ; i < length; i++ ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } else { - for ( i in obj ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } - - return obj; - }, - - // Support: Android<4.1 - trim: function( text ) { - return text == null ? - "" : - ( text + "" ).replace( rtrim, "" ); - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArrayLike( Object( arr ) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - return arr == null ? -1 : indexOf.call( arr, elem, i ); - }, - - merge: function( first, second ) { - var len = +second.length, - j = 0, - i = first.length; - - for ( ; j < len; j++ ) { - first[ i++ ] = second[ j ]; - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, invert ) { - var callbackInverse, - matches = [], - i = 0, - length = elems.length, - callbackExpect = !invert; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - callbackInverse = !callback( elems[ i ], i ); - if ( callbackInverse !== callbackExpect ) { - matches.push( elems[ i ] ); - } - } - - return matches; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var length, value, - i = 0, - ret = []; - - // Go through the array, translating each of the items to their new values - if ( isArrayLike( elems ) ) { - length = elems.length; - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - } - - // Flatten any nested arrays - return concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - var tmp, args, proxy; - - if ( typeof context === "string" ) { - tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - args = slice.call( arguments, 2 ); - proxy = function() { - return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || jQuery.guid++; - - return proxy; - }, - - now: Date.now, - - // jQuery.support is not used in Core but other projects attach their - // properties to it so it needs to exist. - support: support -} ); - -// JSHint would error on this code due to the Symbol not being defined in ES5. -// Defining this global in .jshintrc would create a danger of using the global -// unguarded in another place, it seems safer to just disable JSHint for these -// three lines. -/* jshint ignore: start */ -if ( typeof Symbol === "function" ) { - jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; -} -/* jshint ignore: end */ - -// Populate the class2type map -jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), -function( i, name ) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -} ); - -function isArrayLike( obj ) { - - // Support: iOS 8.2 (not reproducible in simulator) - // `in` check used to prevent JIT error (gh-2145) - // hasOwn isn't used here due to false negatives - // regarding Nodelist length in IE - var length = !!obj && "length" in obj && obj.length, - type = jQuery.type( obj ); - - if ( type === "function" || jQuery.isWindow( obj ) ) { - return false; - } - - return type === "array" || length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj; -} -var Sizzle = -/*! - * Sizzle CSS Selector Engine v2.2.1 - * http://sizzlejs.com/ - * - * Copyright jQuery Foundation and other contributors - * Released under the MIT license - * http://jquery.org/license - * - * Date: 2015-10-17 - */ -(function( window ) { - -var i, - support, - Expr, - getText, - isXML, - tokenize, - compile, - select, - outermostContext, - sortInput, - hasDuplicate, - - // Local document vars - setDocument, - document, - docElem, - documentIsHTML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - - // Instance-specific data - expando = "sizzle" + 1 * new Date(), - preferredDoc = window.document, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - } - return 0; - }, - - // General-purpose constants - MAX_NEGATIVE = 1 << 31, - - // Instance methods - hasOwn = ({}).hasOwnProperty, - arr = [], - pop = arr.pop, - push_native = arr.push, - push = arr.push, - slice = arr.slice, - // Use a stripped-down indexOf as it's faster than native - // http://jsperf.com/thor-indexof-vs-for/5 - indexOf = function( list, elem ) { - var i = 0, - len = list.length; - for ( ; i < len; i++ ) { - if ( list[i] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", - - // Regular expressions - - // http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - - // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", - - // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + - // Operator (capture 2) - "*([*^$|!~]?=)" + whitespace + - // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" - "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + - "*\\]", - - pseudos = ":(" + identifier + ")(?:\\((" + - // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: - // 1. quoted (capture 3; capture 4 or capture 5) - "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + - // 2. simple (capture 6) - "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + - // 3. anything else (capture 2) - ".*" + - ")\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rwhitespace = new RegExp( whitespace + "+", "g" ), - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), - - rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), - - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + identifier + ")" ), - "CLASS": new RegExp( "^\\.(" + identifier + ")" ), - "TAG": new RegExp( "^(" + identifier + "|[*])" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + - "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + - "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + - whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rnative = /^[^{]+\{\s*\[native \w/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rsibling = /[+~]/, - rescape = /'|\\/g, - - // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), - funescape = function( _, escaped, escapedWhitespace ) { - var high = "0x" + escaped - 0x10000; - // NaN means non-codepoint - // Support: Firefox<24 - // Workaround erroneous numeric interpretation of +"0x" - return high !== high || escapedWhitespace ? - escaped : - high < 0 ? - // BMP codepoint - String.fromCharCode( high + 0x10000 ) : - // Supplemental Plane codepoint (surrogate pair) - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }, - - // Used for iframes - // See setDocument() - // Removing the function wrapper causes a "Permission Denied" - // error in IE - unloadHandler = function() { - setDocument(); - }; - -// Optimize for push.apply( _, NodeList ) -try { - push.apply( - (arr = slice.call( preferredDoc.childNodes )), - preferredDoc.childNodes - ); - // Support: Android<4.0 - // Detect silently failing push.apply - arr[ preferredDoc.childNodes.length ].nodeType; -} catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { - push_native.apply( target, slice.call(els) ); - } : - - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - // Can't trust NodeList.length - while ( (target[j++] = els[i++]) ) {} - target.length = j - 1; - } - }; -} - -function Sizzle( selector, context, results, seed ) { - var m, i, elem, nid, nidselect, match, groups, newSelector, - newContext = context && context.ownerDocument, - - // nodeType defaults to 9, since context defaults to document - nodeType = context ? context.nodeType : 9; - - results = results || []; - - // Return early from calls with invalid selector or context - if ( typeof selector !== "string" || !selector || - nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { - - return results; - } - - // Try to shortcut find operations (as opposed to filters) in HTML documents - if ( !seed ) { - - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } - context = context || document; - - if ( documentIsHTML ) { - - // If the selector is sufficiently simple, try using a "get*By*" DOM method - // (excepting DocumentFragment context, where the methods don't exist) - if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { - - // ID selector - if ( (m = match[1]) ) { - - // Document context - if ( nodeType === 9 ) { - if ( (elem = context.getElementById( m )) ) { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - - // Element context - } else { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( newContext && (elem = newContext.getElementById( m )) && - contains( context, elem ) && - elem.id === m ) { - - results.push( elem ); - return results; - } - } - - // Type selector - } else if ( match[2] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; - - // Class selector - } else if ( (m = match[3]) && support.getElementsByClassName && - context.getElementsByClassName ) { - - push.apply( results, context.getElementsByClassName( m ) ); - return results; - } - } - - // Take advantage of querySelectorAll - if ( support.qsa && - !compilerCache[ selector + " " ] && - (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - - if ( nodeType !== 1 ) { - newContext = context; - newSelector = selector; - - // qSA looks outside Element context, which is not what we want - // Thanks to Andrew Dupont for this workaround technique - // Support: IE <=8 - // Exclude object elements - } else if ( context.nodeName.toLowerCase() !== "object" ) { - - // Capture the context ID, setting it first if necessary - if ( (nid = context.getAttribute( "id" )) ) { - nid = nid.replace( rescape, "\\$&" ); - } else { - context.setAttribute( "id", (nid = expando) ); - } - - // Prefix every selector in the list - groups = tokenize( selector ); - i = groups.length; - nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']"; - while ( i-- ) { - groups[i] = nidselect + " " + toSelector( groups[i] ); - } - newSelector = groups.join( "," ); - - // Expand context for sibling selectors - newContext = rsibling.test( selector ) && testContext( context.parentNode ) || - context; - } - - if ( newSelector ) { - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch ( qsaError ) { - } finally { - if ( nid === expando ) { - context.removeAttribute( "id" ); - } - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); -} - -/** - * Create key-value caches of limited size - * @returns {function(string, object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ -function createCache() { - var keys = []; - - function cache( key, value ) { - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key + " " ) > Expr.cacheLength ) { - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return (cache[ key + " " ] = value); - } - return cache; -} - -/** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ -function markFunction( fn ) { - fn[ expando ] = true; - return fn; -} - -/** - * Support testing using an element - * @param {Function} fn Passed the created div and expects a boolean result - */ -function assert( fn ) { - var div = document.createElement("div"); - - try { - return !!fn( div ); - } catch (e) { - return false; - } finally { - // Remove from its parent by default - if ( div.parentNode ) { - div.parentNode.removeChild( div ); - } - // release memory in IE - div = null; - } -} - -/** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied - */ -function addHandle( attrs, handler ) { - var arr = attrs.split("|"), - i = arr.length; - - while ( i-- ) { - Expr.attrHandle[ arr[i] ] = handler; - } -} - -/** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b - */ -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - ( ~b.sourceIndex || MAX_NEGATIVE ) - - ( ~a.sourceIndex || MAX_NEGATIVE ); - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( (cur = cur.nextSibling) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; -} - -/** - * Returns a function to use in pseudos for input types - * @param {String} type - */ -function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for buttons - * @param {String} type - */ -function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for positionals - * @param {Function} fn - */ -function createPositionalPseudo( fn ) { - return markFunction(function( argument ) { - argument = +argument; - return markFunction(function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ (j = matchIndexes[i]) ] ) { - seed[j] = !(matches[j] = seed[j]); - } - } - }); - }); -} - -/** - * Checks a node for validity as a Sizzle context - * @param {Element|Object=} context - * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value - */ -function testContext( context ) { - return context && typeof context.getElementsByTagName !== "undefined" && context; -} - -// Expose support vars for convenience -support = Sizzle.support = {}; - -/** - * Detects XML nodes - * @param {Element|Object} elem An element or a document - * @returns {Boolean} True iff elem is a non-HTML XML node - */ -isXML = Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = elem && (elem.ownerDocument || elem).documentElement; - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -/** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ -setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, parent, - doc = node ? node.ownerDocument || node : preferredDoc; - - // Return early if doc is invalid or already selected - if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Update global variables - document = doc; - docElem = document.documentElement; - documentIsHTML = !isXML( document ); - - // Support: IE 9-11, Edge - // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) - if ( (parent = document.defaultView) && parent.top !== parent ) { - // Support: IE 11 - if ( parent.addEventListener ) { - parent.addEventListener( "unload", unloadHandler, false ); - - // Support: IE 9 - 10 only - } else if ( parent.attachEvent ) { - parent.attachEvent( "onunload", unloadHandler ); - } - } - - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties - // (excepting IE8 booleans) - support.attributes = assert(function( div ) { - div.className = "i"; - return !div.getAttribute("className"); - }); - - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert(function( div ) { - div.appendChild( document.createComment("") ); - return !div.getElementsByTagName("*").length; - }); - - // Support: IE<9 - support.getElementsByClassName = rnative.test( document.getElementsByClassName ); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert(function( div ) { - docElem.appendChild( div ).id = expando; - return !document.getElementsByName || !document.getElementsByName( expando ).length; - }); - - // ID find and filter - if ( support.getById ) { - Expr.find["ID"] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var m = context.getElementById( id ); - return m ? [ m ] : []; - } - }; - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute("id") === attrId; - }; - }; - } else { - // Support: IE6/7 - // getElementById is not reliable as a find shortcut - delete Expr.find["ID"]; - - Expr.filter["ID"] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== "undefined" && - elem.getAttributeNode("id"); - return node && node.value === attrId; - }; - }; - } - - // Tag - Expr.find["TAG"] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( tag ); - - // DocumentFragment nodes don't have gEBTN - } else if ( support.qsa ) { - return context.querySelectorAll( tag ); - } - } : - - function( tag, context ) { - var elem, - tmp = [], - i = 0, - // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( (elem = results[i++]) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Class - Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { - return context.getElementsByClassName( className ); - } - }; - - /* QSA/matchesSelector - ---------------------------------------------------------------------- */ - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See http://bugs.jquery.com/ticket/13378 - rbuggyQSA = []; - - if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert(function( div ) { - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // http://bugs.jquery.com/ticket/12359 - docElem.appendChild( div ).innerHTML = "" + - "" + - ""; - - // Support: IE8, Opera 11-12.16 - // Nothing should be selected when empty strings follow ^= or $= or *= - // The test attribute must be unknown in Opera but "safe" for WinRT - // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section - if ( div.querySelectorAll("[msallowcapture^='']").length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); - } - - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !div.querySelectorAll("[selected]").length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); - } - - // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ - if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { - rbuggyQSA.push("~="); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":checked").length ) { - rbuggyQSA.push(":checked"); - } - - // Support: Safari 8+, iOS 8+ - // https://bugs.webkit.org/show_bug.cgi?id=136851 - // In-page `selector#id sibing-combinator selector` fails - if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { - rbuggyQSA.push(".#.+[+~]"); - } - }); - - assert(function( div ) { - // Support: Windows 8 Native Apps - // The type and name attributes are restricted during .innerHTML assignment - var input = document.createElement("input"); - input.setAttribute( "type", "hidden" ); - div.appendChild( input ).setAttribute( "name", "D" ); - - // Support: IE8 - // Enforce case-sensitivity of name attribute - if ( div.querySelectorAll("[name=d]").length ) { - rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( !div.querySelectorAll(":enabled").length ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Opera 10-11 does not throw on post-comma invalid pseudos - div.querySelectorAll("*,:x"); - rbuggyQSA.push(",.*:"); - }); - } - - if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || - docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector) )) ) { - - assert(function( div ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( div, "div" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( div, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - }); - } - - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); - - /* Contains - ---------------------------------------------------------------------- */ - hasCompare = rnative.test( docElem.compareDocumentPosition ); - - // Element contains another - // Purposefully self-exclusive - // As in, an element does not contain itself - contains = hasCompare || rnative.test( docElem.contains ) ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - /* Sorting - ---------------------------------------------------------------------- */ - - // Document order sorting - sortOrder = hasCompare ? - function( a, b ) { - - // Flag for duplicate removal - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - // Sort on method existence if only one input has compareDocumentPosition - var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; - if ( compare ) { - return compare; - } - - // Calculate position if both inputs belong to the same document - compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? - a.compareDocumentPosition( b ) : - - // Otherwise we know they are disconnected - 1; - - // Disconnected nodes - if ( compare & 1 || - (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { - - // Choose the first element that is related to our preferred document - if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { - return -1; - } - if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { - return 1; - } - - // Maintain original order - return sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - } - - return compare & 4 ? -1 : 1; - } : - function( a, b ) { - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Parentless nodes are either documents or disconnected - if ( !aup || !bup ) { - return a === document ? -1 : - b === document ? 1 : - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( (cur = cur.parentNode) ) { - ap.unshift( cur ); - } - cur = b; - while ( (cur = cur.parentNode) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[i] === bp[i] ) { - i++; - } - - return i ? - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[i], bp[i] ) : - - // Otherwise nodes in our document sort first - ap[i] === preferredDoc ? -1 : - bp[i] === preferredDoc ? 1 : - 0; - }; - - return document; -}; - -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; - -Sizzle.matchesSelector = function( elem, expr ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - // Make sure that attribute selectors are quoted - expr = expr.replace( rattributeQuotes, "='$1']" ); - - if ( support.matchesSelector && documentIsHTML && - !compilerCache[ expr + " " ] && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch (e) {} - } - - return Sizzle( expr, document, null, [ elem ] ).length > 0; -}; - -Sizzle.contains = function( context, elem ) { - // Set document vars if needed - if ( ( context.ownerDocument || context ) !== document ) { - setDocument( context ); - } - return contains( context, elem ); -}; - -Sizzle.attr = function( elem, name ) { - // Set document vars if needed - if ( ( elem.ownerDocument || elem ) !== document ) { - setDocument( elem ); - } - - var fn = Expr.attrHandle[ name.toLowerCase() ], - // Don't get fooled by Object.prototype properties (jQuery #13807) - val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? - fn( elem, name, !documentIsHTML ) : - undefined; - - return val !== undefined ? - val : - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - (val = elem.getAttributeNode(name)) && val.specified ? - val.value : - null; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Document sorting and removing duplicates - * @param {ArrayLike} results - */ -Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - j = 0, - i = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); - - if ( hasDuplicate ) { - while ( (elem = results[i++]) ) { - if ( elem === results[ i ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - // Clear input after sorting to release objects - // See https://github.com/jquery/sizzle/pull/225 - sortInput = null; - - return results; -}; - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - // If no nodeType, this is expected to be an array - while ( (node = elem[i++]) ) { - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - // Use textContent for elements - // innerText usage removed for consistency of new lines (jQuery #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - // Do not include comment or processing instruction nodes - - return ret; -}; - -Expr = Sizzle.selectors = { - - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - attrHandle: {}, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[1] = match[1].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); - - if ( match[2] === "~=" ) { - match[3] = " " + match[3] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[1] = match[1].toLowerCase(); - - if ( match[1].slice( 0, 3 ) === "nth" ) { - // nth-* requires argument - if ( !match[3] ) { - Sizzle.error( match[0] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); - match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); - - // other types prohibit arguments - } else if ( match[3] ) { - Sizzle.error( match[0] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[6] && match[2]; - - if ( matchExpr["CHILD"].test( match[0] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[3] ) { - match[2] = match[4] || match[5] || ""; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - // Get excess from tokenize (recursively) - (excess = tokenize( unquoted, true )) && - // advance to the next closing parenthesis - (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { - - // excess is a negative index - match[0] = match[0].slice( 0, excess ); - match[2] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); - return nodeNameSelector === "*" ? - function() { return true; } : - function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && - classCache( className, function( elem ) { - return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); - }); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - }; - }, - - "CHILD": function( type, what, argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, context, xml ) { - var cache, uniqueCache, outerCache, node, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType, - diff = false; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( (node = node[ dir ]) ) { - if ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) { - - return false; - } - } - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - - // Seek `elem` from a previously-cached index - - // ...in a gzip-friendly way - node = parent; - outerCache = node[ expando ] || (node[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - (outerCache[ node.uniqueID ] = {}); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex && cache[ 2 ]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( (node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - (diff = nodeIndex = 0) || start.pop()) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - } else { - // Use previously-cached element index if available - if ( useCache ) { - // ...in a gzip-friendly way - node = elem; - outerCache = node[ expando ] || (node[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - (outerCache[ node.uniqueID ] = {}); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex; - } - - // xml :nth-child(...) - // or :nth-last-child(...) or :nth(-last)?-of-type(...) - if ( diff === false ) { - // Use the same loop as above to seek `elem` from the start - while ( (node = ++nodeIndex && node && node[ dir ] || - (diff = nodeIndex = 0) || start.pop()) ) { - - if ( ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) && - ++diff ) { - - // Cache the index of each encountered element - if ( useCache ) { - outerCache = node[ expando ] || (node[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - (outerCache[ node.uniqueID ] = {}); - - uniqueCache[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction(function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf( seed, matched[i] ); - seed[ idx ] = !( matches[ idx ] = matched[i] ); - } - }) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - // Potentially complex pseudos - "not": markFunction(function( selector ) { - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction(function( seed, matches, context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( (elem = unmatched[i]) ) { - seed[i] = !(matches[i] = elem); - } - } - }) : - function( elem, context, xml ) { - input[0] = elem; - matcher( input, null, xml, results ); - // Don't keep the element (issue #299) - input[0] = null; - return !results.pop(); - }; - }), - - "has": markFunction(function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - }), - - "contains": markFunction(function( text ) { - text = text.replace( runescape, funescape ); - return function( elem ) { - return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; - }; - }), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - // lang value must be a valid identifier - if ( !ridentifier.test(lang || "") ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( (elemLang = documentIsHTML ? - elem.lang : - elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); - return false; - }; - }), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); - }, - - // Boolean properties - "enabled": function( elem ) { - return elem.disabled === false; - }, - - "disabled": function( elem ) { - return elem.disabled === true; - }, - - "checked": function( elem ) { - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); - }, - - "selected": function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), - // but not by others (comment: 8; processing instruction: 7; etc.) - // nodeType < 6 works because attributes (2) do not appear as children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeType < 6 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos["empty"]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - - // Support: IE<8 - // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" - ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); - }, - - // Position-in-collection - "first": createPositionalPseudo(function() { - return [ 0 ]; - }), - - "last": createPositionalPseudo(function( matchIndexes, length ) { - return [ length - 1 ]; - }), - - "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - }), - - "even": createPositionalPseudo(function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "odd": createPositionalPseudo(function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }), - - "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - }) - } -}; - -Expr.pseudos["nth"] = Expr.pseudos["eq"]; - -// Add button/input type pseudos -for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); -} -for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); -} - -// Easy API for creating new setFilters -function setFilters() {} -setFilters.prototype = Expr.filters = Expr.pseudos; -Expr.setFilters = new setFilters(); - -tokenize = Sizzle.tokenize = function( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || (match = rcomma.exec( soFar )) ) { - if ( match ) { - // Don't consume trailing commas as valid - soFar = soFar.slice( match[0].length ) || soFar; - } - groups.push( (tokens = []) ); - } - - matched = false; - - // Combinators - if ( (match = rcombinators.exec( soFar )) ) { - matched = match.shift(); - tokens.push({ - value: matched, - // Cast descendant combinators to space - type: match[0].replace( rtrim, " " ) - }); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || - (match = preFilters[ type ]( match ))) ) { - matched = match.shift(); - tokens.push({ - value: matched, - type: type, - matches: match - }); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -}; - -function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[i].value; - } - return selector; -} - -function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - checkNonElements = base && dir === "parentNode", - doneName = done++; - - return combinator.first ? - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var oldCache, uniqueCache, outerCache, - newCache = [ dirruns, doneName ]; - - // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching - if ( xml ) { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( (elem = elem[ dir ]) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || (elem[ expando ] = {}); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); - - if ( (oldCache = uniqueCache[ dir ]) && - oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { - - // Assign to newCache so results back-propagate to previous elements - return (newCache[ 2 ] = oldCache[ 2 ]); - } else { - // Reuse newcache so results back-propagate to previous elements - uniqueCache[ dir ] = newCache; - - // A match means we're done; a fail means we have to keep checking - if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { - return true; - } - } - } - } - } - }; -} - -function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[i]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[0]; -} - -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[i], results ); - } - return results; -} - -function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( (elem = unmatched[i]) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; -} - -function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction(function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( (elem = temp[i]) ) { - matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) ) { - // Restore matcherIn since elem is not yet a final match - temp.push( (matcherIn[i] = elem) ); - } - } - postFinder( null, (matcherOut = []), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( (elem = matcherOut[i]) && - (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { - - seed[temp] = !(results[temp] = elem); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - }); -} - -function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[0].type ], - implicitRelative = leadingRelative || Expr.relative[" "], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - (checkContext = context).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - // Avoid hanging onto element (issue #299) - checkContext = null; - return ret; - } ]; - - for ( ; i < len; i++ ) { - if ( (matcher = Expr.relative[ tokens[i].type ]) ) { - matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; - } else { - matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[j].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) - ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); -} - -function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - var bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, outermost ) { - var elem, j, matcher, - matchedCount = 0, - i = "0", - unmatched = seed && [], - setMatched = [], - contextBackup = outermostContext, - // We must always have either seed elements or outermost context - elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), - len = elems.length; - - if ( outermost ) { - outermostContext = context === document || context || outermost; - } - - // Add elements passing elementMatchers directly to results - // Support: IE<9, Safari - // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id - for ( ; i !== len && (elem = elems[i]) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - if ( !context && elem.ownerDocument !== document ) { - setDocument( elem ); - xml = !documentIsHTML; - } - while ( (matcher = elementMatchers[j++]) ) { - if ( matcher( elem, context || document, xml) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - // They will have gone through all possible matchers - if ( (elem = !matcher && elem) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // `i` is now the count of elements visited above, and adding it to `matchedCount` - // makes the latter nonnegative. - matchedCount += i; - - // Apply set filters to unmatched elements - // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` - // equals `i`), unless we didn't visit _any_ elements in the above loop because we have - // no element matchers and no seed. - // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that - // case, which will result in a "00" `matchedCount` that differs from `i` but is also - // numerically zero. - if ( bySet && i !== matchedCount ) { - j = 0; - while ( (matcher = setMatchers[j++]) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !(unmatched[i] || setMatched[i]) ) { - setMatched[i] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; -} - -compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - // Generate a function of recursive functions that can be used to check each element - if ( !match ) { - match = tokenize( selector ); - } - i = match.length; - while ( i-- ) { - cached = matcherFromTokens( match[i] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); - - // Save selector and tokenization - cached.selector = selector; - } - return cached; -}; - -/** - * A low-level selection function that works with Sizzle's compiled - * selector functions - * @param {String|Function} selector A selector or a pre-compiled - * selector function built with Sizzle.compile - * @param {Element} context - * @param {Array} [results] - * @param {Array} [seed] A set of elements to match against - */ -select = Sizzle.select = function( selector, context, results, seed ) { - var i, tokens, token, type, find, - compiled = typeof selector === "function" && selector, - match = !seed && tokenize( (selector = compiled.selector || selector) ); - - results = results || []; - - // Try to minimize operations if there is only one selector in the list and no seed - // (the latter of which guarantees us context) - if ( match.length === 1 ) { - - // Reduce context if the leading compound selector is an ID - tokens = match[0] = match[0].slice( 0 ); - if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && - support.getById && context.nodeType === 9 && documentIsHTML && - Expr.relative[ tokens[1].type ] ) { - - context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; - if ( !context ) { - return results; - - // Precompiled matchers will still verify ancestry, so step up a level - } else if ( compiled ) { - context = context.parentNode; - } - - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[i]; - - // Abort if we hit a combinator - if ( Expr.relative[ (type = token.type) ] ) { - break; - } - if ( (find = Expr.find[ type ]) ) { - // Search, expanding context for leading sibling combinators - if ( (seed = find( - token.matches[0].replace( runescape, funescape ), - rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context - )) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); - return results; - } - - break; - } - } - } - } - - // Compile and execute a filtering function if one is not provided - // Provide `match` to avoid retokenization if we modified the selector above - ( compiled || compile( selector, match ) )( - seed, - context, - !documentIsHTML, - results, - !context || rsibling.test( selector ) && testContext( context.parentNode ) || context - ); - return results; -}; - -// One-time assignments - -// Sort stability -support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; - -// Support: Chrome 14-35+ -// Always assume duplicates if they aren't passed to the comparison function -support.detectDuplicates = !!hasDuplicate; - -// Initialize against the default document -setDocument(); - -// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) -// Detached nodes confoundingly follow *each other* -support.sortDetached = assert(function( div1 ) { - // Should return 1, but returns 4 (following) - return div1.compareDocumentPosition( document.createElement("div") ) & 1; -}); - -// Support: IE<8 -// Prevent attribute/property "interpolation" -// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !assert(function( div ) { - div.innerHTML = ""; - return div.firstChild.getAttribute("href") === "#" ; -}) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - }); -} - -// Support: IE<9 -// Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert(function( div ) { - div.innerHTML = ""; - div.firstChild.setAttribute( "value", "" ); - return div.firstChild.getAttribute( "value" ) === ""; -}) ) { - addHandle( "value", function( elem, name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - }); -} - -// Support: IE<9 -// Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert(function( div ) { - return div.getAttribute("disabled") == null; -}) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - (val = elem.getAttributeNode( name )) && val.specified ? - val.value : - null; - } - }); -} - -return Sizzle; - -})( window ); - - - -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[ ":" ] = jQuery.expr.pseudos; -jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - - -var dir = function( elem, dir, until ) { - var matched = [], - truncate = until !== undefined; - - while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { - if ( elem.nodeType === 1 ) { - if ( truncate && jQuery( elem ).is( until ) ) { - break; - } - matched.push( elem ); - } - } - return matched; -}; - - -var siblings = function( n, elem ) { - var matched = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - matched.push( n ); - } - } - - return matched; -}; - - -var rneedsContext = jQuery.expr.match.needsContext; - -var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ ); - - - -var risSimple = /^.[^:#\[\.,]*$/; - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - /* jshint -W018 */ - return !!qualifier.call( elem, i, elem ) !== not; - } ); - - } - - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - } ); - - } - - if ( typeof qualifier === "string" ) { - if ( risSimple.test( qualifier ) ) { - return jQuery.filter( qualifier, elements, not ); - } - - qualifier = jQuery.filter( qualifier, elements ); - } - - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) > -1 ) !== not; - } ); -} - -jQuery.filter = function( expr, elems, not ) { - var elem = elems[ 0 ]; - - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 && elem.nodeType === 1 ? - jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : - jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - } ) ); -}; - -jQuery.fn.extend( { - find: function( selector ) { - var i, - len = this.length, - ret = [], - self = this; - - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter( function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - } ) ); - } - - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } - - // Needed because $( selector, context ) becomes $( context ).find( selector ) - ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); - ret.selector = this.selector ? this.selector + " " + selector : selector; - return ret; - }, - filter: function( selector ) { - return this.pushStack( winnow( this, selector || [], false ) ); - }, - not: function( selector ) { - return this.pushStack( winnow( this, selector || [], true ) ); - }, - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - } -} ); - - -// Initialize a jQuery object - - -// A central reference to the root jQuery(document) -var rootjQuery, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, - - init = jQuery.fn.init = function( selector, context, root ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Method init() accepts an alternate rootjQuery - // so migrate can support jQuery.sub (gh-2101) - root = root || rootjQuery; - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector[ 0 ] === "<" && - selector[ selector.length - 1 ] === ">" && - selector.length >= 3 ) { - - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && ( match[ 1 ] || !context ) ) { - - // HANDLE: $(html) -> $(array) - if ( match[ 1 ] ) { - context = context instanceof jQuery ? context[ 0 ] : context; - - // Option to run scripts is true for back-compat - // Intentionally let the error be thrown if parseHTML is not present - jQuery.merge( this, jQuery.parseHTML( - match[ 1 ], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - - // Properties of context are called as methods if possible - if ( jQuery.isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[ 2 ] ); - - // Support: Blackberry 4.6 - // gEBID returns nodes no longer in the document (#6963) - if ( elem && elem.parentNode ) { - - // Inject the element directly into the jQuery object - this.length = 1; - this[ 0 ] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || root ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this.context = this[ 0 ] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return root.ready !== undefined ? - root.ready( selector ) : - - // Execute immediately if ready is not present - selector( jQuery ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }; - -// Give the init function the jQuery prototype for later instantiation -init.prototype = jQuery.fn; - -// Initialize central reference -rootjQuery = jQuery( document ); - - -var rparentsprev = /^(?:parents|prev(?:Until|All))/, - - // Methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend( { - has: function( target ) { - var targets = jQuery( target, this ), - l = targets.length; - - return this.filter( function() { - var i = 0; - for ( ; i < l; i++ ) { - if ( jQuery.contains( this, targets[ i ] ) ) { - return true; - } - } - } ); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( ; i < l; i++ ) { - for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { - - // Always skip document fragments - if ( cur.nodeType < 11 && ( pos ? - pos.index( cur ) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector( cur, selectors ) ) ) { - - matched.push( cur ); - break; - } - } - } - - return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); - }, - - // Determine the position of an element within the set - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; - } - - // Index in selector - if ( typeof elem === "string" ) { - return indexOf.call( jQuery( elem ), this[ 0 ] ); - } - - // Locate the position of the desired element - return indexOf.call( this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[ 0 ] : elem - ); - }, - - add: function( selector, context ) { - return this.pushStack( - jQuery.uniqueSort( - jQuery.merge( this.get(), jQuery( selector, context ) ) - ) - ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter( selector ) - ); - } -} ); - -function sibling( cur, dir ) { - while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} - return cur; -} - -jQuery.each( { - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return siblings( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return siblings( elem.firstChild ); - }, - contents: function( elem ) { - return elem.contentDocument || jQuery.merge( [], elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var matched = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - matched = jQuery.filter( selector, matched ); - } - - if ( this.length > 1 ) { - - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - jQuery.uniqueSort( matched ); - } - - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - matched.reverse(); - } - } - - return this.pushStack( matched ); - }; -} ); -var rnotwhite = ( /\S+/g ); - - - -// Convert String-formatted options into Object-formatted ones -function createOptions( options ) { - var object = {}; - jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { - object[ flag ] = true; - } ); - return object; -} - -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - createOptions( options ) : - jQuery.extend( {}, options ); - - var // Flag to know if list is currently firing - firing, - - // Last fire value for non-forgettable lists - memory, - - // Flag to know if list was already fired - fired, - - // Flag to prevent firing - locked, - - // Actual callback list - list = [], - - // Queue of execution data for repeatable lists - queue = [], - - // Index of currently firing callback (modified by add/remove as needed) - firingIndex = -1, - - // Fire callbacks - fire = function() { - - // Enforce single-firing - locked = options.once; - - // Execute callbacks for all pending executions, - // respecting firingIndex overrides and runtime changes - fired = firing = true; - for ( ; queue.length; firingIndex = -1 ) { - memory = queue.shift(); - while ( ++firingIndex < list.length ) { - - // Run callback and check for early termination - if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && - options.stopOnFalse ) { - - // Jump to end and forget the data so .add doesn't re-fire - firingIndex = list.length; - memory = false; - } - } - } - - // Forget the data if we're done with it - if ( !options.memory ) { - memory = false; - } - - firing = false; - - // Clean up if we're done firing for good - if ( locked ) { - - // Keep an empty list if we have data for future add calls - if ( memory ) { - list = []; - - // Otherwise, this object is spent - } else { - list = ""; - } - } - }, - - // Actual Callbacks object - self = { - - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - - // If we have memory from a past run, we should fire after adding - if ( memory && !firing ) { - firingIndex = list.length - 1; - queue.push( memory ); - } - - ( function add( args ) { - jQuery.each( args, function( _, arg ) { - if ( jQuery.isFunction( arg ) ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { - - // Inspect recursively - add( arg ); - } - } ); - } )( arguments ); - - if ( memory && !firing ) { - fire(); - } - } - return this; - }, - - // Remove a callback from the list - remove: function() { - jQuery.each( arguments, function( _, arg ) { - var index; - while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - - // Handle firing indexes - if ( index <= firingIndex ) { - firingIndex--; - } - } - } ); - return this; - }, - - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? - jQuery.inArray( fn, list ) > -1 : - list.length > 0; - }, - - // Remove all callbacks from the list - empty: function() { - if ( list ) { - list = []; - } - return this; - }, - - // Disable .fire and .add - // Abort any current/pending executions - // Clear all callbacks and values - disable: function() { - locked = queue = []; - list = memory = ""; - return this; - }, - disabled: function() { - return !list; - }, - - // Disable .fire - // Also disable .add unless we have memory (since it would have no effect) - // Abort any pending executions - lock: function() { - locked = queue = []; - if ( !memory ) { - list = memory = ""; - } - return this; - }, - locked: function() { - return !!locked; - }, - - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( !locked ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - queue.push( args ); - if ( !firing ) { - fire(); - } - } - return this; - }, - - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; - - -jQuery.extend( { - - Deferred: function( func ) { - var tuples = [ - - // action, add listener, listener list, final state - [ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ], - [ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ], - [ "notify", "progress", jQuery.Callbacks( "memory" ) ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - then: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - return jQuery.Deferred( function( newDefer ) { - jQuery.each( tuples, function( i, tuple ) { - var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; - - // deferred[ done | fail | progress ] for forwarding actions to newDefer - deferred[ tuple[ 1 ] ]( function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise() - .progress( newDefer.notify ) - .done( newDefer.resolve ) - .fail( newDefer.reject ); - } else { - newDefer[ tuple[ 0 ] + "With" ]( - this === promise ? newDefer.promise() : this, - fn ? [ returned ] : arguments - ); - } - } ); - } ); - fns = null; - } ).promise(); - }, - - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Keep pipe for back-compat - promise.pipe = promise.then; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 3 ]; - - // promise[ done | fail | progress ] = list.add - promise[ tuple[ 1 ] ] = list.add; - - // Handle state - if ( stateString ) { - list.add( function() { - - // state = [ resolved | rejected ] - state = stateString; - - // [ reject_list | resolve_list ].disable; progress_list.lock - }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); - } - - // deferred[ resolve | reject | notify ] - deferred[ tuple[ 0 ] ] = function() { - deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments ); - return this; - }; - deferred[ tuple[ 0 ] + "With" ] = list.fireWith; - } ); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( subordinate /* , ..., subordinateN */ ) { - var i = 0, - resolveValues = slice.call( arguments ), - length = resolveValues.length, - - // the count of uncompleted subordinates - remaining = length !== 1 || - ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, - - // the master Deferred. - // If resolveValues consist of only a single Deferred, just use that. - deferred = remaining === 1 ? subordinate : jQuery.Deferred(), - - // Update function for both resolve and progress values - updateFunc = function( i, contexts, values ) { - return function( value ) { - contexts[ i ] = this; - values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( values === progressValues ) { - deferred.notifyWith( contexts, values ); - } else if ( !( --remaining ) ) { - deferred.resolveWith( contexts, values ); - } - }; - }, - - progressValues, progressContexts, resolveContexts; - - // Add listeners to Deferred subordinates; treat others as resolved - if ( length > 1 ) { - progressValues = new Array( length ); - progressContexts = new Array( length ); - resolveContexts = new Array( length ); - for ( ; i < length; i++ ) { - if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { - resolveValues[ i ].promise() - .progress( updateFunc( i, progressContexts, progressValues ) ) - .done( updateFunc( i, resolveContexts, resolveValues ) ) - .fail( deferred.reject ); - } else { - --remaining; - } - } - } - - // If we're not waiting on anything, resolve the master - if ( !remaining ) { - deferred.resolveWith( resolveContexts, resolveValues ); - } - - return deferred.promise(); - } -} ); - - -// The deferred used on DOM ready -var readyList; - -jQuery.fn.ready = function( fn ) { - - // Add the callback - jQuery.ready.promise().done( fn ); - - return this; -}; - -jQuery.extend( { - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.triggerHandler ) { - jQuery( document ).triggerHandler( "ready" ); - jQuery( document ).off( "ready" ); - } - } -} ); - -/** - * The ready event handler and self cleanup method - */ -function completed() { - document.removeEventListener( "DOMContentLoaded", completed ); - window.removeEventListener( "load", completed ); - jQuery.ready(); -} - -jQuery.ready.promise = function( obj ) { - if ( !readyList ) { - - readyList = jQuery.Deferred(); - - // Catch cases where $(document).ready() is called - // after the browser event has already occurred. - // Support: IE9-10 only - // Older IE sometimes signals "interactive" too soon - if ( document.readyState === "complete" || - ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { - - // Handle it asynchronously to allow scripts the opportunity to delay ready - window.setTimeout( jQuery.ready ); - - } else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed ); - } - } - return readyList.promise( obj ); -}; - -// Kick off the DOM ready check even if the user does not -jQuery.ready.promise(); - - - - -// Multifunctional method to get and set values of a collection -// The value/s can optionally be executed if it's a function -var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - len = elems.length, - bulk = key == null; - - // Sets many values - if ( jQuery.type( key ) === "object" ) { - chainable = true; - for ( i in key ) { - access( elems, fn, i, key[ i ], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !jQuery.isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < len; i++ ) { - fn( - elems[ i ], key, raw ? - value : - value.call( elems[ i ], i, fn( elems[ i ], key ) ) - ); - } - } - } - - return chainable ? - elems : - - // Gets - bulk ? - fn.call( elems ) : - len ? fn( elems[ 0 ], key ) : emptyGet; -}; -var acceptData = function( owner ) { - - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - /* jshint -W018 */ - return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); -}; - - - - -function Data() { - this.expando = jQuery.expando + Data.uid++; -} - -Data.uid = 1; - -Data.prototype = { - - register: function( owner, initial ) { - var value = initial || {}; - - // If it is a node unlikely to be stringify-ed or looped over - // use plain assignment - if ( owner.nodeType ) { - owner[ this.expando ] = value; - - // Otherwise secure it in a non-enumerable, non-writable property - // configurability must be true to allow the property to be - // deleted with the delete operator - } else { - Object.defineProperty( owner, this.expando, { - value: value, - writable: true, - configurable: true - } ); - } - return owner[ this.expando ]; - }, - cache: function( owner ) { - - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return an empty object. - if ( !acceptData( owner ) ) { - return {}; - } - - // Check if the owner object already has a cache - var value = owner[ this.expando ]; - - // If not, create one - if ( !value ) { - value = {}; - - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return an empty object. - if ( acceptData( owner ) ) { - - // If it is a node unlikely to be stringify-ed or looped over - // use plain assignment - if ( owner.nodeType ) { - owner[ this.expando ] = value; - - // Otherwise secure it in a non-enumerable property - // configurable must be true to allow the property to be - // deleted when data is removed - } else { - Object.defineProperty( owner, this.expando, { - value: value, - configurable: true - } ); - } - } - } - - return value; - }, - set: function( owner, data, value ) { - var prop, - cache = this.cache( owner ); - - // Handle: [ owner, key, value ] args - if ( typeof data === "string" ) { - cache[ data ] = value; - - // Handle: [ owner, { properties } ] args - } else { - - // Copy the properties one-by-one to the cache object - for ( prop in data ) { - cache[ prop ] = data[ prop ]; - } - } - return cache; - }, - get: function( owner, key ) { - return key === undefined ? - this.cache( owner ) : - owner[ this.expando ] && owner[ this.expando ][ key ]; - }, - access: function( owner, key, value ) { - var stored; - - // In cases where either: - // - // 1. No key was specified - // 2. A string key was specified, but no value provided - // - // Take the "read" path and allow the get method to determine - // which value to return, respectively either: - // - // 1. The entire cache object - // 2. The data stored at the key - // - if ( key === undefined || - ( ( key && typeof key === "string" ) && value === undefined ) ) { - - stored = this.get( owner, key ); - - return stored !== undefined ? - stored : this.get( owner, jQuery.camelCase( key ) ); - } - - // When the key is not a string, or both a key and value - // are specified, set or extend (existing objects) with either: - // - // 1. An object of properties - // 2. A key and value - // - this.set( owner, key, value ); - - // Since the "set" path can have two possible entry points - // return the expected data based on which path was taken[*] - return value !== undefined ? value : key; - }, - remove: function( owner, key ) { - var i, name, camel, - cache = owner[ this.expando ]; - - if ( cache === undefined ) { - return; - } - - if ( key === undefined ) { - this.register( owner ); - - } else { - - // Support array or space separated string of keys - if ( jQuery.isArray( key ) ) { - - // If "name" is an array of keys... - // When data is initially created, via ("key", "val") signature, - // keys will be converted to camelCase. - // Since there is no way to tell _how_ a key was added, remove - // both plain key and camelCase key. #12786 - // This will only penalize the array argument path. - name = key.concat( key.map( jQuery.camelCase ) ); - } else { - camel = jQuery.camelCase( key ); - - // Try the string as a key before any manipulation - if ( key in cache ) { - name = [ key, camel ]; - } else { - - // If a key with the spaces exists, use it. - // Otherwise, create an array by matching non-whitespace - name = camel; - name = name in cache ? - [ name ] : ( name.match( rnotwhite ) || [] ); - } - } - - i = name.length; - - while ( i-- ) { - delete cache[ name[ i ] ]; - } - } - - // Remove the expando if there's no more data - if ( key === undefined || jQuery.isEmptyObject( cache ) ) { - - // Support: Chrome <= 35-45+ - // Webkit & Blink performance suffers when deleting properties - // from DOM nodes, so set to undefined instead - // https://code.google.com/p/chromium/issues/detail?id=378607 - if ( owner.nodeType ) { - owner[ this.expando ] = undefined; - } else { - delete owner[ this.expando ]; - } - } - }, - hasData: function( owner ) { - var cache = owner[ this.expando ]; - return cache !== undefined && !jQuery.isEmptyObject( cache ); - } -}; -var dataPriv = new Data(); - -var dataUser = new Data(); - - - -// Implementation Summary -// -// 1. Enforce API surface and semantic compatibility with 1.9.x branch -// 2. Improve the module's maintainability by reducing the storage -// paths to a single mechanism. -// 3. Use the same single mechanism to support "private" and "user" data. -// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) -// 5. Avoid exposing implementation details on user objects (eg. expando properties) -// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 - -var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, - rmultiDash = /[A-Z]/g; - -function dataAttr( elem, key, data ) { - var name; - - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - - // Only convert to a number if it doesn't change the string - +data + "" === data ? +data : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch ( e ) {} - - // Make sure we set the data so it isn't changed later - dataUser.set( elem, key, data ); - } else { - data = undefined; - } - } - return data; -} - -jQuery.extend( { - hasData: function( elem ) { - return dataUser.hasData( elem ) || dataPriv.hasData( elem ); - }, - - data: function( elem, name, data ) { - return dataUser.access( elem, name, data ); - }, - - removeData: function( elem, name ) { - dataUser.remove( elem, name ); - }, - - // TODO: Now that all calls to _data and _removeData have been replaced - // with direct calls to dataPriv methods, these can be deprecated. - _data: function( elem, name, data ) { - return dataPriv.access( elem, name, data ); - }, - - _removeData: function( elem, name ) { - dataPriv.remove( elem, name ); - } -} ); - -jQuery.fn.extend( { - data: function( key, value ) { - var i, name, data, - elem = this[ 0 ], - attrs = elem && elem.attributes; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = dataUser.get( elem ); - - if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { - i = attrs.length; - while ( i-- ) { - - // Support: IE11+ - // The attrs elements can be null (#14894) - if ( attrs[ i ] ) { - name = attrs[ i ].name; - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.slice( 5 ) ); - dataAttr( elem, name, data[ name ] ); - } - } - } - dataPriv.set( elem, "hasDataAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each( function() { - dataUser.set( this, key ); - } ); - } - - return access( this, function( value ) { - var data, camelKey; - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if ( elem && value === undefined ) { - - // Attempt to get data from the cache - // with the key as-is - data = dataUser.get( elem, key ) || - - // Try to find dashed key if it exists (gh-2779) - // This is for 2.2.x only - dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() ); - - if ( data !== undefined ) { - return data; - } - - camelKey = jQuery.camelCase( key ); - - // Attempt to get data from the cache - // with the key camelized - data = dataUser.get( elem, camelKey ); - if ( data !== undefined ) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr( elem, camelKey, undefined ); - if ( data !== undefined ) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - camelKey = jQuery.camelCase( key ); - this.each( function() { - - // First, attempt to store a copy or reference of any - // data that might've been store with a camelCased key. - var data = dataUser.get( this, camelKey ); - - // For HTML5 data-* attribute interop, we have to - // store property names with dashes in a camelCase form. - // This might not apply to all properties...* - dataUser.set( this, camelKey, value ); - - // *... In the case of properties that might _actually_ - // have dashes, we need to also store a copy of that - // unchanged property. - if ( key.indexOf( "-" ) > -1 && data !== undefined ) { - dataUser.set( this, key, value ); - } - } ); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each( function() { - dataUser.remove( this, key ); - } ); - } -} ); - - -jQuery.extend( { - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = dataPriv.get( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || jQuery.isArray( data ) ) { - queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // Clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // Not public - generate a queueHooks object, or return the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { - empty: jQuery.Callbacks( "once memory" ).add( function() { - dataPriv.remove( elem, [ type + "queue", key ] ); - } ) - } ); - } -} ); - -jQuery.fn.extend( { - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[ 0 ], type ); - } - - return data === undefined ? - this : - this.each( function() { - var queue = jQuery.queue( this, type, data ); - - // Ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - } ); - }, - dequeue: function( type ) { - return this.each( function() { - jQuery.dequeue( this, type ); - } ); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while ( i-- ) { - tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } -} ); -var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; - -var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); - - -var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - -var isHidden = function( elem, el ) { - - // isHidden might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - return jQuery.css( elem, "display" ) === "none" || - !jQuery.contains( elem.ownerDocument, elem ); - }; - - - -function adjustCSS( elem, prop, valueParts, tween ) { - var adjusted, - scale = 1, - maxIterations = 20, - currentValue = tween ? - function() { return tween.cur(); } : - function() { return jQuery.css( elem, prop, "" ); }, - initial = currentValue(), - unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), - - // Starting value computation is required for potential unit mismatches - initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && - rcssNum.exec( jQuery.css( elem, prop ) ); - - if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { - - // Trust units reported by jQuery.css - unit = unit || initialInUnit[ 3 ]; - - // Make sure we update the tween properties later on - valueParts = valueParts || []; - - // Iteratively approximate from a nonzero starting point - initialInUnit = +initial || 1; - - do { - - // If previous iteration zeroed out, double until we get *something*. - // Use string for doubling so we don't accidentally see scale as unchanged below - scale = scale || ".5"; - - // Adjust and apply - initialInUnit = initialInUnit / scale; - jQuery.style( elem, prop, initialInUnit + unit ); - - // Update scale, tolerating zero or NaN from tween.cur() - // Break the loop if scale is unchanged or perfect, or if we've just had enough. - } while ( - scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations - ); - } - - if ( valueParts ) { - initialInUnit = +initialInUnit || +initial || 0; - - // Apply relative offset (+=/-=) if specified - adjusted = valueParts[ 1 ] ? - initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : - +valueParts[ 2 ]; - if ( tween ) { - tween.unit = unit; - tween.start = initialInUnit; - tween.end = adjusted; - } - } - return adjusted; -} -var rcheckableType = ( /^(?:checkbox|radio)$/i ); - -var rtagName = ( /<([\w:-]+)/ ); - -var rscriptType = ( /^$|\/(?:java|ecma)script/i ); - - - -// We have to close these tags to support XHTML (#13200) -var wrapMap = { - - // Support: IE9 - option: [ 1, "", "" ], - - // XHTML parsers do not magically insert elements in the - // same way that tag soup parsers do. So we cannot shorten - // this by omitting or other required elements. - thead: [ 1, "", "" ], - col: [ 2, "", "" ], - tr: [ 2, "", "" ], - td: [ 3, "", "" ], - - _default: [ 0, "", "" ] -}; - -// Support: IE9 -wrapMap.optgroup = wrapMap.option; - -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - - -function getAll( context, tag ) { - - // Support: IE9-11+ - // Use typeof to avoid zero-argument method invocation on host objects (#15151) - var ret = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( tag || "*" ) : - typeof context.querySelectorAll !== "undefined" ? - context.querySelectorAll( tag || "*" ) : - []; - - return tag === undefined || tag && jQuery.nodeName( context, tag ) ? - jQuery.merge( [ context ], ret ) : - ret; -} - - -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - dataPriv.set( - elems[ i ], - "globalEval", - !refElements || dataPriv.get( refElements[ i ], "globalEval" ) - ); - } -} - - -var rhtml = /<|?\w+;/; - -function buildFragment( elems, context, scripts, selection, ignored ) { - var elem, tmp, tag, wrap, contains, j, - fragment = context.createDocumentFragment(), - nodes = [], - i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( jQuery.type( elem ) === "object" ) { - - // Support: Android<4.1, PhantomJS<2 - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; - - // Descend through wrappers to the right content - j = wrap[ 0 ]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Support: Android<4.1, PhantomJS<2 - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, tmp.childNodes ); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Ensure the created nodes are orphaned (#12392) - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ( ( elem = nodes[ i++ ] ) ) { - - // Skip elements already in the context collection (trac-4087) - if ( selection && jQuery.inArray( elem, selection ) > -1 ) { - if ( ignored ) { - ignored.push( elem ); - } - continue; - } - - contains = jQuery.contains( elem.ownerDocument, elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( contains ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( ( elem = tmp[ j++ ] ) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - return fragment; -} - - -( function() { - var fragment = document.createDocumentFragment(), - div = fragment.appendChild( document.createElement( "div" ) ), - input = document.createElement( "input" ); - - // Support: Android 4.0-4.3, Safari<=5.1 - // Check state lost if the name is set (#11217) - // Support: Windows Web Apps (WWA) - // `name` and `type` must use .setAttribute for WWA (#14901) - input.setAttribute( "type", "radio" ); - input.setAttribute( "checked", "checked" ); - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - - // Support: Safari<=5.1, Android<4.2 - // Older WebKit doesn't clone checked state correctly in fragments - support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE<=11+ - // Make sure textarea (and checkbox) defaultValue is properly cloned - div.innerHTML = "x"; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; -} )(); - - -var - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, - rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -// Support: IE9 -// See #13393 for more info -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - -function on( elem, types, selector, data, fn, one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - on( elem, type, selector, data, types[ type ], one ); - } - return elem; - } - - if ( data == null && fn == null ) { - - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return elem; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return elem.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - } ); -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.get( elem ); - - // Don't attach events to noData or text/comment nodes (but allow plain objects) - if ( !elemData ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !( events = elemData.events ) ) { - events = elemData.events = {}; - } - if ( !( eventHandle = elemData.handle ) ) { - eventHandle = elemData.handle = function( e ) { - - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? - jQuery.event.dispatch.apply( elem, arguments ) : undefined; - }; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( rnotwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend( { - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join( "." ) - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !( handlers = events[ type ] ) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || - special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); - - if ( !elemData || !( events = elemData.events ) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnotwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[ 2 ] && - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || - selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || - special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove data and the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - dataPriv.remove( elem, "handle events" ); - } - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event ); - - var i, j, ret, matched, handleObj, - handlerQueue = [], - args = slice.call( arguments ), - handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[ 0 ] = event; - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( ( handleObj = matched.handlers[ j++ ] ) && - !event.isImmediatePropagationStopped() ) { - - // Triggered event must either 1) have no namespace, or 2) have namespace(s) - // a subset or equal to those in the bound event (both can have no namespace). - if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || - handleObj.handler ).apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( ( event.result = ret ) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, matches, sel, handleObj, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Support (at least): Chrome, IE9 - // Find delegate handlers - // Black-hole SVG instance trees (#13180) - // - // Support: Firefox<=42+ - // Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343) - if ( delegateCount && cur.nodeType && - ( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) { - matches = []; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matches[ sel ] === undefined ) { - matches[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) > -1 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matches[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push( { elem: cur, handlers: matches } ); - } - } - } - } - - // Add the remaining (directly-bound) handlers - if ( delegateCount < handlers.length ) { - handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } ); - } - - return handlerQueue; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + - "metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split( " " ), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: ( "button buttons clientX clientY offsetX offsetY pageX pageY " + - "screenX screenY toElement" ).split( " " ), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + - ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + - ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, copy, - type = event.type, - originalEvent = event, - fixHook = this.fixHooks[ type ]; - - if ( !fixHook ) { - this.fixHooks[ type ] = fixHook = - rmouseEvent.test( type ) ? this.mouseHooks : - rkeyEvent.test( type ) ? this.keyHooks : - {}; - } - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = new jQuery.Event( originalEvent ); - - i = copy.length; - while ( i-- ) { - prop = copy[ i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Support: Cordova 2.5 (WebKit) (#13255) - // All events should have a target; Cordova deviceready doesn't - if ( !event.target ) { - event.target = document; - } - - // Support: Safari 6.0+, Chrome<28 - // Target should not be a text node (#504, #13143) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; - }, - - special: { - load: { - - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - focus: { - - // Fire native event if possible so blur/focus sequence is correct - trigger: function() { - if ( this !== safeActiveElement() && this.focus ) { - this.focus(); - return false; - } - }, - delegateType: "focusin" - }, - blur: { - trigger: function() { - if ( this === safeActiveElement() && this.blur ) { - this.blur(); - return false; - } - }, - delegateType: "focusout" - }, - click: { - - // For checkbox, fire native event so checked state will be right - trigger: function() { - if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { - this.click(); - return false; - } - }, - - // For cross-browser consistency, don't fire native .click() on links - _default: function( event ) { - return jQuery.nodeName( event.target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; - } - } - } - } -}; - -jQuery.removeEvent = function( elem, type, handle ) { - - // This "if" is needed for plain objects - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle ); - } -}; - -jQuery.Event = function( src, props ) { - - // Allow instantiation without the 'new' keyword - if ( !( this instanceof jQuery.Event ) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && - - // Support: Android<4.0 - src.returnValue === false ? - returnTrue : - returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - constructor: jQuery.Event, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - var e = this.originalEvent; - - this.isImmediatePropagationStopped = returnTrue; - - if ( e ) { - e.stopImmediatePropagation(); - } - - this.stopPropagation(); - } -}; - -// Create mouseenter/leave events using mouseover/out and event-time checks -// so that event delegation works in jQuery. -// Do the same for pointerenter/pointerleave and pointerover/pointerout -// -// Support: Safari 7 only -// Safari sends mouseenter too often; see: -// https://code.google.com/p/chromium/issues/detail?id=470258 -// for the description of the bug (it existed in older Chrome versions as well). -jQuery.each( { - mouseenter: "mouseover", - mouseleave: "mouseout", - pointerenter: "pointerover", - pointerleave: "pointerout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mouseenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -} ); - -jQuery.fn.extend( { - on: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn ); - }, - one: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? - handleObj.origType + "." + handleObj.namespace : - handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each( function() { - jQuery.event.remove( this, types, fn, selector ); - } ); - } -} ); - - -var - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi, - - // Support: IE 10-11, Edge 10240+ - // In IE/Edge using regex groups here causes severe slowdowns. - // See https://connect.microsoft.com/IE/feedback/details/1736512/ - rnoInnerhtml = / - ``` - - And associate it by name using a view's `templateName` property: - - ```javascript - AView = Ember.View.extend({ - templateName: 'some-template' - }); - ``` - - If you have nested routes, your Handlebars template will look like this: - - ```html - - ``` - - And `templateName` property: - - ```javascript - AView = Ember.View.extend({ - templateName: 'posts/new' - }); - ``` - - Using a value for `templateName` that does not have a template - with a matching `data-template-name` attribute will throw an error. - - For views classes that may have a template later defined (e.g. as the block - portion of a `{{view}}` helper call in another template or in - a subclass), you can provide a `defaultTemplate` property set to compiled - template function. If a template is not later provided for the view instance - the `defaultTemplate` value will be used: - - ```javascript - AView = Ember.View.extend({ - defaultTemplate: Ember.HTMLBars.compile('I was the default'), - template: null, - templateName: null - }); - ``` - - Will result in instances with an HTML representation of: - - ```html - I was the default - ``` - - If a `template` or `templateName` is provided it will take precedence over - `defaultTemplate`: - - ```javascript - AView = Ember.View.extend({ - defaultTemplate: Ember.HTMLBars.compile('I was the default') - }); - - aView = AView.create({ - template: Ember.HTMLBars.compile('I was the template, not default') - }); - ``` - - Will result in the following HTML representation when rendered: - - ```html - I was the template, not default - ``` - - ## View Context - - The default context of the compiled template is the view's controller: - - ```javascript - AView = Ember.View.extend({ - template: Ember.HTMLBars.compile('Hello {{excitedGreeting}}') - }); - - aController = Ember.Object.create({ - firstName: 'Barry', - excitedGreeting: Ember.computed('content.firstName', function() { - return this.get('content.firstName') + '!!!'; - }) - }); - - aView = AView.create({ - controller: aController - }); - ``` - - Will result in an HTML representation of: - - ```html - Hello Barry!!! - ``` - - A context can also be explicitly supplied through the view's `context` - property. If the view has neither `context` nor `controller` properties, the - `parentView`'s context will be used. - - ## Layouts - - Views can have a secondary template that wraps their main template. Like - primary templates, layouts can be any function that accepts an optional - context parameter and returns a string of HTML that will be inserted inside - view's tag. Views whose HTML element is self closing (e.g. ``) - cannot have a layout and this property will be ignored. - - Most typically in Ember a layout will be a compiled template. - - A view's layout can be set directly with the `layout` property or reference - an existing template by name with the `layoutName` property. - - A template used as a layout must contain a single use of the - `{{yield}}` helper. The HTML contents of a view's rendered `template` will be - inserted at this location: - - ```javascript - AViewWithLayout = Ember.View.extend({ - layout: Ember.HTMLBars.compile("{{yield}}"), - template: Ember.HTMLBars.compile("I got wrapped") - }); - ``` - - Will result in view instances with an HTML representation of: - - ```html - - - I got wrapped - - - ``` - - See [Ember.Templates.helpers.yield](/api/classes/Ember.Templates.helpers.html#method_yield) - for more information. - - ## Responding to Browser Events - - Views can respond to user-initiated events in one of three ways: method - implementation, through an event manager, and through `{{action}}` helper use - in their template or layout. - - ### Method Implementation - - Views can respond to user-initiated events by implementing a method that - matches the event name. A `jQuery.Event` object will be passed as the - argument to this method. - - ```javascript - AView = Ember.View.extend({ - click: function(event) { - // will be called when an instance's - // rendered element is clicked - } - }); - ``` - - ### Event Managers - - Views can define an object as their `eventManager` property. This object can - then implement methods that match the desired event names. Matching events - that occur on the view's rendered HTML or the rendered HTML of any of its DOM - descendants will trigger this method. A `jQuery.Event` object will be passed - as the first argument to the method and an `Ember.View` object as the - second. The `Ember.View` will be the view whose rendered HTML was interacted - with. This may be the view with the `eventManager` property or one of its - descendant views. - - ```javascript - AView = Ember.View.extend({ - eventManager: Ember.Object.create({ - doubleClick: function(event, view) { - // will be called when an instance's - // rendered element or any rendering - // of this view's descendant - // elements is clicked - } - }) - }); - ``` - - An event defined for an event manager takes precedence over events of the - same name handled through methods on the view. - - ```javascript - AView = Ember.View.extend({ - mouseEnter: function(event) { - // will never trigger. - }, - eventManager: Ember.Object.create({ - mouseEnter: function(event, view) { - // takes precedence over AView#mouseEnter - } - }) - }); - ``` - - Similarly a view's event manager will take precedence for events of any views - rendered as a descendant. A method name that matches an event name will not - be called if the view instance was rendered inside the HTML representation of - a view that has an `eventManager` property defined that handles events of the - name. Events not handled by the event manager will still trigger method calls - on the descendant. - - ```javascript - var App = Ember.Application.create(); - App.OuterView = Ember.View.extend({ - template: Ember.HTMLBars.compile("outer {{#view 'inner'}}inner{{/view}} outer"), - eventManager: Ember.Object.create({ - mouseEnter: function(event, view) { - // view might be instance of either - // OuterView or InnerView depending on - // where on the page the user interaction occurred - } - }) - }); - - App.InnerView = Ember.View.extend({ - click: function(event) { - // will be called if rendered inside - // an OuterView because OuterView's - // eventManager doesn't handle click events - }, - mouseEnter: function(event) { - // will never be called if rendered inside - // an OuterView. - } - }); - ``` - - ### `{{action}}` Helper - - See [Ember.Templates.helpers.action](/api/classes/Ember.Templates.helpers.html#method_action). - - ### Event Names - - All of the event handling approaches described above respond to the same set - of events. The names of the built-in events are listed below. (The hash of - built-in events exists in `Ember.EventDispatcher`.) Additional, custom events - can be registered by using `Ember.Application.customEvents`. - - Touch events: - - * `touchStart` - * `touchMove` - * `touchEnd` - * `touchCancel` - - Keyboard events - - * `keyDown` - * `keyUp` - * `keyPress` - - Mouse events - - * `mouseDown` - * `mouseUp` - * `contextMenu` - * `click` - * `doubleClick` - * `mouseMove` - * `focusIn` - * `focusOut` - * `mouseEnter` - * `mouseLeave` - - Form events: - - * `submit` - * `change` - * `focusIn` - * `focusOut` - * `input` - - HTML5 drag and drop events: - - * `dragStart` - * `drag` - * `dragEnter` - * `dragLeave` - * `dragOver` - * `dragEnd` - * `drop` - - ## `{{view}}` Helper - - Other `Ember.View` instances can be included as part of a view's template by - using the `{{view}}` helper. See [Ember.Templates.helpers.view](/api/classes/Ember.Templates.helpers.html#method_view) - for additional information. - - @class View - @namespace Ember - @extends Ember.CoreView - @deprecated See http://emberjs.com/deprecations/v1.x/#toc_ember-view - @uses Ember.ViewContextSupport - @uses Ember.ViewChildViewsSupport - @uses Ember.TemplateRenderingSupport - @uses Ember.ClassNamesSupport - @uses Ember.AttributeBindingsSupport - @uses Ember.LegacyViewSupport - @uses Ember.InstrumentationSupport - @uses Ember.VisibilitySupport - @uses Ember.AriaRoleSupport - @public - */ - // jscs:disable validateIndentation - var View = _emberViewsViewsCore_view.default.extend(_emberViewsMixinsView_context_support.default, _emberViewsMixinsView_child_views_support.default, _emberViewsMixinsLegacy_child_views_support.default, _emberViewsMixinsView_state_support.default, _emberViewsMixinsTemplate_rendering_support.default, _emberViewsMixinsClass_names_support.default, _emberViewsMixinsLegacy_view_support.default, _emberViewsMixinsInstrumentation_support.default, _emberViewsMixinsVisibility_support.default, _emberViewsCompatAttrsProxy.default, _emberViewsMixinsAria_role_support.default, _emberViewsMixinsView_support.default, { - init: function () { - this._super.apply(this, arguments); - - if (!this._viewRegistry) { - this._viewRegistry = View.views; - } - }, - - /** - Given a property name, returns a dasherized version of that - property name if the property evaluates to a non-falsy value. - For example, if the view has property `isUrgent` that evaluates to true, - passing `isUrgent` to this method will return `"is-urgent"`. - @method _classStringForProperty - @param property - @private - */ - _classStringForProperty: function (parsedPath) { - return View._classStringForValue(parsedPath.path, parsedPath.stream.value(), parsedPath.className, parsedPath.falsyClassName); - } - }); - - _emberMetalDeprecate_property.deprecateProperty(View.prototype, 'currentState', '_currentState', { - id: 'ember-view.current-state', - until: '2.3.0', - url: 'http://emberjs.com/deprecations/v2.x/#toc_ember-component-currentstate' - }); - - // jscs:enable validateIndentation - - /* - Describe how the specified actions should behave in the various - states that a view can exist in. Possible states: - - * preRender: when a view is first instantiated, and after its - element was destroyed, it is in the preRender state - * inBuffer: once a view has been rendered, but before it has - been inserted into the DOM, it is in the inBuffer state - * hasElement: the DOM representation of the view is created, - and is ready to be inserted - * inDOM: once a view has been inserted into the DOM it is in - the inDOM state. A view spends the vast majority of its - existence in this state. - * destroyed: once a view has been destroyed (using the destroy - method), it is in this state. No further actions can be invoked - on a destroyed view. - */ - - // in the destroyed state, everything is illegal - - // before rendering has begun, all legal manipulations are noops. - - // inside the buffer, legal manipulations are done on the buffer - - // once the view has been inserted into the DOM, legal manipulations - // are done on the DOM element. - - View.reopenClass({ - /** - Global views hash - @property views - @static - @type Object - @private - */ - views: {}, - - // If someone overrides the child views computed property when - // defining their class, we want to be able to process the user's - // supplied childViews and then restore the original computed property - // at view initialization time. This happens in Ember.ContainerView's init - // method. - childViewsProperty: _emberViewsMixinsView_child_views_support.childViewsProperty - }); - - function viewDeprecationMessage() { - _emberMetalDebug.deprecate('Ember.View is deprecated. Consult the Deprecations Guide for a migration strategy.', !!_emberMetalCore.default.ENV._ENABLE_LEGACY_VIEW_SUPPORT, { - url: 'http://emberjs.com/deprecations/v1.x/#toc_ember-view', - id: 'ember-views.view-deprecated', - until: '2.4.0' - }); - } - - var DeprecatedView = View.extend({ - init: function () { - viewDeprecationMessage(); - this._super.apply(this, arguments); - } - }); - - DeprecatedView.reopen = function () { - viewDeprecationMessage(); - View.reopen.apply(View, arguments); - return this; - }; - - exports.default = View; - exports.ViewContextSupport = _emberViewsMixinsView_context_support.default; - exports.ViewChildViewsSupport = _emberViewsMixinsView_child_views_support.default; - exports.ViewStateSupport = _emberViewsMixinsView_state_support.default; - exports.TemplateRenderingSupport = _emberViewsMixinsTemplate_rendering_support.default; - exports.ClassNamesSupport = _emberViewsMixinsClass_names_support.default; - exports.DeprecatedView = DeprecatedView; -}); -// for the side effect of extending Ember.run.queues -enifed('htmlbars-runtime/expression-visitor', ['exports'], function (exports) { - /** - # Expression Nodes: - - These nodes are not directly responsible for any part of the DOM, but are - eventually passed to a Statement Node. - - * get - * subexpr - * concat - */ - - 'use strict'; - - exports.acceptParams = acceptParams; - exports.acceptHash = acceptHash; - - function acceptParams(nodes, env, scope) { - var array = []; - - for (var i = 0, l = nodes.length; i < l; i++) { - array.push(acceptExpression(nodes[i], env, scope).value); - } - - return array; - } - - function acceptHash(pairs, env, scope) { - var object = {}; - - for (var i = 0, l = pairs.length; i < l; i += 2) { - var key = pairs[i]; - var value = pairs[i + 1]; - object[key] = acceptExpression(value, env, scope).value; - } - - return object; - } - - function acceptExpression(node, env, scope) { - var ret = { value: null }; - - // Primitive literals are unambiguously non-array representations of - // themselves. - if (typeof node !== 'object' || node === null) { - ret.value = node; - } else { - ret.value = evaluateNode(node, env, scope); - } - - return ret; - } - - function evaluateNode(node, env, scope) { - switch (node[0]) { - // can be used by manualElement - case 'value': - return node[1]; - case 'get': - return evaluateGet(node, env, scope); - case 'subexpr': - return evaluateSubexpr(node, env, scope); - case 'concat': - return evaluateConcat(node, env, scope); - } - } - - function evaluateGet(node, env, scope) { - var path = node[1]; - - return env.hooks.get(env, scope, path); - } - - function evaluateSubexpr(node, env, scope) { - var path = node[1]; - var rawParams = node[2]; - var rawHash = node[3]; - - var params = acceptParams(rawParams, env, scope); - var hash = acceptHash(rawHash, env, scope); - - return env.hooks.subexpr(env, scope, path, params, hash); - } - - function evaluateConcat(node, env, scope) { - var rawParts = node[1]; - - var parts = acceptParams(rawParts, env, scope); - - return env.hooks.concat(env, parts); - } -}); -enifed("htmlbars-runtime/hooks", ["exports", "htmlbars-runtime/render", "morph-range/morph-list", "htmlbars-util/object-utils", "htmlbars-util/morph-utils", "htmlbars-util/template-utils"], function (exports, _htmlbarsRuntimeRender, _morphRangeMorphList, _htmlbarsUtilObjectUtils, _htmlbarsUtilMorphUtils, _htmlbarsUtilTemplateUtils) { - "use strict"; - - exports.wrap = wrap; - exports.wrapForHelper = wrapForHelper; - exports.createScope = createScope; - exports.createFreshScope = createFreshScope; - exports.bindShadowScope = bindShadowScope; - exports.createChildScope = createChildScope; - exports.bindSelf = bindSelf; - exports.updateSelf = updateSelf; - exports.bindLocal = bindLocal; - exports.updateLocal = updateLocal; - exports.bindBlock = bindBlock; - exports.block = block; - exports.continueBlock = continueBlock; - exports.hostBlock = hostBlock; - exports.handleRedirect = handleRedirect; - exports.handleKeyword = handleKeyword; - exports.linkRenderNode = linkRenderNode; - exports.inline = inline; - exports.keyword = keyword; - exports.invokeHelper = invokeHelper; - exports.classify = classify; - exports.partial = partial; - exports.range = range; - exports.element = element; - exports.attribute = attribute; - exports.subexpr = subexpr; - exports.get = get; - exports.getRoot = getRoot; - exports.getBlock = getBlock; - exports.getChild = getChild; - exports.getValue = getValue; - exports.getCellOrValue = getCellOrValue; - exports.component = component; - exports.concat = concat; - exports.hasHelper = hasHelper; - exports.lookupHelper = lookupHelper; - exports.bindScope = bindScope; - exports.updateScope = updateScope; - - /** - HTMLBars delegates the runtime behavior of a template to - hooks provided by the host environment. These hooks explain - the lexical environment of a Handlebars template, the internal - representation of references, and the interaction between an - HTMLBars template and the DOM it is managing. - - While HTMLBars host hooks have access to all of this internal - machinery, templates and helpers have access to the abstraction - provided by the host hooks. - - ## The Lexical Environment - - The default lexical environment of an HTMLBars template includes: - - * Any local variables, provided by *block arguments* - * The current value of `self` - - ## Simple Nesting - - Let's look at a simple template with a nested block: - - ```hbs - {{title}} - - {{#if author}} - {{author}} - {{/if}} - ``` - - In this case, the lexical environment at the top-level of the - template does not change inside of the `if` block. This is - achieved via an implementation of `if` that looks like this: - - ```js - registerHelper('if', function(params) { - if (!!params[0]) { - return this.yield(); - } - }); - ``` - - A call to `this.yield` invokes the child template using the - current lexical environment. - - ## Block Arguments - - It is possible for nested blocks to introduce new local - variables: - - ```hbs - {{#count-calls as |i|}} - {{title}} - Called {{i}} times - {{/count}} - ``` - - In this example, the child block inherits its surrounding - lexical environment, but augments it with a single new - variable binding. - - The implementation of `count-calls` supplies the value of - `i`, but does not otherwise alter the environment: - - ```js - var count = 0; - registerHelper('count-calls', function() { - return this.yield([ ++count ]); - }); - ``` - */ - - function wrap(template) { - if (template === null) { - return null; - } - - return { - meta: template.meta, - arity: template.arity, - raw: template, - render: function (self, env, options, blockArguments) { - var scope = env.hooks.createFreshScope(); - - var contextualElement = options && options.contextualElement; - var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(null, self, blockArguments, contextualElement); - - return _htmlbarsRuntimeRender.default(template, env, scope, renderOptions); - } - }; - } - - function wrapForHelper(template, env, scope, morph, renderState, visitor) { - if (!template) { - return {}; - } - - var yieldArgs = yieldTemplate(template, env, scope, morph, renderState, visitor); - - return { - meta: template.meta, - arity: template.arity, - 'yield': yieldArgs, // quoted since it's a reserved word, see issue #420 - yieldItem: yieldItem(template, env, scope, morph, renderState, visitor), - raw: template, - - render: function (self, blockArguments) { - yieldArgs(blockArguments, self); - } - }; - } - - // Called by a user-land helper to render a template. - function yieldTemplate(template, env, parentScope, morph, renderState, visitor) { - return function (blockArguments, self) { - // Render state is used to track the progress of the helper (since it - // may call into us multiple times). As the user-land helper calls - // into library code, we track what needs to be cleaned up after the - // helper has returned. - // - // Here, we remember that a template has been yielded and so we do not - // need to remove the previous template. (If no template is yielded - // this render by the helper, we assume nothing should be shown and - // remove any previous rendered templates.) - renderState.morphToClear = null; - - // In this conditional is true, it means that on the previous rendering pass - // the helper yielded multiple items via `yieldItem()`, but this time they - // are yielding a single template. In that case, we mark the morph list for - // cleanup so it is removed from the DOM. - if (morph.morphList) { - _htmlbarsUtilTemplateUtils.clearMorphList(morph.morphList, morph, env); - renderState.morphListToClear = null; - } - - var scope = parentScope; - - if (morph.lastYielded && isStableTemplate(template, morph.lastYielded)) { - return morph.lastResult.revalidateWith(env, undefined, self, blockArguments, visitor); - } - - // Check to make sure that we actually **need** a new scope, and can't - // share the parent scope. Note that we need to move this check into - // a host hook, because the host's notion of scope may require a new - // scope in more cases than the ones we can determine statically. - if (self !== undefined || parentScope === null || template.arity) { - scope = env.hooks.createChildScope(parentScope); - } - - morph.lastYielded = { self: self, template: template, shadowTemplate: null }; - - // Render the template that was selected by the helper - var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(morph, self, blockArguments); - _htmlbarsRuntimeRender.default(template, env, scope, renderOptions); - }; - } - - function yieldItem(template, env, parentScope, morph, renderState, visitor) { - // Initialize state that tracks multiple items being - // yielded in. - var currentMorph = null; - - // Candidate morphs for deletion. - var candidates = {}; - - // Reuse existing MorphList if this is not a first-time - // render. - var morphList = morph.morphList; - if (morphList) { - currentMorph = morphList.firstChildMorph; - } - - // Advances the currentMorph pointer to the morph in the previously-rendered - // list that matches the yielded key. While doing so, it marks any morphs - // that it advances past as candidates for deletion. Assuming those morphs - // are not yielded in later, they will be removed in the prune step during - // cleanup. - // Note that this helper function assumes that the morph being seeked to is - // guaranteed to exist in the previous MorphList; if this is called and the - // morph does not exist, it will result in an infinite loop - function advanceToKey(key) { - var seek = currentMorph; - - while (seek.key !== key) { - candidates[seek.key] = seek; - seek = seek.nextMorph; - } - - currentMorph = seek.nextMorph; - return seek; - } - - return function (_key, blockArguments, self) { - if (typeof _key !== 'string') { - throw new Error("You must provide a string key when calling `yieldItem`; you provided " + _key); - } - - // At least one item has been yielded, so we do not wholesale - // clear the last MorphList but instead apply a prune operation. - renderState.morphListToClear = null; - morph.lastYielded = null; - - var morphList, morphMap; - - if (!morph.morphList) { - morph.morphList = new _morphRangeMorphList.default(); - morph.morphMap = {}; - morph.setMorphList(morph.morphList); - } - - morphList = morph.morphList; - morphMap = morph.morphMap; - - // A map of morphs that have been yielded in on this - // rendering pass. Any morphs that do not make it into - // this list will be pruned from the MorphList during the cleanup - // process. - var handledMorphs = renderState.handledMorphs; - var key = undefined; - - if (_key in handledMorphs) { - // In this branch we are dealing with a duplicate key. The strategy - // is to take the original key and append a counter to it that is - // incremented every time the key is reused. In order to greatly - // reduce the chance of colliding with another valid key we also add - // an extra string "--z8mS2hvDW0A--" to the new key. - var collisions = renderState.collisions; - if (collisions === undefined) { - collisions = renderState.collisions = {}; - } - var count = collisions[_key] | 0; - collisions[_key] = ++count; - - key = _key + '--z8mS2hvDW0A--' + count; - } else { - key = _key; - } - - if (currentMorph && currentMorph.key === key) { - yieldTemplate(template, env, parentScope, currentMorph, renderState, visitor)(blockArguments, self); - currentMorph = currentMorph.nextMorph; - handledMorphs[key] = currentMorph; - } else if (morphMap[key] !== undefined) { - var foundMorph = morphMap[key]; - - if (key in candidates) { - // If we already saw this morph, move it forward to this position - morphList.insertBeforeMorph(foundMorph, currentMorph); - } else { - // Otherwise, move the pointer forward to the existing morph for this key - advanceToKey(key); - } - - handledMorphs[foundMorph.key] = foundMorph; - yieldTemplate(template, env, parentScope, foundMorph, renderState, visitor)(blockArguments, self); - } else { - var childMorph = _htmlbarsRuntimeRender.createChildMorph(env.dom, morph); - childMorph.key = key; - morphMap[key] = handledMorphs[key] = childMorph; - morphList.insertBeforeMorph(childMorph, currentMorph); - yieldTemplate(template, env, parentScope, childMorph, renderState, visitor)(blockArguments, self); - } - - renderState.morphListToPrune = morphList; - morph.childNodes = null; - }; - } - - function isStableTemplate(template, lastYielded) { - return !lastYielded.shadowTemplate && template === lastYielded.template; - } - function optionsFor(template, inverse, env, scope, morph, visitor) { - // If there was a template yielded last time, set morphToClear so it will be cleared - // if no template is yielded on this render. - var morphToClear = morph.lastResult ? morph : null; - var renderState = new _htmlbarsUtilTemplateUtils.RenderState(morphToClear, morph.morphList || null); - - return { - templates: { - template: wrapForHelper(template, env, scope, morph, renderState, visitor), - inverse: wrapForHelper(inverse, env, scope, morph, renderState, visitor) - }, - renderState: renderState - }; - } - - function thisFor(options) { - return { - arity: options.template.arity, - 'yield': options.template.yield, // quoted since it's a reserved word, see issue #420 - yieldItem: options.template.yieldItem, - yieldIn: options.template.yieldIn - }; - } - - /** - Host Hook: createScope - - @param {Scope?} parentScope - @return Scope - - Corresponds to entering a new HTMLBars block. - - This hook is invoked when a block is entered with - a new `self` or additional local variables. - - When invoked for a top-level template, the - `parentScope` is `null`, and this hook should return - a fresh Scope. - - When invoked for a child template, the `parentScope` - is the scope for the parent environment. - - Note that the `Scope` is an opaque value that is - passed to other host hooks. For example, the `get` - hook uses the scope to retrieve a value for a given - scope and variable name. - */ - - function createScope(env, parentScope) { - if (parentScope) { - return env.hooks.createChildScope(parentScope); - } else { - return env.hooks.createFreshScope(); - } - } - - function createFreshScope() { - // because `in` checks have unpredictable performance, keep a - // separate dictionary to track whether a local was bound. - // See `bindLocal` for more information. - return { self: null, blocks: {}, locals: {}, localPresent: {} }; - } - - /** - Host Hook: bindShadowScope - - @param {Scope?} parentScope - @return Scope - - Corresponds to rendering a new template into an existing - render tree, but with a new top-level lexical scope. This - template is called the "shadow root". - - If a shadow template invokes `{{yield}}`, it will render - the block provided to the shadow root in the original - lexical scope. - - ```hbs - {{!-- post template --}} - {{props.title}} - {{yield}} - - {{!-- blog template --}} - {{#post title="Hello world"}} - by {{byline}} - This is my first post - {{/post}} - - {{#post title="Goodbye world"}} - by {{byline}} - This is my last post - {{/post}} - ``` - - ```js - helpers.post = function(params, hash, options) { - options.template.yieldIn(postTemplate, { props: hash }); - }; - - blog.render({ byline: "Yehuda Katz" }); - ``` - - Produces: - - ```html - Hello world - by Yehuda Katz - This is my first post - - Goodbye world - by Yehuda Katz - This is my last post - ``` - - In short, `yieldIn` creates a new top-level scope for the - provided template and renders it, making the original block - available to `{{yield}}` in that template. - */ - - function bindShadowScope(env /*, parentScope, shadowScope */) { - return env.hooks.createFreshScope(); - } - - function createChildScope(parent) { - var scope = Object.create(parent); - scope.locals = Object.create(parent.locals); - scope.localPresent = Object.create(parent.localPresent); - scope.blocks = Object.create(parent.blocks); - return scope; - } - - /** - Host Hook: bindSelf - - @param {Scope} scope - @param {any} self - - Corresponds to entering a template. - - This hook is invoked when the `self` value for a scope is ready to be bound. - - The host must ensure that child scopes reflect the change to the `self` in - future calls to the `get` hook. - */ - - function bindSelf(env, scope, self) { - scope.self = self; - } - - function updateSelf(env, scope, self) { - env.hooks.bindSelf(env, scope, self); - } - - /** - Host Hook: bindLocal - - @param {Environment} env - @param {Scope} scope - @param {String} name - @param {any} value - - Corresponds to entering a template with block arguments. - - This hook is invoked when a local variable for a scope has been provided. - - The host must ensure that child scopes reflect the change in future calls - to the `get` hook. - */ - - function bindLocal(env, scope, name, value) { - scope.localPresent[name] = true; - scope.locals[name] = value; - } - - function updateLocal(env, scope, name, value) { - env.hooks.bindLocal(env, scope, name, value); - } - - /** - Host Hook: bindBlock - - @param {Environment} env - @param {Scope} scope - @param {Function} block - - Corresponds to entering a shadow template that was invoked by a block helper with - `yieldIn`. - - This hook is invoked with an opaque block that will be passed along - to the shadow template, and inserted into the shadow template when - `{{yield}}` is used. Optionally provide a non-default block name - that can be targeted by `{{yield to=blockName}}`. - */ - - function bindBlock(env, scope, block) { - var name = arguments.length <= 3 || arguments[3] === undefined ? 'default' : arguments[3]; - - scope.blocks[name] = block; - } - - /** - Host Hook: block - - @param {RenderNode} renderNode - @param {Environment} env - @param {Scope} scope - @param {String} path - @param {Array} params - @param {Object} hash - @param {Block} block - @param {Block} elseBlock - - Corresponds to: - - ```hbs - {{#helper param1 param2 key1=val1 key2=val2}} - {{!-- child template --}} - {{/helper}} - ``` - - This host hook is a workhorse of the system. It is invoked - whenever a block is encountered, and is responsible for - resolving the helper to call, and then invoke it. - - The helper should be invoked with: - - - `{Array} params`: the parameters passed to the helper - in the template. - - `{Object} hash`: an object containing the keys and values passed - in the hash position in the template. - - The values in `params` and `hash` will already be resolved - through a previous call to the `get` host hook. - - The helper should be invoked with a `this` value that is - an object with one field: - - `{Function} yield`: when invoked, this function executes the - block with the current scope. It takes an optional array of - block parameters. If block parameters are supplied, HTMLBars - will invoke the `bindLocal` host hook to bind the supplied - values to the block arguments provided by the template. - - In general, the default implementation of `block` should work - for most host environments. It delegates to other host hooks - where appropriate, and properly invokes the helper with the - appropriate arguments. - */ - - function block(morph, env, scope, path, params, hash, template, inverse, visitor) { - if (handleRedirect(morph, env, scope, path, params, hash, template, inverse, visitor)) { - return; - } - - continueBlock(morph, env, scope, path, params, hash, template, inverse, visitor); - } - - function continueBlock(morph, env, scope, path, params, hash, template, inverse, visitor) { - hostBlock(morph, env, scope, template, inverse, null, visitor, function (options) { - var helper = env.hooks.lookupHelper(env, scope, path); - return env.hooks.invokeHelper(morph, env, scope, visitor, params, hash, helper, options.templates, thisFor(options.templates)); - }); - } - - function hostBlock(morph, env, scope, template, inverse, shadowOptions, visitor, callback) { - var options = optionsFor(template, inverse, env, scope, morph, visitor); - _htmlbarsUtilTemplateUtils.renderAndCleanup(morph, env, options, shadowOptions, callback); - } - - function handleRedirect(morph, env, scope, path, params, hash, template, inverse, visitor) { - if (!path) { - return false; - } - - var redirect = env.hooks.classify(env, scope, path); - if (redirect) { - switch (redirect) { - case 'component': - env.hooks.component(morph, env, scope, path, params, hash, { default: template, inverse: inverse }, visitor);break; - case 'inline': - env.hooks.inline(morph, env, scope, path, params, hash, visitor);break; - case 'block': - env.hooks.block(morph, env, scope, path, params, hash, template, inverse, visitor);break; - default: - throw new Error("Internal HTMLBars redirection to " + redirect + " not supported"); - } - return true; - } - - if (handleKeyword(path, morph, env, scope, params, hash, template, inverse, visitor)) { - return true; - } - - return false; - } - - function handleKeyword(path, morph, env, scope, params, hash, template, inverse, visitor) { - var keyword = env.hooks.keywords[path]; - if (!keyword) { - return false; - } - - if (typeof keyword === 'function') { - return keyword(morph, env, scope, params, hash, template, inverse, visitor); - } - - if (keyword.willRender) { - keyword.willRender(morph, env); - } - - var lastState, newState; - if (keyword.setupState) { - lastState = _htmlbarsUtilObjectUtils.shallowCopy(morph.getState()); - newState = morph.setState(keyword.setupState(lastState, env, scope, params, hash)); - } - - if (keyword.childEnv) { - // Build the child environment... - env = keyword.childEnv(morph.getState(), env); - - // ..then save off the child env builder on the render node. If the render - // node tree is re-rendered and this node is not dirty, the child env - // builder will still be invoked so that child dirty render nodes still get - // the correct child env. - morph.buildChildEnv = keyword.childEnv; - } - - var firstTime = !morph.rendered; - - if (keyword.isEmpty) { - var isEmpty = keyword.isEmpty(morph.getState(), env, scope, params, hash); - - if (isEmpty) { - if (!firstTime) { - _htmlbarsUtilTemplateUtils.clearMorph(morph, env, false); - } - return true; - } - } - - if (firstTime) { - if (keyword.render) { - keyword.render(morph, env, scope, params, hash, template, inverse, visitor); - } - morph.rendered = true; - return true; - } - - var isStable; - if (keyword.isStable) { - isStable = keyword.isStable(lastState, newState); - } else { - isStable = stableState(lastState, newState); - } - - if (isStable) { - if (keyword.rerender) { - var newEnv = keyword.rerender(morph, env, scope, params, hash, template, inverse, visitor); - env = newEnv || env; - } - _htmlbarsUtilMorphUtils.validateChildMorphs(env, morph, visitor); - return true; - } else { - _htmlbarsUtilTemplateUtils.clearMorph(morph, env, false); - } - - // If the node is unstable, re-render from scratch - if (keyword.render) { - keyword.render(morph, env, scope, params, hash, template, inverse, visitor); - morph.rendered = true; - return true; - } - } - - function stableState(oldState, newState) { - if (_htmlbarsUtilObjectUtils.keyLength(oldState) !== _htmlbarsUtilObjectUtils.keyLength(newState)) { - return false; - } - - for (var prop in oldState) { - if (oldState[prop] !== newState[prop]) { - return false; - } - } - - return true; - } - - function linkRenderNode() /* morph, env, scope, params, hash */{ - return; - } - - /** - Host Hook: inline - - @param {RenderNode} renderNode - @param {Environment} env - @param {Scope} scope - @param {String} path - @param {Array} params - @param {Hash} hash - - Corresponds to: - - ```hbs - {{helper param1 param2 key1=val1 key2=val2}} - ``` - - This host hook is similar to the `block` host hook, but it - invokes helpers that do not supply an attached block. - - Like the `block` hook, the helper should be invoked with: - - - `{Array} params`: the parameters passed to the helper - in the template. - - `{Object} hash`: an object containing the keys and values passed - in the hash position in the template. - - The values in `params` and `hash` will already be resolved - through a previous call to the `get` host hook. - - In general, the default implementation of `inline` should work - for most host environments. It delegates to other host hooks - where appropriate, and properly invokes the helper with the - appropriate arguments. - - The default implementation of `inline` also makes `partial` - a keyword. Instead of invoking a helper named `partial`, - it invokes the `partial` host hook. - */ - - function inline(morph, env, scope, path, params, hash, visitor) { - if (handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) { - return; - } - - var value = undefined, - hasValue = undefined; - if (morph.linkedResult) { - value = env.hooks.getValue(morph.linkedResult); - hasValue = true; - } else { - var options = optionsFor(null, null, env, scope, morph); - - var helper = env.hooks.lookupHelper(env, scope, path); - var result = env.hooks.invokeHelper(morph, env, scope, visitor, params, hash, helper, options.templates, thisFor(options.templates)); - - if (result && result.link) { - morph.linkedResult = result.value; - _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, '@content-helper', [morph.linkedResult], null); - } - - if (result && 'value' in result) { - value = env.hooks.getValue(result.value); - hasValue = true; - } - } - - if (hasValue) { - if (morph.lastValue !== value) { - morph.setContent(value); - } - morph.lastValue = value; - } - } - - function keyword(path, morph, env, scope, params, hash, template, inverse, visitor) { - handleKeyword(path, morph, env, scope, params, hash, template, inverse, visitor); - } - - function invokeHelper(morph, env, scope, visitor, _params, _hash, helper, templates, context) { - var params = normalizeArray(env, _params); - var hash = normalizeObject(env, _hash); - return { value: helper.call(context, params, hash, templates) }; - } - - function normalizeArray(env, array) { - var out = new Array(array.length); - - for (var i = 0, l = array.length; i < l; i++) { - out[i] = env.hooks.getCellOrValue(array[i]); - } - - return out; - } - - function normalizeObject(env, object) { - var out = {}; - - for (var prop in object) { - out[prop] = env.hooks.getCellOrValue(object[prop]); - } - - return out; - } - - function classify() /* env, scope, path */{ - return null; - } - - var keywords = { - partial: function (morph, env, scope, params) { - var value = env.hooks.partial(morph, env, scope, params[0]); - morph.setContent(value); - return true; - }, - - // quoted since it's a reserved word, see issue #420 - 'yield': function (morph, env, scope, params, hash, template, inverse, visitor) { - // the current scope is provided purely for the creation of shadow - // scopes; it should not be provided to user code. - - var to = env.hooks.getValue(hash.to) || 'default'; - var block = env.hooks.getBlock(scope, to); - - if (block) { - block.invoke(env, params, hash.self, morph, scope, visitor); - } - return true; - }, - - hasBlock: function (morph, env, scope, params) { - var name = env.hooks.getValue(params[0]) || 'default'; - return !!env.hooks.getBlock(scope, name); - }, - - hasBlockParams: function (morph, env, scope, params) { - var name = env.hooks.getValue(params[0]) || 'default'; - var block = env.hooks.getBlock(scope, name); - return !!(block && block.arity); - } - - }; - - exports.keywords = keywords; - /** - Host Hook: partial - - @param {RenderNode} renderNode - @param {Environment} env - @param {Scope} scope - @param {String} path - - Corresponds to: - - ```hbs - {{partial "location"}} - ``` - - This host hook is invoked by the default implementation of - the `inline` hook. This makes `partial` a keyword in an - HTMLBars environment using the default `inline` host hook. - - It is implemented as a host hook so that it can retrieve - the named partial out of the `Environment`. Helpers, in - contrast, only have access to the values passed in to them, - and not to the ambient lexical environment. - - The host hook should invoke the referenced partial with - the ambient `self`. - */ - - function partial(renderNode, env, scope, path) { - var template = env.partials[path]; - return template.render(scope.self, env, {}).fragment; - } - - /** - Host hook: range - - @param {RenderNode} renderNode - @param {Environment} env - @param {Scope} scope - @param {any} value - - Corresponds to: - - ```hbs - {{content}} - {{{unescaped}}} - ``` - - This hook is responsible for updating a render node - that represents a range of content with a value. - */ - - function range(morph, env, scope, path, value, visitor) { - if (handleRedirect(morph, env, scope, path, [], {}, null, null, visitor)) { - return; - } - - value = env.hooks.getValue(value); - - if (morph.lastValue !== value) { - morph.setContent(value); - } - - morph.lastValue = value; - } - - /** - Host hook: element - - @param {RenderNode} renderNode - @param {Environment} env - @param {Scope} scope - @param {String} path - @param {Array} params - @param {Hash} hash - - Corresponds to: - - ```hbs - - ``` - - This hook is responsible for invoking a helper that - modifies an element. - - Its purpose is largely legacy support for awkward - idioms that became common when using the string-based - Handlebars engine. - - Most of the uses of the `element` hook are expected - to be superseded by component syntax and the - `attribute` hook. - */ - - function element(morph, env, scope, path, params, hash, visitor) { - if (handleRedirect(morph, env, scope, path, params, hash, null, null, visitor)) { - return; - } - - var helper = env.hooks.lookupHelper(env, scope, path); - if (helper) { - env.hooks.invokeHelper(null, env, scope, null, params, hash, helper, { element: morph.element }); - } - } - - /** - Host hook: attribute - - @param {RenderNode} renderNode - @param {Environment} env - @param {String} name - @param {any} value - - Corresponds to: - - ```hbs - - ``` - - This hook is responsible for updating a render node - that represents an element's attribute with a value. - - It receives the name of the attribute as well as an - already-resolved value, and should update the render - node with the value if appropriate. - */ - - function attribute(morph, env, scope, name, value) { - value = env.hooks.getValue(value); - - if (morph.lastValue !== value) { - morph.setContent(value); - } - - morph.lastValue = value; - } - - function subexpr(env, scope, helperName, params, hash) { - var helper = env.hooks.lookupHelper(env, scope, helperName); - var result = env.hooks.invokeHelper(null, env, scope, null, params, hash, helper, {}); - if (result && 'value' in result) { - return env.hooks.getValue(result.value); - } - } - - /** - Host Hook: get - - @param {Environment} env - @param {Scope} scope - @param {String} path - - Corresponds to: - - ```hbs - {{foo.bar}} - ^ - - {{helper foo.bar key=value}} - ^ ^ - ``` - - This hook is the "leaf" hook of the system. It is used to - resolve a path relative to the current scope. - */ - - function get(env, scope, path) { - if (path === '') { - return scope.self; - } - - var keys = path.split('.'); - var value = env.hooks.getRoot(scope, keys[0])[0]; - - for (var i = 1; i < keys.length; i++) { - if (value) { - value = env.hooks.getChild(value, keys[i]); - } else { - break; - } - } - - return value; - } - - function getRoot(scope, key) { - if (scope.localPresent[key]) { - return [scope.locals[key]]; - } else if (scope.self) { - return [scope.self[key]]; - } else { - return [undefined]; - } - } - - function getBlock(scope, key) { - return scope.blocks[key]; - } - - function getChild(value, key) { - return value[key]; - } - - function getValue(reference) { - return reference; - } - - function getCellOrValue(reference) { - return reference; - } - - function component(morph, env, scope, tagName, params, attrs, templates, visitor) { - if (env.hooks.hasHelper(env, scope, tagName)) { - return env.hooks.block(morph, env, scope, tagName, params, attrs, templates.default, templates.inverse, visitor); - } - - componentFallback(morph, env, scope, tagName, attrs, templates.default); - } - - function concat(env, params) { - var value = ""; - for (var i = 0, l = params.length; i < l; i++) { - value += env.hooks.getValue(params[i]); - } - return value; - } - - function componentFallback(morph, env, scope, tagName, attrs, template) { - var element = env.dom.createElement(tagName); - for (var name in attrs) { - element.setAttribute(name, env.hooks.getValue(attrs[name])); - } - var fragment = _htmlbarsRuntimeRender.default(template, env, scope, {}).fragment; - element.appendChild(fragment); - morph.setNode(element); - } - - function hasHelper(env, scope, helperName) { - return env.helpers[helperName] !== undefined; - } - - function lookupHelper(env, scope, helperName) { - return env.helpers[helperName]; - } - - function bindScope() /* env, scope */{ - // this function is used to handle host-specified extensions to scope - // other than `self`, `locals` and `block`. - } - - function updateScope(env, scope) { - env.hooks.bindScope(env, scope); - } - - exports.default = { - // fundamental hooks that you will likely want to override - bindLocal: bindLocal, - bindSelf: bindSelf, - bindScope: bindScope, - classify: classify, - component: component, - concat: concat, - createFreshScope: createFreshScope, - getChild: getChild, - getRoot: getRoot, - getBlock: getBlock, - getValue: getValue, - getCellOrValue: getCellOrValue, - keywords: keywords, - linkRenderNode: linkRenderNode, - partial: partial, - subexpr: subexpr, - - // fundamental hooks with good default behavior - bindBlock: bindBlock, - bindShadowScope: bindShadowScope, - updateLocal: updateLocal, - updateSelf: updateSelf, - updateScope: updateScope, - createChildScope: createChildScope, - hasHelper: hasHelper, - lookupHelper: lookupHelper, - invokeHelper: invokeHelper, - cleanupRenderNode: null, - destroyRenderNode: null, - willCleanupTree: null, - didCleanupTree: null, - willRenderNode: null, - didRenderNode: null, - - // derived hooks - attribute: attribute, - block: block, - createScope: createScope, - element: element, - get: get, - inline: inline, - range: range, - keyword: keyword - }; -}); -enifed("htmlbars-runtime/morph", ["exports", "morph-range"], function (exports, _morphRange) { - "use strict"; - - var guid = 1; - - function HTMLBarsMorph(domHelper, contextualElement) { - this.super$constructor(domHelper, contextualElement); - - this._state = undefined; - this.ownerNode = null; - this.isDirty = false; - this.isSubtreeDirty = false; - this.lastYielded = null; - this.lastResult = null; - this.lastValue = null; - this.buildChildEnv = null; - this.morphList = null; - this.morphMap = null; - this.key = null; - this.linkedParams = null; - this.linkedResult = null; - this.childNodes = null; - this.rendered = false; - this.guid = "range" + guid++; - this.seen = false; - } - - HTMLBarsMorph.empty = function (domHelper, contextualElement) { - var morph = new HTMLBarsMorph(domHelper, contextualElement); - morph.clear(); - return morph; - }; - - HTMLBarsMorph.create = function (domHelper, contextualElement, node) { - var morph = new HTMLBarsMorph(domHelper, contextualElement); - morph.setNode(node); - return morph; - }; - - HTMLBarsMorph.attach = function (domHelper, contextualElement, firstNode, lastNode) { - var morph = new HTMLBarsMorph(domHelper, contextualElement); - morph.setRange(firstNode, lastNode); - return morph; - }; - - var prototype = HTMLBarsMorph.prototype = Object.create(_morphRange.default.prototype); - prototype.constructor = HTMLBarsMorph; - prototype.super$constructor = _morphRange.default; - - prototype.getState = function () { - if (!this._state) { - this._state = {}; - } - - return this._state; - }; - - prototype.setState = function (newState) { - /*jshint -W093 */ - - return this._state = newState; - }; - - exports.default = HTMLBarsMorph; -}); -enifed("htmlbars-runtime/node-visitor", ["exports", "htmlbars-util/morph-utils", "htmlbars-runtime/expression-visitor"], function (exports, _htmlbarsUtilMorphUtils, _htmlbarsRuntimeExpressionVisitor) { - "use strict"; - - /** - Node classification: - - # Primary Statement Nodes: - - These nodes are responsible for a render node that represents a morph-range. - - * block - * inline - * content - * element - * component - - # Leaf Statement Nodes: - - This node is responsible for a render node that represents a morph-attr. - - * attribute - */ - - function linkParamsAndHash(env, scope, morph, path, params, hash) { - if (morph.linkedParams) { - params = morph.linkedParams.params; - hash = morph.linkedParams.hash; - } else { - params = params && _htmlbarsRuntimeExpressionVisitor.acceptParams(params, env, scope); - hash = hash && _htmlbarsRuntimeExpressionVisitor.acceptHash(hash, env, scope); - } - - _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, path, params, hash); - return [params, hash]; - } - - var AlwaysDirtyVisitor = { - - block: function (node, morph, env, scope, template, visitor) { - var path = node[1]; - var params = node[2]; - var hash = node[3]; - var templateId = node[4]; - var inverseId = node[5]; - - var paramsAndHash = linkParamsAndHash(env, scope, morph, path, params, hash); - - morph.isDirty = morph.isSubtreeDirty = false; - env.hooks.block(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], templateId === null ? null : template.templates[templateId], inverseId === null ? null : template.templates[inverseId], visitor); - }, - - inline: function (node, morph, env, scope, visitor) { - var path = node[1]; - var params = node[2]; - var hash = node[3]; - - var paramsAndHash = linkParamsAndHash(env, scope, morph, path, params, hash); - - morph.isDirty = morph.isSubtreeDirty = false; - env.hooks.inline(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], visitor); - }, - - content: function (node, morph, env, scope, visitor) { - var path = node[1]; - - morph.isDirty = morph.isSubtreeDirty = false; - - if (isHelper(env, scope, path)) { - env.hooks.inline(morph, env, scope, path, [], {}, visitor); - if (morph.linkedResult) { - _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, '@content-helper', [morph.linkedResult], null); - } - return; - } - - var params = undefined; - if (morph.linkedParams) { - params = morph.linkedParams.params; - } else { - params = [env.hooks.get(env, scope, path)]; - } - - _htmlbarsUtilMorphUtils.linkParams(env, scope, morph, '@range', params, null); - env.hooks.range(morph, env, scope, path, params[0], visitor); - }, - - element: function (node, morph, env, scope, visitor) { - var path = node[1]; - var params = node[2]; - var hash = node[3]; - - var paramsAndHash = linkParamsAndHash(env, scope, morph, path, params, hash); - - morph.isDirty = morph.isSubtreeDirty = false; - env.hooks.element(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], visitor); - }, - - attribute: function (node, morph, env, scope) { - var name = node[1]; - var value = node[2]; - - var paramsAndHash = linkParamsAndHash(env, scope, morph, '@attribute', [value], null); - - morph.isDirty = morph.isSubtreeDirty = false; - env.hooks.attribute(morph, env, scope, name, paramsAndHash[0][0]); - }, - - component: function (node, morph, env, scope, template, visitor) { - var path = node[1]; - var attrs = node[2]; - var templateId = node[3]; - var inverseId = node[4]; - - var paramsAndHash = linkParamsAndHash(env, scope, morph, path, [], attrs); - var templates = { - default: template.templates[templateId], - inverse: template.templates[inverseId] - }; - - morph.isDirty = morph.isSubtreeDirty = false; - env.hooks.component(morph, env, scope, path, paramsAndHash[0], paramsAndHash[1], templates, visitor); - }, - - attributes: function (node, morph, env, scope, parentMorph, visitor) { - var template = node[1]; - - env.hooks.attributes(morph, env, scope, template, parentMorph, visitor); - } - - }; - - exports.AlwaysDirtyVisitor = AlwaysDirtyVisitor; - exports.default = { - block: function (node, morph, env, scope, template, visitor) { - dirtyCheck(env, morph, visitor, function (visitor) { - AlwaysDirtyVisitor.block(node, morph, env, scope, template, visitor); - }); - }, - - inline: function (node, morph, env, scope, visitor) { - dirtyCheck(env, morph, visitor, function (visitor) { - AlwaysDirtyVisitor.inline(node, morph, env, scope, visitor); - }); - }, - - content: function (node, morph, env, scope, visitor) { - dirtyCheck(env, morph, visitor, function (visitor) { - AlwaysDirtyVisitor.content(node, morph, env, scope, visitor); - }); - }, - - element: function (node, morph, env, scope, template, visitor) { - dirtyCheck(env, morph, visitor, function (visitor) { - AlwaysDirtyVisitor.element(node, morph, env, scope, template, visitor); - }); - }, - - attribute: function (node, morph, env, scope, template) { - dirtyCheck(env, morph, null, function () { - AlwaysDirtyVisitor.attribute(node, morph, env, scope, template); - }); - }, - - component: function (node, morph, env, scope, template, visitor) { - dirtyCheck(env, morph, visitor, function (visitor) { - AlwaysDirtyVisitor.component(node, morph, env, scope, template, visitor); - }); - }, - - attributes: function (node, morph, env, scope, parentMorph, visitor) { - AlwaysDirtyVisitor.attributes(node, morph, env, scope, parentMorph, visitor); - } - }; - - function dirtyCheck(_env, morph, visitor, callback) { - var isDirty = morph.isDirty; - var isSubtreeDirty = morph.isSubtreeDirty; - var env = _env; - - if (isSubtreeDirty) { - visitor = AlwaysDirtyVisitor; - } - - if (isDirty || isSubtreeDirty) { - callback(visitor); - } else { - if (morph.buildChildEnv) { - env = morph.buildChildEnv(morph.getState(), env); - } - _htmlbarsUtilMorphUtils.validateChildMorphs(env, morph, visitor); - } - } - - function isHelper(env, scope, path) { - return env.hooks.keywords[path] !== undefined || env.hooks.hasHelper(env, scope, path); - } -}); -enifed("htmlbars-runtime/render", ["exports", "htmlbars-util/morph-utils", "htmlbars-runtime/node-visitor", "htmlbars-runtime/morph", "htmlbars-util/template-utils", "htmlbars-util/void-tag-names"], function (exports, _htmlbarsUtilMorphUtils, _htmlbarsRuntimeNodeVisitor, _htmlbarsRuntimeMorph, _htmlbarsUtilTemplateUtils, _htmlbarsUtilVoidTagNames) { - "use strict"; - - exports.default = render; - exports.RenderOptions = RenderOptions; - exports.manualElement = manualElement; - exports.attachAttributes = attachAttributes; - exports.createChildMorph = createChildMorph; - exports.getCachedFragment = getCachedFragment; - - var svgNamespace = "http://www.w3.org/2000/svg"; - - function render(template, env, scope, options) { - var dom = env.dom; - var contextualElement; - - if (options) { - if (options.renderNode) { - contextualElement = options.renderNode.contextualElement; - } else if (options.contextualElement) { - contextualElement = options.contextualElement; - } - } - - dom.detectNamespace(contextualElement); - - var renderResult = RenderResult.build(env, scope, template, options, contextualElement); - renderResult.render(); - - return renderResult; - } - - function RenderOptions(renderNode, self, blockArguments, contextualElement) { - this.renderNode = renderNode || null; - this.self = self; - this.blockArguments = blockArguments || null; - this.contextualElement = contextualElement || null; - } - - function RenderResult(env, scope, options, rootNode, ownerNode, nodes, fragment, template, shouldSetContent) { - this.root = rootNode; - this.fragment = fragment; - - this.nodes = nodes; - this.template = template; - this.statements = template.statements.slice(); - this.env = env; - this.scope = scope; - this.shouldSetContent = shouldSetContent; - - if (options.self !== undefined) { - this.bindSelf(options.self); - } - if (options.blockArguments !== undefined) { - this.bindLocals(options.blockArguments); - } - - this.initializeNodes(ownerNode); - } - - RenderResult.build = function (env, scope, template, options, contextualElement) { - var dom = env.dom; - var fragment = getCachedFragment(template, env); - var nodes = template.buildRenderNodes(dom, fragment, contextualElement); - - var rootNode, ownerNode, shouldSetContent; - - if (options && options.renderNode) { - rootNode = options.renderNode; - ownerNode = rootNode.ownerNode; - shouldSetContent = true; - } else { - rootNode = dom.createMorph(null, fragment.firstChild, fragment.lastChild, contextualElement); - ownerNode = rootNode; - rootNode.ownerNode = ownerNode; - shouldSetContent = false; - } - - if (rootNode.childNodes) { - _htmlbarsUtilMorphUtils.visitChildren(rootNode.childNodes, function (node) { - _htmlbarsUtilTemplateUtils.clearMorph(node, env, true); - }); - } - - rootNode.childNodes = nodes; - return new RenderResult(env, scope, options, rootNode, ownerNode, nodes, fragment, template, shouldSetContent); - }; - - function manualElement(tagName, attributes, _isEmpty) { - var statements = []; - - for (var key in attributes) { - if (typeof attributes[key] === 'string') { - continue; - } - statements.push(["attribute", key, attributes[key]]); - } - - var isEmpty = _isEmpty || _htmlbarsUtilVoidTagNames.default[tagName]; - - if (!isEmpty) { - statements.push(['content', 'yield']); - } - - var template = { - arity: 0, - cachedFragment: null, - hasRendered: false, - buildFragment: function buildFragment(dom) { - var el0 = dom.createDocumentFragment(); - if (tagName === 'svg') { - dom.setNamespace(svgNamespace); - } - var el1 = dom.createElement(tagName); - - for (var key in attributes) { - if (typeof attributes[key] !== 'string') { - continue; - } - dom.setAttribute(el1, key, attributes[key]); - } - - if (!isEmpty) { - var el2 = dom.createComment(""); - dom.appendChild(el1, el2); - } - - dom.appendChild(el0, el1); - - return el0; - }, - buildRenderNodes: function buildRenderNodes(dom, fragment) { - var element = dom.childAt(fragment, [0]); - var morphs = []; - - for (var key in attributes) { - if (typeof attributes[key] === 'string') { - continue; - } - morphs.push(dom.createAttrMorph(element, key)); - } - - if (!isEmpty) { - morphs.push(dom.createMorphAt(element, 0, 0)); - } - - return morphs; - }, - statements: statements, - locals: [], - templates: [] - }; - - return template; - } - - function attachAttributes(attributes) { - var statements = []; - - for (var key in attributes) { - if (typeof attributes[key] === 'string') { - continue; - } - statements.push(["attribute", key, attributes[key]]); - } - - var template = { - arity: 0, - cachedFragment: null, - hasRendered: false, - buildFragment: function buildFragment(dom) { - var el0 = this.element; - if (el0.namespaceURI === "http://www.w3.org/2000/svg") { - dom.setNamespace(svgNamespace); - } - for (var key in attributes) { - if (typeof attributes[key] !== 'string') { - continue; - } - dom.setAttribute(el0, key, attributes[key]); - } - - return el0; - }, - buildRenderNodes: function buildRenderNodes(dom) { - var element = this.element; - var morphs = []; - - for (var key in attributes) { - if (typeof attributes[key] === 'string') { - continue; - } - morphs.push(dom.createAttrMorph(element, key)); - } - - return morphs; - }, - statements: statements, - locals: [], - templates: [], - element: null - }; - - return template; - } - - RenderResult.prototype.initializeNodes = function (ownerNode) { - var childNodes = this.root.childNodes; - - for (var i = 0, l = childNodes.length; i < l; i++) { - childNodes[i].ownerNode = ownerNode; - } - }; - - RenderResult.prototype.render = function () { - this.root.lastResult = this; - this.root.rendered = true; - this.populateNodes(_htmlbarsRuntimeNodeVisitor.AlwaysDirtyVisitor); - - if (this.shouldSetContent && this.root.setContent) { - this.root.setContent(this.fragment); - } - }; - - RenderResult.prototype.dirty = function () { - _htmlbarsUtilMorphUtils.visitChildren([this.root], function (node) { - node.isDirty = true; - }); - }; - - RenderResult.prototype.revalidate = function (env, self, blockArguments, scope) { - this.revalidateWith(env, scope, self, blockArguments, _htmlbarsRuntimeNodeVisitor.default); - }; - - RenderResult.prototype.rerender = function (env, self, blockArguments, scope) { - this.revalidateWith(env, scope, self, blockArguments, _htmlbarsRuntimeNodeVisitor.AlwaysDirtyVisitor); - }; - - RenderResult.prototype.revalidateWith = function (env, scope, self, blockArguments, visitor) { - if (env !== undefined) { - this.env = env; - } - if (scope !== undefined) { - this.scope = scope; - } - this.updateScope(); - - if (self !== undefined) { - this.updateSelf(self); - } - if (blockArguments !== undefined) { - this.updateLocals(blockArguments); - } - - this.populateNodes(visitor); - }; - - RenderResult.prototype.destroy = function () { - var rootNode = this.root; - _htmlbarsUtilTemplateUtils.clearMorph(rootNode, this.env, true); - }; - - RenderResult.prototype.populateNodes = function (visitor) { - var env = this.env; - var scope = this.scope; - var template = this.template; - var nodes = this.nodes; - var statements = this.statements; - var i, l; - - for (i = 0, l = statements.length; i < l; i++) { - var statement = statements[i]; - var morph = nodes[i]; - - if (env.hooks.willRenderNode) { - env.hooks.willRenderNode(morph, env, scope); - } - - switch (statement[0]) { - case 'block': - visitor.block(statement, morph, env, scope, template, visitor);break; - case 'inline': - visitor.inline(statement, morph, env, scope, visitor);break; - case 'content': - visitor.content(statement, morph, env, scope, visitor);break; - case 'element': - visitor.element(statement, morph, env, scope, template, visitor);break; - case 'attribute': - visitor.attribute(statement, morph, env, scope);break; - case 'component': - visitor.component(statement, morph, env, scope, template, visitor);break; - } - - if (env.hooks.didRenderNode) { - env.hooks.didRenderNode(morph, env, scope); - } - } - }; - - RenderResult.prototype.bindScope = function () { - this.env.hooks.bindScope(this.env, this.scope); - }; - - RenderResult.prototype.updateScope = function () { - this.env.hooks.updateScope(this.env, this.scope); - }; - - RenderResult.prototype.bindSelf = function (self) { - this.env.hooks.bindSelf(this.env, this.scope, self); - }; - - RenderResult.prototype.updateSelf = function (self) { - this.env.hooks.updateSelf(this.env, this.scope, self); - }; - - RenderResult.prototype.bindLocals = function (blockArguments) { - var localNames = this.template.locals; - - for (var i = 0, l = localNames.length; i < l; i++) { - this.env.hooks.bindLocal(this.env, this.scope, localNames[i], blockArguments[i]); - } - }; - - RenderResult.prototype.updateLocals = function (blockArguments) { - var localNames = this.template.locals; - - for (var i = 0, l = localNames.length; i < l; i++) { - this.env.hooks.updateLocal(this.env, this.scope, localNames[i], blockArguments[i]); - } - }; - - function initializeNode(node, owner) { - node.ownerNode = owner; - } - - function createChildMorph(dom, parentMorph, contextualElement) { - var morph = _htmlbarsRuntimeMorph.default.empty(dom, contextualElement || parentMorph.contextualElement); - initializeNode(morph, parentMorph.ownerNode); - return morph; - } - - function getCachedFragment(template, env) { - var dom = env.dom, - fragment; - if (env.useFragmentCache && dom.canClone) { - if (template.cachedFragment === null) { - fragment = template.buildFragment(dom); - if (template.hasRendered) { - template.cachedFragment = fragment; - } else { - template.hasRendered = true; - } - } - if (template.cachedFragment) { - fragment = dom.cloneNode(template.cachedFragment, true); - } - } else if (!fragment) { - fragment = template.buildFragment(dom); - } - - return fragment; - } -}); -enifed('htmlbars-runtime', ['exports', 'htmlbars-runtime/hooks', 'htmlbars-runtime/render', 'htmlbars-util/morph-utils', 'htmlbars-util/template-utils'], function (exports, _htmlbarsRuntimeHooks, _htmlbarsRuntimeRender, _htmlbarsUtilMorphUtils, _htmlbarsUtilTemplateUtils) { - 'use strict'; - - var internal = { - blockFor: _htmlbarsUtilTemplateUtils.blockFor, - manualElement: _htmlbarsRuntimeRender.manualElement, - hostBlock: _htmlbarsRuntimeHooks.hostBlock, - continueBlock: _htmlbarsRuntimeHooks.continueBlock, - hostYieldWithShadowTemplate: _htmlbarsRuntimeHooks.hostYieldWithShadowTemplate, - visitChildren: _htmlbarsUtilMorphUtils.visitChildren, - validateChildMorphs: _htmlbarsUtilMorphUtils.validateChildMorphs, - clearMorph: _htmlbarsUtilTemplateUtils.clearMorph - }; - - exports.hooks = _htmlbarsRuntimeHooks.default; - exports.render = _htmlbarsRuntimeRender.default; - exports.internal = internal; -}); -enifed('htmlbars-util/array-utils', ['exports'], function (exports) { - 'use strict'; - - exports.forEach = forEach; - exports.map = map; - - function forEach(array, callback, binding) { - var i, l; - if (binding === undefined) { - for (i = 0, l = array.length; i < l; i++) { - callback(array[i], i, array); - } - } else { - for (i = 0, l = array.length; i < l; i++) { - callback.call(binding, array[i], i, array); - } - } - } - - function map(array, callback) { - var output = []; - var i, l; - - for (i = 0, l = array.length; i < l; i++) { - output.push(callback(array[i], i, array)); - } - - return output; - } - - var getIdx; - if (Array.prototype.indexOf) { - getIdx = function (array, obj, from) { - return array.indexOf(obj, from); - }; - } else { - getIdx = function (array, obj, from) { - if (from === undefined || from === null) { - from = 0; - } else if (from < 0) { - from = Math.max(0, array.length + from); - } - for (var i = from, l = array.length; i < l; i++) { - if (array[i] === obj) { - return i; - } - } - return -1; - }; - } - - var isArray = Array.isArray || function (array) { - return Object.prototype.toString.call(array) === '[object Array]'; - }; - - exports.isArray = isArray; - var indexOfArray = getIdx; - exports.indexOfArray = indexOfArray; -}); -enifed('htmlbars-util/handlebars/safe-string', ['exports'], function (exports) { - // Build out our basic SafeString type - 'use strict'; - - function SafeString(string) { - this.string = string; - } - - SafeString.prototype.toString = SafeString.prototype.toHTML = function () { - return '' + this.string; - }; - - exports.default = SafeString; -}); -enifed('htmlbars-util/handlebars/utils', ['exports'], function (exports) { - 'use strict'; - - exports.extend = extend; - exports.indexOf = indexOf; - exports.escapeExpression = escapeExpression; - exports.isEmpty = isEmpty; - exports.blockParams = blockParams; - exports.appendContextPath = appendContextPath; - var escape = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''', - '`': '`' - }; - - var badChars = /[&<>"'`]/g, - possible = /[&<>"'`]/; - - function escapeChar(chr) { - return escape[chr]; - } - - function extend(obj /* , ...source */) { - for (var i = 1; i < arguments.length; i++) { - for (var key in arguments[i]) { - if (Object.prototype.hasOwnProperty.call(arguments[i], key)) { - obj[key] = arguments[i][key]; - } - } - } - - return obj; - } - - var toString = Object.prototype.toString; - - exports.toString = toString; - // Sourced from lodash - // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt - /*eslint-disable func-style, no-var */ - var isFunction = function (value) { - return typeof value === 'function'; - }; - // fallback for older versions of Chrome and Safari - /* istanbul ignore next */ - if (isFunction(/x/)) { - exports.isFunction = isFunction = function (value) { - return typeof value === 'function' && toString.call(value) === '[object Function]'; - }; - } - var isFunction; - exports.isFunction = isFunction; - /*eslint-enable func-style, no-var */ - - /* istanbul ignore next */ - var isArray = Array.isArray || function (value) { - return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false; - }; - - exports.isArray = isArray; - // Older IE versions do not directly support indexOf so we must implement our own, sadly. - - function indexOf(array, value) { - for (var i = 0, len = array.length; i < len; i++) { - if (array[i] === value) { - return i; - } - } - return -1; - } - - function escapeExpression(string) { - if (typeof string !== 'string') { - // don't escape SafeStrings, since they're already safe - if (string && string.toHTML) { - return string.toHTML(); - } else if (string == null) { - return ''; - } else if (!string) { - return string + ''; - } - - // Force a string conversion as this will be done by the append regardless and - // the regex test will do this transparently behind the scenes, causing issues if - // an object's to string has escaped characters in it. - string = '' + string; - } - - if (!possible.test(string)) { - return string; - } - return string.replace(badChars, escapeChar); - } - - function isEmpty(value) { - if (!value && value !== 0) { - return true; - } else if (isArray(value) && value.length === 0) { - return true; - } else { - return false; - } - } - - function blockParams(params, ids) { - params.path = ids; - return params; - } - - function appendContextPath(contextPath, id) { - return (contextPath ? contextPath + '.' : '') + id; - } -}); -enifed("htmlbars-util/morph-utils", ["exports"], function (exports) { - /*globals console*/ - - "use strict"; - - exports.visitChildren = visitChildren; - exports.validateChildMorphs = validateChildMorphs; - exports.linkParams = linkParams; - exports.dump = dump; - - function visitChildren(nodes, callback) { - if (!nodes || nodes.length === 0) { - return; - } - - nodes = nodes.slice(); - - while (nodes.length) { - var node = nodes.pop(); - callback(node); - - if (node.childNodes) { - nodes.push.apply(nodes, node.childNodes); - } else if (node.firstChildMorph) { - var current = node.firstChildMorph; - - while (current) { - nodes.push(current); - current = current.nextMorph; - } - } else if (node.morphList) { - var current = node.morphList.firstChildMorph; - - while (current) { - nodes.push(current); - current = current.nextMorph; - } - } - } - } - - function validateChildMorphs(env, morph, visitor) { - var morphList = morph.morphList; - if (morph.morphList) { - var current = morphList.firstChildMorph; - - while (current) { - var next = current.nextMorph; - validateChildMorphs(env, current, visitor); - current = next; - } - } else if (morph.lastResult) { - morph.lastResult.revalidateWith(env, undefined, undefined, undefined, visitor); - } else if (morph.childNodes) { - // This means that the childNodes were wired up manually - for (var i = 0, l = morph.childNodes.length; i < l; i++) { - validateChildMorphs(env, morph.childNodes[i], visitor); - } - } - } - - function linkParams(env, scope, morph, path, params, hash) { - if (morph.linkedParams) { - return; - } - - if (env.hooks.linkRenderNode(morph, env, scope, path, params, hash)) { - morph.linkedParams = { params: params, hash: hash }; - } - } - - function dump(node) { - console.group(node, node.isDirty); - - if (node.childNodes) { - map(node.childNodes, dump); - } else if (node.firstChildMorph) { - var current = node.firstChildMorph; - - while (current) { - dump(current); - current = current.nextMorph; - } - } else if (node.morphList) { - dump(node.morphList); - } - - console.groupEnd(); - } - - function map(nodes, cb) { - for (var i = 0, l = nodes.length; i < l; i++) { - cb(nodes[i]); - } - } -}); -enifed('htmlbars-util/namespaces', ['exports'], function (exports) { - // ref http://dev.w3.org/html5/spec-LC/namespaces.html - 'use strict'; - - exports.getAttrNamespace = getAttrNamespace; - var defaultNamespaces = { - html: 'http://www.w3.org/1999/xhtml', - mathml: 'http://www.w3.org/1998/Math/MathML', - svg: 'http://www.w3.org/2000/svg', - xlink: 'http://www.w3.org/1999/xlink', - xml: 'http://www.w3.org/XML/1998/namespace' - }; - - function getAttrNamespace(attrName, detectedNamespace) { - if (detectedNamespace) { - return detectedNamespace; - } - - var namespace; - - var colonIndex = attrName.indexOf(':'); - if (colonIndex !== -1) { - var prefix = attrName.slice(0, colonIndex); - namespace = defaultNamespaces[prefix]; - } - - return namespace || null; - } -}); -enifed("htmlbars-util/object-utils", ["exports"], function (exports) { - "use strict"; - - exports.merge = merge; - exports.shallowCopy = shallowCopy; - exports.keySet = keySet; - exports.keyLength = keyLength; - - function merge(options, defaults) { - for (var prop in defaults) { - if (options.hasOwnProperty(prop)) { - continue; - } - options[prop] = defaults[prop]; - } - return options; - } - - function shallowCopy(obj) { - return merge({}, obj); - } - - function keySet(obj) { - var set = {}; - - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - set[prop] = true; - } - } - - return set; - } - - function keyLength(obj) { - var count = 0; - - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - count++; - } - } - - return count; - } -}); -enifed("htmlbars-util/quoting", ["exports"], function (exports) { - "use strict"; - - exports.hash = hash; - exports.repeat = repeat; - function escapeString(str) { - str = str.replace(/\\/g, "\\\\"); - str = str.replace(/"/g, '\\"'); - str = str.replace(/\n/g, "\\n"); - return str; - } - - exports.escapeString = escapeString; - - function string(str) { - return '"' + escapeString(str) + '"'; - } - - exports.string = string; - - function array(a) { - return "[" + a + "]"; - } - - exports.array = array; - - function hash(pairs) { - return "{" + pairs.join(", ") + "}"; - } - - function repeat(chars, times) { - var str = ""; - while (times--) { - str += chars; - } - return str; - } -}); -enifed('htmlbars-util/safe-string', ['exports', 'htmlbars-util/handlebars/safe-string'], function (exports, _htmlbarsUtilHandlebarsSafeString) { - 'use strict'; - - exports.default = _htmlbarsUtilHandlebarsSafeString.default; -}); -enifed("htmlbars-util/template-utils", ["exports", "htmlbars-util/morph-utils", "htmlbars-runtime/render"], function (exports, _htmlbarsUtilMorphUtils, _htmlbarsRuntimeRender) { - "use strict"; - - exports.RenderState = RenderState; - exports.blockFor = blockFor; - exports.renderAndCleanup = renderAndCleanup; - exports.clearMorph = clearMorph; - exports.clearMorphList = clearMorphList; - - function RenderState(renderNode, morphList) { - // The morph list that is no longer needed and can be - // destroyed. - this.morphListToClear = morphList; - - // The morph list that needs to be pruned of any items - // that were not yielded on a subsequent render. - this.morphListToPrune = null; - - // A map of morphs for each item yielded in during this - // rendering pass. Any morphs in the DOM but not in this map - // will be pruned during cleanup. - this.handledMorphs = {}; - this.collisions = undefined; - - // The morph to clear once rendering is complete. By - // default, we set this to the previous morph (to catch - // the case where nothing is yielded; in that case, we - // should just clear the morph). Otherwise this gets set - // to null if anything is rendered. - this.morphToClear = renderNode; - - this.shadowOptions = null; - } - - function Block(render, template, blockOptions) { - this.render = render; - this.template = template; - this.blockOptions = blockOptions; - this.arity = template.arity; - } - - Block.prototype.invoke = function (env, blockArguments, _self, renderNode, parentScope, visitor) { - if (renderNode.lastResult) { - renderNode.lastResult.revalidateWith(env, undefined, _self, blockArguments, visitor); - } else { - this._firstRender(env, blockArguments, _self, renderNode, parentScope); - } - }; - - Block.prototype._firstRender = function (env, blockArguments, _self, renderNode, parentScope) { - var options = { renderState: new RenderState(renderNode) }; - var render = this.render; - var template = this.template; - var scope = this.blockOptions.scope; - - var shadowScope = scope ? env.hooks.createChildScope(scope) : env.hooks.createFreshScope(); - - env.hooks.bindShadowScope(env, parentScope, shadowScope, this.blockOptions.options); - - if (_self !== undefined) { - env.hooks.bindSelf(env, shadowScope, _self); - } else if (this.blockOptions.self !== undefined) { - env.hooks.bindSelf(env, shadowScope, this.blockOptions.self); - } - - bindBlocks(env, shadowScope, this.blockOptions.yieldTo); - - renderAndCleanup(renderNode, env, options, null, function () { - options.renderState.morphToClear = null; - var renderOptions = new _htmlbarsRuntimeRender.RenderOptions(renderNode, undefined, blockArguments); - render(template, env, shadowScope, renderOptions); - }); - }; - - function blockFor(render, template, blockOptions) { - return new Block(render, template, blockOptions); - } - - function bindBlocks(env, shadowScope, blocks) { - if (!blocks) { - return; - } - if (blocks instanceof Block) { - env.hooks.bindBlock(env, shadowScope, blocks); - } else { - for (var name in blocks) { - if (blocks.hasOwnProperty(name)) { - env.hooks.bindBlock(env, shadowScope, blocks[name], name); - } - } - } - } - - function renderAndCleanup(morph, env, options, shadowOptions, callback) { - // The RenderState object is used to collect information about what the - // helper or hook being invoked has yielded. Once it has finished either - // yielding multiple items (via yieldItem) or a single template (via - // yieldTemplate), we detect what was rendered and how it differs from - // the previous render, cleaning up old state in DOM as appropriate. - var renderState = options.renderState; - renderState.collisions = undefined; - renderState.shadowOptions = shadowOptions; - - // Invoke the callback, instructing it to save information about what it - // renders into RenderState. - var result = callback(options); - - // The hook can opt-out of cleanup if it handled cleanup itself. - if (result && result.handled) { - return; - } - - var morphMap = morph.morphMap; - - // Walk the morph list, clearing any items that were yielded in a previous - // render but were not yielded during this render. - var morphList = renderState.morphListToPrune; - if (morphList) { - var handledMorphs = renderState.handledMorphs; - var item = morphList.firstChildMorph; - - while (item) { - var next = item.nextMorph; - - // If we don't see the key in handledMorphs, it wasn't - // yielded in and we can safely remove it from DOM. - if (!(item.key in handledMorphs)) { - morphMap[item.key] = undefined; - clearMorph(item, env, true); - item.destroy(); - } - - item = next; - } - } - - morphList = renderState.morphListToClear; - if (morphList) { - clearMorphList(morphList, morph, env); - } - - var toClear = renderState.morphToClear; - if (toClear) { - clearMorph(toClear, env); - } - } - - function clearMorph(morph, env, destroySelf) { - var cleanup = env.hooks.cleanupRenderNode; - var destroy = env.hooks.destroyRenderNode; - var willCleanup = env.hooks.willCleanupTree; - var didCleanup = env.hooks.didCleanupTree; - - function destroyNode(node) { - if (cleanup) { - cleanup(node); - } - if (destroy) { - destroy(node); - } - } - - if (willCleanup) { - willCleanup(env, morph, destroySelf); - } - if (cleanup) { - cleanup(morph); - } - if (destroySelf && destroy) { - destroy(morph); - } - - _htmlbarsUtilMorphUtils.visitChildren(morph.childNodes, destroyNode); - - // TODO: Deal with logical children that are not in the DOM tree - morph.clear(); - if (didCleanup) { - didCleanup(env, morph, destroySelf); - } - - morph.lastResult = null; - morph.lastYielded = null; - morph.childNodes = null; - } - - function clearMorphList(morphList, morph, env) { - var item = morphList.firstChildMorph; - - while (item) { - var next = item.nextMorph; - morph.morphMap[item.key] = undefined; - clearMorph(item, env, true); - item.destroy(); - - item = next; - } - - // Remove the MorphList from the morph. - morphList.clear(); - morph.morphList = null; - } -}); -enifed("htmlbars-util/void-tag-names", ["exports", "htmlbars-util/array-utils"], function (exports, _htmlbarsUtilArrayUtils) { - "use strict"; - - // The HTML elements in this list are speced by - // http://www.w3.org/TR/html-markup/syntax.html#syntax-elements, - // and will be forced to close regardless of if they have a - // self-closing /> at the end. - var voidTagNames = "area base br col command embed hr img input keygen link meta param source track wbr"; - var voidMap = {}; - - _htmlbarsUtilArrayUtils.forEach(voidTagNames.split(" "), function (tagName) { - voidMap[tagName] = true; - }); - - exports.default = voidMap; -}); -enifed('htmlbars-util', ['exports', 'htmlbars-util/safe-string', 'htmlbars-util/handlebars/utils', 'htmlbars-util/namespaces', 'htmlbars-util/morph-utils'], function (exports, _htmlbarsUtilSafeString, _htmlbarsUtilHandlebarsUtils, _htmlbarsUtilNamespaces, _htmlbarsUtilMorphUtils) { - 'use strict'; - - exports.SafeString = _htmlbarsUtilSafeString.default; - exports.escapeExpression = _htmlbarsUtilHandlebarsUtils.escapeExpression; - exports.getAttrNamespace = _htmlbarsUtilNamespaces.getAttrNamespace; - exports.validateChildMorphs = _htmlbarsUtilMorphUtils.validateChildMorphs; - exports.linkParams = _htmlbarsUtilMorphUtils.linkParams; - exports.dump = _htmlbarsUtilMorphUtils.dump; -}); -enifed('morph-attr/sanitize-attribute-value', ['exports'], function (exports) { - /* jshint scripturl:true */ - - 'use strict'; - - exports.sanitizeAttributeValue = sanitizeAttributeValue; - var badProtocols = { - 'javascript:': true, - 'vbscript:': true - }; - - var badTags = { - 'A': true, - 'BODY': true, - 'LINK': true, - 'IMG': true, - 'IFRAME': true, - 'BASE': true, - 'FORM': true - }; - - var badTagsForDataURI = { - 'EMBED': true - }; - - var badAttributes = { - 'href': true, - 'src': true, - 'background': true, - 'action': true - }; - - exports.badAttributes = badAttributes; - var badAttributesForDataURI = { - 'src': true - }; - - function sanitizeAttributeValue(dom, element, attribute, value) { - var tagName; - - if (!element) { - tagName = null; - } else { - tagName = element.tagName.toUpperCase(); - } - - if (value && value.toHTML) { - return value.toHTML(); - } - - if ((tagName === null || badTags[tagName]) && badAttributes[attribute]) { - var protocol = dom.protocolForURL(value); - if (badProtocols[protocol] === true) { - return 'unsafe:' + value; - } - } - - if (badTagsForDataURI[tagName] && badAttributesForDataURI[attribute]) { - return 'unsafe:' + value; - } - - return value; - } -}); -enifed("morph-attr", ["exports", "morph-attr/sanitize-attribute-value", "dom-helper/prop", "dom-helper/build-html-dom", "htmlbars-util"], function (exports, _morphAttrSanitizeAttributeValue, _domHelperProp, _domHelperBuildHtmlDom, _htmlbarsUtil) { - "use strict"; - - function getProperty() { - return this.domHelper.getPropertyStrict(this.element, this.attrName); - } - - function updateProperty(value) { - if (this._renderedInitially === true || !_domHelperProp.isAttrRemovalValue(value)) { - var element = this.element; - var attrName = this.attrName; - - if (attrName === 'value' && element.tagName === 'INPUT' && element.value === value) { - // Do nothing. Attempts to avoid accidently changing the input cursor location. - // See https://github.com/tildeio/htmlbars/pull/447 for more details. - } else { - // do not render if initial value is undefined or null - this.domHelper.setPropertyStrict(element, attrName, value); - } - } - - this._renderedInitially = true; - } - - function getAttribute() { - return this.domHelper.getAttribute(this.element, this.attrName); - } - - function updateAttribute(value) { - if (_domHelperProp.isAttrRemovalValue(value)) { - this.domHelper.removeAttribute(this.element, this.attrName); - } else { - this.domHelper.setAttribute(this.element, this.attrName, value); - } - } - - function getAttributeNS() { - return this.domHelper.getAttributeNS(this.element, this.namespace, this.attrName); - } - - function updateAttributeNS(value) { - if (_domHelperProp.isAttrRemovalValue(value)) { - this.domHelper.removeAttribute(this.element, this.attrName); - } else { - this.domHelper.setAttributeNS(this.element, this.namespace, this.attrName, value); - } - } - - var UNSET = { unset: true }; - - var guid = 1; - - AttrMorph.create = function (element, attrName, domHelper, namespace) { - var ns = _htmlbarsUtil.getAttrNamespace(attrName, namespace); - - if (ns) { - return new AttributeNSAttrMorph(element, attrName, domHelper, ns); - } else { - return createNonNamespacedAttrMorph(element, attrName, domHelper); - } - }; - - function createNonNamespacedAttrMorph(element, attrName, domHelper) { - var _normalizeProperty = _domHelperProp.normalizeProperty(element, attrName); - - var normalized = _normalizeProperty.normalized; - var type = _normalizeProperty.type; - - if (element.namespaceURI === _domHelperBuildHtmlDom.svgNamespace || attrName === 'style' || type === 'attr') { - return new AttributeAttrMorph(element, normalized, domHelper); - } else { - return new PropertyAttrMorph(element, normalized, domHelper); - } - } - - function AttrMorph(element, attrName, domHelper) { - this.element = element; - this.domHelper = domHelper; - this.attrName = attrName; - this._state = undefined; - this.isDirty = false; - this.isSubtreeDirty = false; - this.escaped = true; - this.lastValue = UNSET; - this.lastResult = null; - this.lastYielded = null; - this.childNodes = null; - this.linkedParams = null; - this.linkedResult = null; - this.guid = "attr" + guid++; - this.seen = false; - this.ownerNode = null; - this.rendered = false; - this._renderedInitially = false; - this.namespace = undefined; - this.didInit(); - } - - AttrMorph.prototype.getState = function () { - if (!this._state) { - this._state = {}; - } - - return this._state; - }; - - AttrMorph.prototype.setState = function (newState) { - /*jshint -W093 */ - - return this._state = newState; - }; - - AttrMorph.prototype.didInit = function () {}; - AttrMorph.prototype.willSetContent = function () {}; - - AttrMorph.prototype.setContent = function (value) { - this.willSetContent(value); - - if (this.lastValue === value) { - return; - } - this.lastValue = value; - - if (this.escaped) { - var sanitized = _morphAttrSanitizeAttributeValue.sanitizeAttributeValue(this.domHelper, this.element, this.attrName, value); - this._update(sanitized, this.namespace); - } else { - this._update(value, this.namespace); - } - }; - - AttrMorph.prototype.getContent = function () { - var value = this.lastValue = this._get(); - return value; - }; - - // renderAndCleanup calls `clear` on all items in the morph map - // just before calling `destroy` on the morph. - // - // As a future refactor this could be changed to set the property - // back to its original/default value. - AttrMorph.prototype.clear = function () {}; - - AttrMorph.prototype.destroy = function () { - this.element = null; - this.domHelper = null; - }; - - AttrMorph.prototype._$superAttrMorph = AttrMorph; - - function PropertyAttrMorph(element, attrName, domHelper) { - this._$superAttrMorph(element, attrName, domHelper); - } - - PropertyAttrMorph.prototype = Object.create(AttrMorph.prototype); - PropertyAttrMorph.prototype._update = updateProperty; - PropertyAttrMorph.prototype._get = getProperty; - - function AttributeNSAttrMorph(element, attrName, domHelper, namespace) { - this._$superAttrMorph(element, attrName, domHelper); - this.namespace = namespace; - } - - AttributeNSAttrMorph.prototype = Object.create(AttrMorph.prototype); - AttributeNSAttrMorph.prototype._update = updateAttributeNS; - AttributeNSAttrMorph.prototype._get = getAttributeNS; - - function AttributeAttrMorph(element, attrName, domHelper) { - this._$superAttrMorph(element, attrName, domHelper); - } - - AttributeAttrMorph.prototype = Object.create(AttrMorph.prototype); - AttributeAttrMorph.prototype._update = updateAttribute; - AttributeAttrMorph.prototype._get = getAttribute; - - exports.default = AttrMorph; - exports.sanitizeAttributeValue = _morphAttrSanitizeAttributeValue.sanitizeAttributeValue; -}); -enifed('morph-range/morph-list', ['exports', 'morph-range/utils'], function (exports, _morphRangeUtils) { - 'use strict'; - - function MorphList() { - // morph graph - this.firstChildMorph = null; - this.lastChildMorph = null; - - this.mountedMorph = null; - } - - var prototype = MorphList.prototype; - - prototype.clear = function MorphList$clear() { - var current = this.firstChildMorph; - - while (current) { - var next = current.nextMorph; - current.previousMorph = null; - current.nextMorph = null; - current.parentMorphList = null; - current = next; - } - - this.firstChildMorph = this.lastChildMorph = null; - }; - - prototype.destroy = function MorphList$destroy() {}; - - prototype.appendMorph = function MorphList$appendMorph(morph) { - this.insertBeforeMorph(morph, null); - }; - - prototype.insertBeforeMorph = function MorphList$insertBeforeMorph(morph, referenceMorph) { - if (morph.parentMorphList !== null) { - morph.unlink(); - } - if (referenceMorph && referenceMorph.parentMorphList !== this) { - throw new Error('The morph before which the new morph is to be inserted is not a child of this morph.'); - } - - var mountedMorph = this.mountedMorph; - - if (mountedMorph) { - - var parentNode = mountedMorph.firstNode.parentNode; - var referenceNode = referenceMorph ? referenceMorph.firstNode : mountedMorph.lastNode.nextSibling; - - _morphRangeUtils.insertBefore(parentNode, morph.firstNode, morph.lastNode, referenceNode); - - // was not in list mode replace current content - if (!this.firstChildMorph) { - _morphRangeUtils.clear(this.mountedMorph.firstNode.parentNode, this.mountedMorph.firstNode, this.mountedMorph.lastNode); - } - } - - morph.parentMorphList = this; - - var previousMorph = referenceMorph ? referenceMorph.previousMorph : this.lastChildMorph; - if (previousMorph) { - previousMorph.nextMorph = morph; - morph.previousMorph = previousMorph; - } else { - this.firstChildMorph = morph; - } - - if (referenceMorph) { - referenceMorph.previousMorph = morph; - morph.nextMorph = referenceMorph; - } else { - this.lastChildMorph = morph; - } - - this.firstChildMorph._syncFirstNode(); - this.lastChildMorph._syncLastNode(); - }; - - prototype.removeChildMorph = function MorphList$removeChildMorph(morph) { - if (morph.parentMorphList !== this) { - throw new Error("Cannot remove a morph from a parent it is not inside of"); - } - - morph.destroy(); - }; - - exports.default = MorphList; -}); -enifed('morph-range/morph-list.umd', ['exports', 'morph-range/morph-list'], function (exports, _morphRangeMorphList) { - 'use strict'; - - (function (root, factory) { - if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (typeof exports === 'object') { - module.exports = factory(); - } else { - root.MorphList = factory(); - } - })(undefined, function () { - return _morphRangeMorphList.default; - }); -}); -enifed("morph-range/utils", ["exports"], function (exports) { - // inclusive of both nodes - "use strict"; - - exports.clear = clear; - exports.insertBefore = insertBefore; - - function clear(parentNode, firstNode, lastNode) { - if (!parentNode) { - return; - } - - var node = firstNode; - var nextNode; - do { - nextNode = node.nextSibling; - parentNode.removeChild(node); - if (node === lastNode) { - break; - } - node = nextNode; - } while (node); - } - - function insertBefore(parentNode, firstNode, lastNode, refNode) { - var node = firstNode; - var nextNode; - do { - nextNode = node.nextSibling; - parentNode.insertBefore(node, refNode); - if (node === lastNode) { - break; - } - node = nextNode; - } while (node); - } -}); -enifed('morph-range', ['exports', 'morph-range/utils'], function (exports, _morphRangeUtils) { - 'use strict'; - - // constructor just initializes the fields - // use one of the static initializers to create a valid morph. - function Morph(domHelper, contextualElement) { - this.domHelper = domHelper; - // context if content if current content is detached - this.contextualElement = contextualElement; - // inclusive range of morph - // these should be nodeType 1, 3, or 8 - this.firstNode = null; - this.lastNode = null; - - // flag to force text to setContent to be treated as html - this.parseTextAsHTML = false; - - // morph list graph - this.parentMorphList = null; - this.previousMorph = null; - this.nextMorph = null; - } - - Morph.empty = function (domHelper, contextualElement) { - var morph = new Morph(domHelper, contextualElement); - morph.clear(); - return morph; - }; - - Morph.create = function (domHelper, contextualElement, node) { - var morph = new Morph(domHelper, contextualElement); - morph.setNode(node); - return morph; - }; - - Morph.attach = function (domHelper, contextualElement, firstNode, lastNode) { - var morph = new Morph(domHelper, contextualElement); - morph.setRange(firstNode, lastNode); - return morph; - }; - - Morph.prototype.setContent = function Morph$setContent(content) { - if (content === null || content === undefined) { - return this.clear(); - } - - var type = typeof content; - switch (type) { - case 'string': - if (this.parseTextAsHTML) { - return this.domHelper.setMorphHTML(this, content); - } - return this.setText(content); - case 'object': - if (typeof content.nodeType === 'number') { - return this.setNode(content); - } - /* Handlebars.SafeString */ - if (typeof content.toHTML === 'function') { - return this.setHTML(content.toHTML()); - } - if (this.parseTextAsHTML) { - return this.setHTML(content.toString()); - } - /* falls through */ - case 'boolean': - case 'number': - return this.setText(content.toString()); - case 'function': - raiseCannotBindToFunction(content); - default: - throw new TypeError('unsupported content'); - } - }; - - function raiseCannotBindToFunction(content) { - var functionName = content.name; - var message; - - if (functionName) { - message = 'Unsupported Content: Cannot bind to function `' + functionName + '`'; - } else { - message = 'Unsupported Content: Cannot bind to function'; - } - - throw new TypeError(message); - } - - Morph.prototype.clear = function Morph$clear() { - var node = this.setNode(this.domHelper.createComment('')); - return node; - }; - - Morph.prototype.setText = function Morph$setText(text) { - var firstNode = this.firstNode; - var lastNode = this.lastNode; - - if (firstNode && lastNode === firstNode && firstNode.nodeType === 3) { - firstNode.nodeValue = text; - return firstNode; - } - - return this.setNode(text ? this.domHelper.createTextNode(text) : this.domHelper.createComment('')); - }; - - Morph.prototype.setNode = function Morph$setNode(newNode) { - var firstNode, lastNode; - switch (newNode.nodeType) { - case 3: - firstNode = newNode; - lastNode = newNode; - break; - case 11: - firstNode = newNode.firstChild; - lastNode = newNode.lastChild; - if (firstNode === null) { - firstNode = this.domHelper.createComment(''); - newNode.appendChild(firstNode); - lastNode = firstNode; - } - break; - default: - firstNode = newNode; - lastNode = newNode; - break; - } - - this.setRange(firstNode, lastNode); - - return newNode; - }; - - Morph.prototype.setRange = function (firstNode, lastNode) { - var previousFirstNode = this.firstNode; - if (previousFirstNode !== null) { - - var parentNode = previousFirstNode.parentNode; - if (parentNode !== null) { - _morphRangeUtils.insertBefore(parentNode, firstNode, lastNode, previousFirstNode); - _morphRangeUtils.clear(parentNode, previousFirstNode, this.lastNode); - } - } - - this.firstNode = firstNode; - this.lastNode = lastNode; - - if (this.parentMorphList) { - this._syncFirstNode(); - this._syncLastNode(); - } - }; - - Morph.prototype.destroy = function Morph$destroy() { - this.unlink(); - - var firstNode = this.firstNode; - var lastNode = this.lastNode; - var parentNode = firstNode && firstNode.parentNode; - - this.firstNode = null; - this.lastNode = null; - - _morphRangeUtils.clear(parentNode, firstNode, lastNode); - }; - - Morph.prototype.unlink = function Morph$unlink() { - var parentMorphList = this.parentMorphList; - var previousMorph = this.previousMorph; - var nextMorph = this.nextMorph; - - if (previousMorph) { - if (nextMorph) { - previousMorph.nextMorph = nextMorph; - nextMorph.previousMorph = previousMorph; - } else { - previousMorph.nextMorph = null; - parentMorphList.lastChildMorph = previousMorph; - } - } else { - if (nextMorph) { - nextMorph.previousMorph = null; - parentMorphList.firstChildMorph = nextMorph; - } else if (parentMorphList) { - parentMorphList.lastChildMorph = parentMorphList.firstChildMorph = null; - } - } - - this.parentMorphList = null; - this.nextMorph = null; - this.previousMorph = null; - - if (parentMorphList && parentMorphList.mountedMorph) { - if (!parentMorphList.firstChildMorph) { - // list is empty - parentMorphList.mountedMorph.clear(); - return; - } else { - parentMorphList.firstChildMorph._syncFirstNode(); - parentMorphList.lastChildMorph._syncLastNode(); - } - } - }; - - Morph.prototype.setHTML = function (text) { - var fragment = this.domHelper.parseHTML(text, this.contextualElement); - return this.setNode(fragment); - }; - - Morph.prototype.setMorphList = function Morph$appendMorphList(morphList) { - morphList.mountedMorph = this; - this.clear(); - - var originalFirstNode = this.firstNode; - - if (morphList.firstChildMorph) { - this.firstNode = morphList.firstChildMorph.firstNode; - this.lastNode = morphList.lastChildMorph.lastNode; - - var current = morphList.firstChildMorph; - - while (current) { - var next = current.nextMorph; - current.insertBeforeNode(originalFirstNode, null); - current = next; - } - originalFirstNode.parentNode.removeChild(originalFirstNode); - } - }; - - Morph.prototype._syncFirstNode = function Morph$syncFirstNode() { - var morph = this; - var parentMorphList; - while (parentMorphList = morph.parentMorphList) { - if (parentMorphList.mountedMorph === null) { - break; - } - if (morph !== parentMorphList.firstChildMorph) { - break; - } - if (morph.firstNode === parentMorphList.mountedMorph.firstNode) { - break; - } - - parentMorphList.mountedMorph.firstNode = morph.firstNode; - - morph = parentMorphList.mountedMorph; - } - }; - - Morph.prototype._syncLastNode = function Morph$syncLastNode() { - var morph = this; - var parentMorphList; - while (parentMorphList = morph.parentMorphList) { - if (parentMorphList.mountedMorph === null) { - break; - } - if (morph !== parentMorphList.lastChildMorph) { - break; - } - if (morph.lastNode === parentMorphList.mountedMorph.lastNode) { - break; - } - - parentMorphList.mountedMorph.lastNode = morph.lastNode; - - morph = parentMorphList.mountedMorph; - } - }; - - Morph.prototype.insertBeforeNode = function Morph$insertBeforeNode(parentNode, refNode) { - _morphRangeUtils.insertBefore(parentNode, this.firstNode, this.lastNode, refNode); - }; - - Morph.prototype.appendToNode = function Morph$appendToNode(parentNode) { - _morphRangeUtils.insertBefore(parentNode, this.firstNode, this.lastNode, null); - }; - - exports.default = Morph; -}); -enifed("route-recognizer/dsl", ["exports"], function (exports) { - "use strict"; - - function Target(path, matcher, delegate) { - this.path = path; - this.matcher = matcher; - this.delegate = delegate; - } - - Target.prototype = { - to: function (target, callback) { - var delegate = this.delegate; - - if (delegate && delegate.willAddRoute) { - target = delegate.willAddRoute(this.matcher.target, target); - } - - this.matcher.add(this.path, target); - - if (callback) { - if (callback.length === 0) { - throw new Error("You must have an argument in the function passed to `to`"); - } - this.matcher.addChild(this.path, target, callback, this.delegate); - } - return this; - } - }; - - function Matcher(target) { - this.routes = {}; - this.children = {}; - this.target = target; - } - - Matcher.prototype = { - add: function (path, handler) { - this.routes[path] = handler; - }, - - addChild: function (path, target, callback, delegate) { - var matcher = new Matcher(target); - this.children[path] = matcher; - - var match = generateMatch(path, matcher, delegate); - - if (delegate && delegate.contextEntered) { - delegate.contextEntered(target, match); - } - - callback(match); - } - }; - - function generateMatch(startingPath, matcher, delegate) { - return function (path, nestedCallback) { - var fullPath = startingPath + path; - - if (nestedCallback) { - nestedCallback(generateMatch(fullPath, matcher, delegate)); - } else { - return new Target(startingPath + path, matcher, delegate); - } - }; - } - - function addRoute(routeArray, path, handler) { - var len = 0; - for (var i = 0, l = routeArray.length; i < l; i++) { - len += routeArray[i].path.length; - } - - path = path.substr(len); - var route = { path: path, handler: handler }; - routeArray.push(route); - } - - function eachRoute(baseRoute, matcher, callback, binding) { - var routes = matcher.routes; - - for (var path in routes) { - if (routes.hasOwnProperty(path)) { - var routeArray = baseRoute.slice(); - addRoute(routeArray, path, routes[path]); - - if (matcher.children[path]) { - eachRoute(routeArray, matcher.children[path], callback, binding); - } else { - callback.call(binding, routeArray); - } - } - } - } - - exports.default = function (callback, addRouteCallback) { - var matcher = new Matcher(); - - callback(generateMatch("", matcher, this.delegate)); - - eachRoute([], matcher, function (route) { - if (addRouteCallback) { - addRouteCallback(this, route); - } else { - this.add(route); - } - }, this); - }; -}); -enifed('route-recognizer', ['exports', 'route-recognizer/dsl'], function (exports, _routeRecognizerDsl) { - 'use strict'; - - var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\']; - - var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); - - function isArray(test) { - return Object.prototype.toString.call(test) === "[object Array]"; - } - - // A Segment represents a segment in the original route description. - // Each Segment type provides an `eachChar` and `regex` method. - // - // The `eachChar` method invokes the callback with one or more character - // specifications. A character specification consumes one or more input - // characters. - // - // The `regex` method returns a regex fragment for the segment. If the - // segment is a dynamic of star segment, the regex fragment also includes - // a capture. - // - // A character specification contains: - // - // * `validChars`: a String with a list of all valid characters, or - // * `invalidChars`: a String with a list of all invalid characters - // * `repeat`: true if the character specification can repeat - - function StaticSegment(string) { - this.string = string; - } - StaticSegment.prototype = { - eachChar: function (callback) { - var string = this.string, - ch; - - for (var i = 0, l = string.length; i < l; i++) { - ch = string.charAt(i); - callback({ validChars: ch }); - } - }, - - regex: function () { - return this.string.replace(escapeRegex, '\\$1'); - }, - - generate: function () { - return this.string; - } - }; - - function DynamicSegment(name) { - this.name = name; - } - DynamicSegment.prototype = { - eachChar: function (callback) { - callback({ invalidChars: "/", repeat: true }); - }, - - regex: function () { - return "([^/]+)"; - }, - - generate: function (params) { - return params[this.name]; - } - }; - - function StarSegment(name) { - this.name = name; - } - StarSegment.prototype = { - eachChar: function (callback) { - callback({ invalidChars: "", repeat: true }); - }, - - regex: function () { - return "(.+)"; - }, - - generate: function (params) { - return params[this.name]; - } - }; - - function EpsilonSegment() {} - EpsilonSegment.prototype = { - eachChar: function () {}, - regex: function () { - return ""; - }, - generate: function () { - return ""; - } - }; - - function parse(route, names, types) { - // normalize route as not starting with a "/". Recognition will - // also normalize. - if (route.charAt(0) === "/") { - route = route.substr(1); - } - - var segments = route.split("/"), - results = []; - - for (var i = 0, l = segments.length; i < l; i++) { - var segment = segments[i], - match; - - if (match = segment.match(/^:([^\/]+)$/)) { - results.push(new DynamicSegment(match[1])); - names.push(match[1]); - types.dynamics++; - } else if (match = segment.match(/^\*([^\/]+)$/)) { - results.push(new StarSegment(match[1])); - names.push(match[1]); - types.stars++; - } else if (segment === "") { - results.push(new EpsilonSegment()); - } else { - results.push(new StaticSegment(segment)); - types.statics++; - } - } - - return results; - } - - // A State has a character specification and (`charSpec`) and a list of possible - // subsequent states (`nextStates`). - // - // If a State is an accepting state, it will also have several additional - // properties: - // - // * `regex`: A regular expression that is used to extract parameters from paths - // that reached this accepting state. - // * `handlers`: Information on how to convert the list of captures into calls - // to registered handlers with the specified parameters - // * `types`: How many static, dynamic or star segments in this route. Used to - // decide which route to use if multiple registered routes match a path. - // - // Currently, State is implemented naively by looping over `nextStates` and - // comparing a character specification against a character. A more efficient - // implementation would use a hash of keys pointing at one or more next states. - - function State(charSpec) { - this.charSpec = charSpec; - this.nextStates = []; - } - - State.prototype = { - get: function (charSpec) { - var nextStates = this.nextStates; - - for (var i = 0, l = nextStates.length; i < l; i++) { - var child = nextStates[i]; - - var isEqual = child.charSpec.validChars === charSpec.validChars; - isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars; - - if (isEqual) { - return child; - } - } - }, - - put: function (charSpec) { - var state; - - // If the character specification already exists in a child of the current - // state, just return that state. - if (state = this.get(charSpec)) { - return state; - } - - // Make a new state for the character spec - state = new State(charSpec); - - // Insert the new state as a child of the current state - this.nextStates.push(state); - - // If this character specification repeats, insert the new state as a child - // of itself. Note that this will not trigger an infinite loop because each - // transition during recognition consumes a character. - if (charSpec.repeat) { - state.nextStates.push(state); - } - - // Return the new state - return state; - }, - - // Find a list of child states matching the next character - match: function (ch) { - // DEBUG "Processing `" + ch + "`:" - var nextStates = this.nextStates, - child, - charSpec, - chars; - - // DEBUG " " + debugState(this) - var returned = []; - - for (var i = 0, l = nextStates.length; i < l; i++) { - child = nextStates[i]; - - charSpec = child.charSpec; - - if (typeof (chars = charSpec.validChars) !== 'undefined') { - if (chars.indexOf(ch) !== -1) { - returned.push(child); - } - } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') { - if (chars.indexOf(ch) === -1) { - returned.push(child); - } - } - } - - return returned; - } - - /** IF DEBUG - , debug: function() { - var charSpec = this.charSpec, - debug = "[", - chars = charSpec.validChars || charSpec.invalidChars; - if (charSpec.invalidChars) { debug += "^"; } - debug += chars; - debug += "]"; - if (charSpec.repeat) { debug += "+"; } - return debug; - } - END IF **/ - }; - - /** IF DEBUG - function debug(log) { - console.log(log); - } - - function debugState(state) { - return state.nextStates.map(function(n) { - if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; } - return "( " + n.debug() + " " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )"; - }).join(", ") - } - END IF **/ - - // This is a somewhat naive strategy, but should work in a lot of cases - // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id. - // - // This strategy generally prefers more static and less dynamic matching. - // Specifically, it - // - // * prefers fewer stars to more, then - // * prefers using stars for less of the match to more, then - // * prefers fewer dynamic segments to more, then - // * prefers more static segments to more - function sortSolutions(states) { - return states.sort(function (a, b) { - if (a.types.stars !== b.types.stars) { - return a.types.stars - b.types.stars; - } - - if (a.types.stars) { - if (a.types.statics !== b.types.statics) { - return b.types.statics - a.types.statics; - } - if (a.types.dynamics !== b.types.dynamics) { - return b.types.dynamics - a.types.dynamics; - } - } - - if (a.types.dynamics !== b.types.dynamics) { - return a.types.dynamics - b.types.dynamics; - } - if (a.types.statics !== b.types.statics) { - return b.types.statics - a.types.statics; - } - - return 0; - }); - } - - function recognizeChar(states, ch) { - var nextStates = []; - - for (var i = 0, l = states.length; i < l; i++) { - var state = states[i]; - - nextStates = nextStates.concat(state.match(ch)); - } - - return nextStates; - } - - var oCreate = Object.create || function (proto) { - function F() {} - F.prototype = proto; - return new F(); - }; - - function RecognizeResults(queryParams) { - this.queryParams = queryParams || {}; - } - RecognizeResults.prototype = oCreate({ - splice: Array.prototype.splice, - slice: Array.prototype.slice, - push: Array.prototype.push, - length: 0, - queryParams: null - }); - - function findHandler(state, path, queryParams) { - var handlers = state.handlers, - regex = state.regex; - var captures = path.match(regex), - currentCapture = 1; - var result = new RecognizeResults(queryParams); - - for (var i = 0, l = handlers.length; i < l; i++) { - var handler = handlers[i], - names = handler.names, - params = {}; - - for (var j = 0, m = names.length; j < m; j++) { - params[names[j]] = captures[currentCapture++]; - } - - result.push({ handler: handler.handler, params: params, isDynamic: !!names.length }); - } - - return result; - } - - function addSegment(currentState, segment) { - segment.eachChar(function (ch) { - var state; - - currentState = currentState.put(ch); - }); - - return currentState; - } - - function decodeQueryParamPart(part) { - // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 - part = part.replace(/\+/gm, '%20'); - return decodeURIComponent(part); - } - - // The main interface - - var RouteRecognizer = function () { - this.rootState = new State(); - this.names = {}; - }; - - RouteRecognizer.prototype = { - add: function (routes, options) { - var currentState = this.rootState, - regex = "^", - types = { statics: 0, dynamics: 0, stars: 0 }, - handlers = [], - allSegments = [], - name; - - var isEmpty = true; - - for (var i = 0, l = routes.length; i < l; i++) { - var route = routes[i], - names = []; - - var segments = parse(route.path, names, types); - - allSegments = allSegments.concat(segments); - - for (var j = 0, m = segments.length; j < m; j++) { - var segment = segments[j]; - - if (segment instanceof EpsilonSegment) { - continue; - } - - isEmpty = false; - - // Add a "/" for the new segment - currentState = currentState.put({ validChars: "/" }); - regex += "/"; - - // Add a representation of the segment to the NFA and regex - currentState = addSegment(currentState, segment); - regex += segment.regex(); - } - - var handler = { handler: route.handler, names: names }; - handlers.push(handler); - } - - if (isEmpty) { - currentState = currentState.put({ validChars: "/" }); - regex += "/"; - } - - currentState.handlers = handlers; - currentState.regex = new RegExp(regex + "$"); - currentState.types = types; - - if (name = options && options.as) { - this.names[name] = { - segments: allSegments, - handlers: handlers - }; - } - }, - - handlersFor: function (name) { - var route = this.names[name], - result = []; - if (!route) { - throw new Error("There is no route named " + name); - } - - for (var i = 0, l = route.handlers.length; i < l; i++) { - result.push(route.handlers[i]); - } - - return result; - }, - - hasRoute: function (name) { - return !!this.names[name]; - }, - - generate: function (name, params) { - var route = this.names[name], - output = ""; - if (!route) { - throw new Error("There is no route named " + name); - } - - var segments = route.segments; - - for (var i = 0, l = segments.length; i < l; i++) { - var segment = segments[i]; - - if (segment instanceof EpsilonSegment) { - continue; - } - - output += "/"; - output += segment.generate(params); - } - - if (output.charAt(0) !== '/') { - output = '/' + output; - } - - if (params && params.queryParams) { - output += this.generateQueryString(params.queryParams, route.handlers); - } - - return output; - }, - - generateQueryString: function (params, handlers) { - var pairs = []; - var keys = []; - for (var key in params) { - if (params.hasOwnProperty(key)) { - keys.push(key); - } - } - keys.sort(); - for (var i = 0, len = keys.length; i < len; i++) { - key = keys[i]; - var value = params[key]; - if (value == null) { - continue; - } - var pair = encodeURIComponent(key); - if (isArray(value)) { - for (var j = 0, l = value.length; j < l; j++) { - var arrayPair = key + '[]' + '=' + encodeURIComponent(value[j]); - pairs.push(arrayPair); - } - } else { - pair += "=" + encodeURIComponent(value); - pairs.push(pair); - } - } - - if (pairs.length === 0) { - return ''; - } - - return "?" + pairs.join("&"); - }, - - parseQueryString: function (queryString) { - var pairs = queryString.split("&"), - queryParams = {}; - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i].split('='), - key = decodeQueryParamPart(pair[0]), - keyLength = key.length, - isArray = false, - value; - if (pair.length === 1) { - value = 'true'; - } else { - //Handle arrays - if (keyLength > 2 && key.slice(keyLength - 2) === '[]') { - isArray = true; - key = key.slice(0, keyLength - 2); - if (!queryParams[key]) { - queryParams[key] = []; - } - } - value = pair[1] ? decodeQueryParamPart(pair[1]) : ''; - } - if (isArray) { - queryParams[key].push(value); - } else { - queryParams[key] = value; - } - } - return queryParams; - }, - - recognize: function (path) { - var states = [this.rootState], - pathLen, - i, - l, - queryStart, - queryParams = {}, - isSlashDropped = false; - - queryStart = path.indexOf('?'); - if (queryStart !== -1) { - var queryString = path.substr(queryStart + 1, path.length); - path = path.substr(0, queryStart); - queryParams = this.parseQueryString(queryString); - } - - path = decodeURI(path); - - // DEBUG GROUP path - - if (path.charAt(0) !== "/") { - path = "/" + path; - } - - pathLen = path.length; - if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { - path = path.substr(0, pathLen - 1); - isSlashDropped = true; - } - - for (i = 0, l = path.length; i < l; i++) { - states = recognizeChar(states, path.charAt(i)); - if (!states.length) { - break; - } - } - - // END DEBUG GROUP - - var solutions = []; - for (i = 0, l = states.length; i < l; i++) { - if (states[i].handlers) { - solutions.push(states[i]); - } - } - - states = sortSolutions(solutions); - - var state = solutions[0]; - - if (state && state.handlers) { - // if a trailing slash was dropped and a star segment is the last segment - // specified, put the trailing slash back - if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") { - path = path + "/"; - } - return findHandler(state, path, queryParams); - } - } - }; - - RouteRecognizer.prototype.map = _routeRecognizerDsl.default; - - RouteRecognizer.VERSION = '0.1.5'; - - exports.default = RouteRecognizer; -}); -enifed('router/handler-info/factory', ['exports', 'router/handler-info/resolved-handler-info', 'router/handler-info/unresolved-handler-info-by-object', 'router/handler-info/unresolved-handler-info-by-param'], function (exports, _routerHandlerInfoResolvedHandlerInfo, _routerHandlerInfoUnresolvedHandlerInfoByObject, _routerHandlerInfoUnresolvedHandlerInfoByParam) { - 'use strict'; - - handlerInfoFactory.klasses = { - resolved: _routerHandlerInfoResolvedHandlerInfo.default, - param: _routerHandlerInfoUnresolvedHandlerInfoByParam.default, - object: _routerHandlerInfoUnresolvedHandlerInfoByObject.default - }; - - function handlerInfoFactory(name, props) { - var Ctor = handlerInfoFactory.klasses[name], - handlerInfo = new Ctor(props || {}); - handlerInfo.factory = handlerInfoFactory; - return handlerInfo; - } - - exports.default = handlerInfoFactory; -}); -enifed('router/handler-info/resolved-handler-info', ['exports', 'router/handler-info', 'router/utils', 'rsvp/promise'], function (exports, _routerHandlerInfo, _routerUtils, _rsvpPromise) { - 'use strict'; - - var ResolvedHandlerInfo = _routerUtils.subclass(_routerHandlerInfo.default, { - resolve: function (shouldContinue, payload) { - // A ResolvedHandlerInfo just resolved with itself. - if (payload && payload.resolvedModels) { - payload.resolvedModels[this.name] = this.context; - } - return _rsvpPromise.default.resolve(this, this.promiseLabel("Resolve")); - }, - - getUnresolved: function () { - return this.factory('param', { - name: this.name, - handler: this.handler, - params: this.params - }); - }, - - isResolved: true - }); - - exports.default = ResolvedHandlerInfo; -}); -enifed('router/handler-info/unresolved-handler-info-by-object', ['exports', 'router/handler-info', 'router/utils', 'rsvp/promise'], function (exports, _routerHandlerInfo, _routerUtils, _rsvpPromise) { - 'use strict'; - - var UnresolvedHandlerInfoByObject = _routerUtils.subclass(_routerHandlerInfo.default, { - getModel: function (payload) { - this.log(payload, this.name + ": resolving provided model"); - return _rsvpPromise.default.resolve(this.context); - }, - - initialize: function (props) { - this.names = props.names || []; - this.context = props.context; - }, - - /** - @private - Serializes a handler using its custom `serialize` method or - by a default that looks up the expected property name from - the dynamic segment. - @param {Object} model the model to be serialized for this handler - */ - serialize: function (_model) { - var model = _model || this.context, - names = this.names, - handler = this.handler; - - var object = {}; - if (_routerUtils.isParam(model)) { - object[names[0]] = model; - return object; - } - - // Use custom serialize if it exists. - if (handler.serialize) { - return handler.serialize(model, names); - } - - if (names.length !== 1) { - return; - } - - var name = names[0]; - - if (/_id$/.test(name)) { - object[name] = model.id; - } else { - object[name] = model; - } - return object; - } - }); - - exports.default = UnresolvedHandlerInfoByObject; -}); -enifed('router/handler-info/unresolved-handler-info-by-param', ['exports', 'router/handler-info', 'router/utils'], function (exports, _routerHandlerInfo, _routerUtils) { - 'use strict'; - - // Generated by URL transitions and non-dynamic route segments in named Transitions. - var UnresolvedHandlerInfoByParam = _routerUtils.subclass(_routerHandlerInfo.default, { - initialize: function (props) { - this.params = props.params || {}; - }, - - getModel: function (payload) { - var fullParams = this.params; - if (payload && payload.queryParams) { - fullParams = {}; - _routerUtils.merge(fullParams, this.params); - fullParams.queryParams = payload.queryParams; - } - - var handler = this.handler; - var hookName = _routerUtils.resolveHook(handler, 'deserialize') || _routerUtils.resolveHook(handler, 'model'); - - return this.runSharedModelHook(payload, hookName, [fullParams]); - } - }); - - exports.default = UnresolvedHandlerInfoByParam; -}); -enifed('router/handler-info', ['exports', 'router/utils', 'rsvp/promise'], function (exports, _routerUtils, _rsvpPromise) { - 'use strict'; - - function HandlerInfo(_props) { - var props = _props || {}; - _routerUtils.merge(this, props); - this.initialize(props); - } - - HandlerInfo.prototype = { - name: null, - handler: null, - params: null, - context: null, - - // Injected by the handler info factory. - factory: null, - - initialize: function () {}, - - log: function (payload, message) { - if (payload.log) { - payload.log(this.name + ': ' + message); - } - }, - - promiseLabel: function (label) { - return _routerUtils.promiseLabel("'" + this.name + "' " + label); - }, - - getUnresolved: function () { - return this; - }, - - serialize: function () { - return this.params || {}; - }, - - resolve: function (shouldContinue, payload) { - var checkForAbort = _routerUtils.bind(this, this.checkForAbort, shouldContinue), - beforeModel = _routerUtils.bind(this, this.runBeforeModelHook, payload), - model = _routerUtils.bind(this, this.getModel, payload), - afterModel = _routerUtils.bind(this, this.runAfterModelHook, payload), - becomeResolved = _routerUtils.bind(this, this.becomeResolved, payload); - - return _rsvpPromise.default.resolve(undefined, this.promiseLabel("Start handler")).then(checkForAbort, null, this.promiseLabel("Check for abort")).then(beforeModel, null, this.promiseLabel("Before model")).then(checkForAbort, null, this.promiseLabel("Check if aborted during 'beforeModel' hook")).then(model, null, this.promiseLabel("Model")).then(checkForAbort, null, this.promiseLabel("Check if aborted in 'model' hook")).then(afterModel, null, this.promiseLabel("After model")).then(checkForAbort, null, this.promiseLabel("Check if aborted in 'afterModel' hook")).then(becomeResolved, null, this.promiseLabel("Become resolved")); - }, - - runBeforeModelHook: function (payload) { - if (payload.trigger) { - payload.trigger(true, 'willResolveModel', payload, this.handler); - } - return this.runSharedModelHook(payload, 'beforeModel', []); - }, - - runAfterModelHook: function (payload, resolvedModel) { - // Stash the resolved model on the payload. - // This makes it possible for users to swap out - // the resolved model in afterModel. - var name = this.name; - this.stashResolvedModel(payload, resolvedModel); - - return this.runSharedModelHook(payload, 'afterModel', [resolvedModel]).then(function () { - // Ignore the fulfilled value returned from afterModel. - // Return the value stashed in resolvedModels, which - // might have been swapped out in afterModel. - return payload.resolvedModels[name]; - }, null, this.promiseLabel("Ignore fulfillment value and return model value")); - }, - - runSharedModelHook: function (payload, hookName, args) { - this.log(payload, "calling " + hookName + " hook"); - - if (this.queryParams) { - args.push(this.queryParams); - } - args.push(payload); - - var result = _routerUtils.applyHook(this.handler, hookName, args); - - if (result && result.isTransition) { - result = null; - } - - return _rsvpPromise.default.resolve(result, this.promiseLabel("Resolve value returned from one of the model hooks")); - }, - - // overridden by subclasses - getModel: null, - - checkForAbort: function (shouldContinue, promiseValue) { - return _rsvpPromise.default.resolve(shouldContinue(), this.promiseLabel("Check for abort")).then(function () { - // We don't care about shouldContinue's resolve value; - // pass along the original value passed to this fn. - return promiseValue; - }, null, this.promiseLabel("Ignore fulfillment value and continue")); - }, - - stashResolvedModel: function (payload, resolvedModel) { - payload.resolvedModels = payload.resolvedModels || {}; - payload.resolvedModels[this.name] = resolvedModel; - }, - - becomeResolved: function (payload, resolvedContext) { - var params = this.serialize(resolvedContext); - - if (payload) { - this.stashResolvedModel(payload, resolvedContext); - payload.params = payload.params || {}; - payload.params[this.name] = params; - } - - return this.factory('resolved', { - context: resolvedContext, - name: this.name, - handler: this.handler, - params: params - }); - }, - - shouldSupercede: function (other) { - // Prefer this newer handlerInfo over `other` if: - // 1) The other one doesn't exist - // 2) The names don't match - // 3) This handler has a context that doesn't match - // the other one (or the other one doesn't have one). - // 4) This handler has parameters that don't match the other. - if (!other) { - return true; - } - - var contextsMatch = other.context === this.context; - return other.name !== this.name || this.hasOwnProperty('context') && !contextsMatch || this.hasOwnProperty('params') && !paramsMatch(this.params, other.params); - } - }; - - function paramsMatch(a, b) { - if (!a ^ !b) { - // Only one is null. - return false; - } - - if (!a) { - // Both must be null. - return true; - } - - // Note: this assumes that both params have the same - // number of keys, but since we're comparing the - // same handlers, they should. - for (var k in a) { - if (a.hasOwnProperty(k) && a[k] !== b[k]) { - return false; - } - } - return true; - } - - exports.default = HandlerInfo; -}); -enifed('router/router', ['exports', 'route-recognizer', 'rsvp/promise', 'router/utils', 'router/transition-state', 'router/transition', 'router/transition-intent/named-transition-intent', 'router/transition-intent/url-transition-intent', 'router/handler-info'], function (exports, _routeRecognizer, _rsvpPromise, _routerUtils, _routerTransitionState, _routerTransition, _routerTransitionIntentNamedTransitionIntent, _routerTransitionIntentUrlTransitionIntent, _routerHandlerInfo) { - 'use strict'; - - var pop = Array.prototype.pop; - - function Router(_options) { - var options = _options || {}; - this.getHandler = options.getHandler || this.getHandler; - this.updateURL = options.updateURL || this.updateURL; - this.replaceURL = options.replaceURL || this.replaceURL; - this.didTransition = options.didTransition || this.didTransition; - this.willTransition = options.willTransition || this.willTransition; - this.delegate = options.delegate || this.delegate; - this.triggerEvent = options.triggerEvent || this.triggerEvent; - this.log = options.log || this.log; - - this.recognizer = new _routeRecognizer.default(); - this.reset(); - } - - function getTransitionByIntent(intent, isIntermediate) { - var wasTransitioning = !!this.activeTransition; - var oldState = wasTransitioning ? this.activeTransition.state : this.state; - var newTransition; - - var newState = intent.applyToState(oldState, this.recognizer, this.getHandler, isIntermediate); - var queryParamChangelist = _routerUtils.getChangelist(oldState.queryParams, newState.queryParams); - - if (handlerInfosEqual(newState.handlerInfos, oldState.handlerInfos)) { - - // This is a no-op transition. See if query params changed. - if (queryParamChangelist) { - newTransition = this.queryParamsTransition(queryParamChangelist, wasTransitioning, oldState, newState); - if (newTransition) { - return newTransition; - } - } - - // No-op. No need to create a new transition. - return this.activeTransition || new _routerTransition.Transition(this); - } - - if (isIntermediate) { - setupContexts(this, newState); - return; - } - - // Create a new transition to the destination route. - newTransition = new _routerTransition.Transition(this, intent, newState); - - // Abort and usurp any previously active transition. - if (this.activeTransition) { - this.activeTransition.abort(); - } - this.activeTransition = newTransition; - - // Transition promises by default resolve with resolved state. - // For our purposes, swap out the promise to resolve - // after the transition has been finalized. - newTransition.promise = newTransition.promise.then(function (result) { - return finalizeTransition(newTransition, result.state); - }, null, _routerUtils.promiseLabel("Settle transition promise when transition is finalized")); - - if (!wasTransitioning) { - notifyExistingHandlers(this, newState, newTransition); - } - - fireQueryParamDidChange(this, newState, queryParamChangelist); - - return newTransition; - } - - Router.prototype = { - - /** - The main entry point into the router. The API is essentially - the same as the `map` method in `route-recognizer`. - This method extracts the String handler at the last `.to()` - call and uses it as the name of the whole route. - @param {Function} callback - */ - map: function (callback) { - this.recognizer.delegate = this.delegate; - - this.recognizer.map(callback, function (recognizer, routes) { - for (var i = routes.length - 1, proceed = true; i >= 0 && proceed; --i) { - var route = routes[i]; - recognizer.add(routes, { as: route.handler }); - proceed = route.path === '/' || route.path === '' || route.handler.slice(-6) === '.index'; - } - }); - }, - - hasRoute: function (route) { - return this.recognizer.hasRoute(route); - }, - - getHandler: function () {}, - - queryParamsTransition: function (changelist, wasTransitioning, oldState, newState) { - var router = this; - - fireQueryParamDidChange(this, newState, changelist); - - if (!wasTransitioning && this.activeTransition) { - // One of the handlers in queryParamsDidChange - // caused a transition. Just return that transition. - return this.activeTransition; - } else { - // Running queryParamsDidChange didn't change anything. - // Just update query params and be on our way. - - // We have to return a noop transition that will - // perform a URL update at the end. This gives - // the user the ability to set the url update - // method (default is replaceState). - var newTransition = new _routerTransition.Transition(this); - newTransition.queryParamsOnly = true; - - oldState.queryParams = finalizeQueryParamChange(this, newState.handlerInfos, newState.queryParams, newTransition); - - newTransition.promise = newTransition.promise.then(function (result) { - updateURL(newTransition, oldState, true); - if (router.didTransition) { - router.didTransition(router.currentHandlerInfos); - } - return result; - }, null, _routerUtils.promiseLabel("Transition complete")); - return newTransition; - } - }, - - // NOTE: this doesn't really belong here, but here - // it shall remain until our ES6 transpiler can - // handle cyclical deps. - transitionByIntent: function (intent, isIntermediate) { - try { - return getTransitionByIntent.apply(this, arguments); - } catch (e) { - return new _routerTransition.Transition(this, intent, null, e); - } - }, - - /** - Clears the current and target route handlers and triggers exit - on each of them starting at the leaf and traversing up through - its ancestors. - */ - reset: function () { - if (this.state) { - _routerUtils.forEach(this.state.handlerInfos.slice().reverse(), function (handlerInfo) { - var handler = handlerInfo.handler; - _routerUtils.callHook(handler, 'exit'); - }); - } - - this.state = new _routerTransitionState.default(); - this.currentHandlerInfos = null; - }, - - activeTransition: null, - - /** - var handler = handlerInfo.handler; - The entry point for handling a change to the URL (usually - via the back and forward button). - Returns an Array of handlers and the parameters associated - with those parameters. - @param {String} url a URL to process - @return {Array} an Array of `[handler, parameter]` tuples - */ - handleURL: function (url) { - // Perform a URL-based transition, but don't change - // the URL afterward, since it already happened. - var args = _routerUtils.slice.call(arguments); - if (url.charAt(0) !== '/') { - args[0] = '/' + url; - } - - return doTransition(this, args).method(null); - }, - - /** - Hook point for updating the URL. - @param {String} url a URL to update to - */ - updateURL: function () { - throw new Error("updateURL is not implemented"); - }, - - /** - Hook point for replacing the current URL, i.e. with replaceState - By default this behaves the same as `updateURL` - @param {String} url a URL to update to - */ - replaceURL: function (url) { - this.updateURL(url); - }, - - /** - Transition into the specified named route. - If necessary, trigger the exit callback on any handlers - that are no longer represented by the target route. - @param {String} name the name of the route - */ - transitionTo: function (name) { - return doTransition(this, arguments); - }, - - intermediateTransitionTo: function (name) { - return doTransition(this, arguments, true); - }, - - refresh: function (pivotHandler) { - var state = this.activeTransition ? this.activeTransition.state : this.state; - var handlerInfos = state.handlerInfos; - var params = {}; - for (var i = 0, len = handlerInfos.length; i < len; ++i) { - var handlerInfo = handlerInfos[i]; - params[handlerInfo.name] = handlerInfo.params || {}; - } - - _routerUtils.log(this, "Starting a refresh transition"); - var intent = new _routerTransitionIntentNamedTransitionIntent.default({ - name: handlerInfos[handlerInfos.length - 1].name, - pivotHandler: pivotHandler || handlerInfos[0].handler, - contexts: [], // TODO collect contexts...? - queryParams: this._changedQueryParams || state.queryParams || {} - }); - - return this.transitionByIntent(intent, false); - }, - - /** - Identical to `transitionTo` except that the current URL will be replaced - if possible. - This method is intended primarily for use with `replaceState`. - @param {String} name the name of the route - */ - replaceWith: function (name) { - return doTransition(this, arguments).method('replace'); - }, - - /** - Take a named route and context objects and generate a - URL. - @param {String} name the name of the route to generate - a URL for - @param {...Object} objects a list of objects to serialize - @return {String} a URL - */ - generate: function (handlerName) { - - var partitionedArgs = _routerUtils.extractQueryParams(_routerUtils.slice.call(arguments, 1)), - suppliedParams = partitionedArgs[0], - queryParams = partitionedArgs[1]; - - // Construct a TransitionIntent with the provided params - // and apply it to the present state of the router. - var intent = new _routerTransitionIntentNamedTransitionIntent.default({ name: handlerName, contexts: suppliedParams }); - var state = intent.applyToState(this.state, this.recognizer, this.getHandler); - var params = {}; - - for (var i = 0, len = state.handlerInfos.length; i < len; ++i) { - var handlerInfo = state.handlerInfos[i]; - var handlerParams = handlerInfo.serialize(); - _routerUtils.merge(params, handlerParams); - } - params.queryParams = queryParams; - - return this.recognizer.generate(handlerName, params); - }, - - applyIntent: function (handlerName, contexts) { - var intent = new _routerTransitionIntentNamedTransitionIntent.default({ - name: handlerName, - contexts: contexts - }); - - var state = this.activeTransition && this.activeTransition.state || this.state; - return intent.applyToState(state, this.recognizer, this.getHandler); - }, - - isActiveIntent: function (handlerName, contexts, queryParams, _state) { - var state = _state || this.state, - targetHandlerInfos = state.handlerInfos, - found = false, - names, - object, - handlerInfo, - handlerObj, - i, - len; - - if (!targetHandlerInfos.length) { - return false; - } - - var targetHandler = targetHandlerInfos[targetHandlerInfos.length - 1].name; - var recogHandlers = this.recognizer.handlersFor(targetHandler); - - var index = 0; - for (len = recogHandlers.length; index < len; ++index) { - handlerInfo = targetHandlerInfos[index]; - if (handlerInfo.name === handlerName) { - break; - } - } - - if (index === recogHandlers.length) { - // The provided route name isn't even in the route hierarchy. - return false; - } - - var testState = new _routerTransitionState.default(); - testState.handlerInfos = targetHandlerInfos.slice(0, index + 1); - recogHandlers = recogHandlers.slice(0, index + 1); - - var intent = new _routerTransitionIntentNamedTransitionIntent.default({ - name: targetHandler, - contexts: contexts - }); - - var newState = intent.applyToHandlers(testState, recogHandlers, this.getHandler, targetHandler, true, true); - - var handlersEqual = handlerInfosEqual(newState.handlerInfos, testState.handlerInfos); - if (!queryParams || !handlersEqual) { - return handlersEqual; - } - - // Get a hash of QPs that will still be active on new route - var activeQPsOnNewHandler = {}; - _routerUtils.merge(activeQPsOnNewHandler, queryParams); - - var activeQueryParams = state.queryParams; - for (var key in activeQueryParams) { - if (activeQueryParams.hasOwnProperty(key) && activeQPsOnNewHandler.hasOwnProperty(key)) { - activeQPsOnNewHandler[key] = activeQueryParams[key]; - } - } - - return handlersEqual && !_routerUtils.getChangelist(activeQPsOnNewHandler, queryParams); - }, - - isActive: function (handlerName) { - var partitionedArgs = _routerUtils.extractQueryParams(_routerUtils.slice.call(arguments, 1)); - return this.isActiveIntent(handlerName, partitionedArgs[0], partitionedArgs[1]); - }, - - trigger: function (name) { - var args = _routerUtils.slice.call(arguments); - _routerUtils.trigger(this, this.currentHandlerInfos, false, args); - }, - - /** - Hook point for logging transition status updates. - @param {String} message The message to log. - */ - log: null - }; - - /** - @private - - Fires queryParamsDidChange event - */ - function fireQueryParamDidChange(router, newState, queryParamChangelist) { - // If queryParams changed trigger event - if (queryParamChangelist) { - - // This is a little hacky but we need some way of storing - // changed query params given that no activeTransition - // is guaranteed to have occurred. - router._changedQueryParams = queryParamChangelist.all; - _routerUtils.trigger(router, newState.handlerInfos, true, ['queryParamsDidChange', queryParamChangelist.changed, queryParamChangelist.all, queryParamChangelist.removed]); - router._changedQueryParams = null; - } - } - - /** - @private - - Takes an Array of `HandlerInfo`s, figures out which ones are - exiting, entering, or changing contexts, and calls the - proper handler hooks. - - For example, consider the following tree of handlers. Each handler is - followed by the URL segment it handles. - - ``` - |~index ("/") - | |~posts ("/posts") - | | |-showPost ("/:id") - | | |-newPost ("/new") - | | |-editPost ("/edit") - | |~about ("/about/:id") - ``` - - Consider the following transitions: - - 1. A URL transition to `/posts/1`. - 1. Triggers the `*model` callbacks on the - `index`, `posts`, and `showPost` handlers - 2. Triggers the `enter` callback on the same - 3. Triggers the `setup` callback on the same - 2. A direct transition to `newPost` - 1. Triggers the `exit` callback on `showPost` - 2. Triggers the `enter` callback on `newPost` - 3. Triggers the `setup` callback on `newPost` - 3. A direct transition to `about` with a specified - context object - 1. Triggers the `exit` callback on `newPost` - and `posts` - 2. Triggers the `serialize` callback on `about` - 3. Triggers the `enter` callback on `about` - 4. Triggers the `setup` callback on `about` - - @param {Router} transition - @param {TransitionState} newState - */ - function setupContexts(router, newState, transition) { - var partition = partitionHandlers(router.state, newState); - var i, l, handler; - - for (i = 0, l = partition.exited.length; i < l; i++) { - handler = partition.exited[i].handler; - delete handler.context; - - _routerUtils.callHook(handler, 'reset', true, transition); - _routerUtils.callHook(handler, 'exit', transition); - } - - var oldState = router.oldState = router.state; - router.state = newState; - var currentHandlerInfos = router.currentHandlerInfos = partition.unchanged.slice(); - - try { - for (i = 0, l = partition.reset.length; i < l; i++) { - handler = partition.reset[i].handler; - _routerUtils.callHook(handler, 'reset', false, transition); - } - - for (i = 0, l = partition.updatedContext.length; i < l; i++) { - handlerEnteredOrUpdated(currentHandlerInfos, partition.updatedContext[i], false, transition); - } - - for (i = 0, l = partition.entered.length; i < l; i++) { - handlerEnteredOrUpdated(currentHandlerInfos, partition.entered[i], true, transition); - } - } catch (e) { - router.state = oldState; - router.currentHandlerInfos = oldState.handlerInfos; - throw e; - } - - router.state.queryParams = finalizeQueryParamChange(router, currentHandlerInfos, newState.queryParams, transition); - } - - /** - @private - - Helper method used by setupContexts. Handles errors or redirects - that may happen in enter/setup. - */ - function handlerEnteredOrUpdated(currentHandlerInfos, handlerInfo, enter, transition) { - - var handler = handlerInfo.handler, - context = handlerInfo.context; - - if (enter) { - _routerUtils.callHook(handler, 'enter', transition); - } - if (transition && transition.isAborted) { - throw new _routerTransition.TransitionAborted(); - } - - handler.context = context; - _routerUtils.callHook(handler, 'contextDidChange'); - - _routerUtils.callHook(handler, 'setup', context, transition); - if (transition && transition.isAborted) { - throw new _routerTransition.TransitionAborted(); - } - - currentHandlerInfos.push(handlerInfo); - - return true; - } - - /** - @private - - This function is called when transitioning from one URL to - another to determine which handlers are no longer active, - which handlers are newly active, and which handlers remain - active but have their context changed. - - Take a list of old handlers and new handlers and partition - them into four buckets: - - * unchanged: the handler was active in both the old and - new URL, and its context remains the same - * updated context: the handler was active in both the - old and new URL, but its context changed. The handler's - `setup` method, if any, will be called with the new - context. - * exited: the handler was active in the old URL, but is - no longer active. - * entered: the handler was not active in the old URL, but - is now active. - - The PartitionedHandlers structure has four fields: - - * `updatedContext`: a list of `HandlerInfo` objects that - represent handlers that remain active but have a changed - context - * `entered`: a list of `HandlerInfo` objects that represent - handlers that are newly active - * `exited`: a list of `HandlerInfo` objects that are no - longer active. - * `unchanged`: a list of `HanderInfo` objects that remain active. - - @param {Array[HandlerInfo]} oldHandlers a list of the handler - information for the previous URL (or `[]` if this is the - first handled transition) - @param {Array[HandlerInfo]} newHandlers a list of the handler - information for the new URL - - @return {Partition} - */ - function partitionHandlers(oldState, newState) { - var oldHandlers = oldState.handlerInfos; - var newHandlers = newState.handlerInfos; - - var handlers = { - updatedContext: [], - exited: [], - entered: [], - unchanged: [] - }; - - var handlerChanged, - contextChanged = false, - i, - l; - - for (i = 0, l = newHandlers.length; i < l; i++) { - var oldHandler = oldHandlers[i], - newHandler = newHandlers[i]; - - if (!oldHandler || oldHandler.handler !== newHandler.handler) { - handlerChanged = true; - } - - if (handlerChanged) { - handlers.entered.push(newHandler); - if (oldHandler) { - handlers.exited.unshift(oldHandler); - } - } else if (contextChanged || oldHandler.context !== newHandler.context) { - contextChanged = true; - handlers.updatedContext.push(newHandler); - } else { - handlers.unchanged.push(oldHandler); - } - } - - for (i = newHandlers.length, l = oldHandlers.length; i < l; i++) { - handlers.exited.unshift(oldHandlers[i]); - } - - handlers.reset = handlers.updatedContext.slice(); - handlers.reset.reverse(); - - return handlers; - } - - function updateURL(transition, state, inputUrl) { - var urlMethod = transition.urlMethod; - - if (!urlMethod) { - return; - } - - var router = transition.router, - handlerInfos = state.handlerInfos, - handlerName = handlerInfos[handlerInfos.length - 1].name, - params = {}; - - for (var i = handlerInfos.length - 1; i >= 0; --i) { - var handlerInfo = handlerInfos[i]; - _routerUtils.merge(params, handlerInfo.params); - if (handlerInfo.handler.inaccessibleByURL) { - urlMethod = null; - } - } - - if (urlMethod) { - params.queryParams = transition._visibleQueryParams || state.queryParams; - var url = router.recognizer.generate(handlerName, params); - - if (urlMethod === 'replace') { - router.replaceURL(url); - } else { - router.updateURL(url); - } - } - } - - /** - @private - - Updates the URL (if necessary) and calls `setupContexts` - to update the router's array of `currentHandlerInfos`. - */ - function finalizeTransition(transition, newState) { - - try { - _routerUtils.log(transition.router, transition.sequence, "Resolved all models on destination route; finalizing transition."); - - var router = transition.router, - handlerInfos = newState.handlerInfos, - seq = transition.sequence; - - // Run all the necessary enter/setup/exit hooks - setupContexts(router, newState, transition); - - // Check if a redirect occurred in enter/setup - if (transition.isAborted) { - // TODO: cleaner way? distinguish b/w targetHandlerInfos? - router.state.handlerInfos = router.currentHandlerInfos; - return _rsvpPromise.default.reject(_routerTransition.logAbort(transition)); - } - - updateURL(transition, newState, transition.intent.url); - - transition.isActive = false; - router.activeTransition = null; - - _routerUtils.trigger(router, router.currentHandlerInfos, true, ['didTransition']); - - if (router.didTransition) { - router.didTransition(router.currentHandlerInfos); - } - - _routerUtils.log(router, transition.sequence, "TRANSITION COMPLETE."); - - // Resolve with the final handler. - return handlerInfos[handlerInfos.length - 1].handler; - } catch (e) { - if (!(e instanceof _routerTransition.TransitionAborted)) { - //var erroneousHandler = handlerInfos.pop(); - var infos = transition.state.handlerInfos; - transition.trigger(true, 'error', e, transition, infos[infos.length - 1].handler); - transition.abort(); - } - - throw e; - } - } - - /** - @private - - Begins and returns a Transition based on the provided - arguments. Accepts arguments in the form of both URL - transitions and named transitions. - - @param {Router} router - @param {Array[Object]} args arguments passed to transitionTo, - replaceWith, or handleURL - */ - function doTransition(router, args, isIntermediate) { - // Normalize blank transitions to root URL transitions. - var name = args[0] || '/'; - - var lastArg = args[args.length - 1]; - var queryParams = {}; - if (lastArg && lastArg.hasOwnProperty('queryParams')) { - queryParams = pop.call(args).queryParams; - } - - var intent; - if (args.length === 0) { - - _routerUtils.log(router, "Updating query params"); - - // A query param update is really just a transition - // into the route you're already on. - var handlerInfos = router.state.handlerInfos; - intent = new _routerTransitionIntentNamedTransitionIntent.default({ - name: handlerInfos[handlerInfos.length - 1].name, - contexts: [], - queryParams: queryParams - }); - } else if (name.charAt(0) === '/') { - - _routerUtils.log(router, "Attempting URL transition to " + name); - intent = new _routerTransitionIntentUrlTransitionIntent.default({ url: name }); - } else { - - _routerUtils.log(router, "Attempting transition to " + name); - intent = new _routerTransitionIntentNamedTransitionIntent.default({ - name: args[0], - contexts: _routerUtils.slice.call(args, 1), - queryParams: queryParams - }); - } - - return router.transitionByIntent(intent, isIntermediate); - } - - function handlerInfosEqual(handlerInfos, otherHandlerInfos) { - if (handlerInfos.length !== otherHandlerInfos.length) { - return false; - } - - for (var i = 0, len = handlerInfos.length; i < len; ++i) { - if (handlerInfos[i] !== otherHandlerInfos[i]) { - return false; - } - } - return true; - } - - function finalizeQueryParamChange(router, resolvedHandlers, newQueryParams, transition) { - // We fire a finalizeQueryParamChange event which - // gives the new route hierarchy a chance to tell - // us which query params it's consuming and what - // their final values are. If a query param is - // no longer consumed in the final route hierarchy, - // its serialized segment will be removed - // from the URL. - - for (var k in newQueryParams) { - if (newQueryParams.hasOwnProperty(k) && newQueryParams[k] === null) { - delete newQueryParams[k]; - } - } - - var finalQueryParamsArray = []; - _routerUtils.trigger(router, resolvedHandlers, true, ['finalizeQueryParamChange', newQueryParams, finalQueryParamsArray, transition]); - - if (transition) { - transition._visibleQueryParams = {}; - } - - var finalQueryParams = {}; - for (var i = 0, len = finalQueryParamsArray.length; i < len; ++i) { - var qp = finalQueryParamsArray[i]; - finalQueryParams[qp.key] = qp.value; - if (transition && qp.visible !== false) { - transition._visibleQueryParams[qp.key] = qp.value; - } - } - return finalQueryParams; - } - - function notifyExistingHandlers(router, newState, newTransition) { - var oldHandlers = router.state.handlerInfos, - changing = [], - leavingIndex = null, - leaving, - leavingChecker, - i, - oldHandlerLen, - oldHandler, - newHandler; - - oldHandlerLen = oldHandlers.length; - for (i = 0; i < oldHandlerLen; i++) { - oldHandler = oldHandlers[i]; - newHandler = newState.handlerInfos[i]; - - if (!newHandler || oldHandler.name !== newHandler.name) { - leavingIndex = i; - break; - } - - if (!newHandler.isResolved) { - changing.push(oldHandler); - } - } - - if (leavingIndex !== null) { - leaving = oldHandlers.slice(leavingIndex, oldHandlerLen); - leavingChecker = function (name) { - for (var h = 0, len = leaving.length; h < len; h++) { - if (leaving[h].name === name) { - return true; - } - } - return false; - }; - } - - _routerUtils.trigger(router, oldHandlers, true, ['willTransition', newTransition]); - - if (router.willTransition) { - router.willTransition(oldHandlers, newState.handlerInfos, newTransition); - } - } - - exports.default = Router; -}); -enifed('router/transition-intent/named-transition-intent', ['exports', 'router/transition-intent', 'router/transition-state', 'router/handler-info/factory', 'router/utils'], function (exports, _routerTransitionIntent, _routerTransitionState, _routerHandlerInfoFactory, _routerUtils) { - 'use strict'; - - exports.default = _routerUtils.subclass(_routerTransitionIntent.default, { - name: null, - pivotHandler: null, - contexts: null, - queryParams: null, - - initialize: function (props) { - this.name = props.name; - this.pivotHandler = props.pivotHandler; - this.contexts = props.contexts || []; - this.queryParams = props.queryParams; - }, - - applyToState: function (oldState, recognizer, getHandler, isIntermediate) { - - var partitionedArgs = _routerUtils.extractQueryParams([this.name].concat(this.contexts)), - pureArgs = partitionedArgs[0], - queryParams = partitionedArgs[1], - handlers = recognizer.handlersFor(pureArgs[0]); - - var targetRouteName = handlers[handlers.length - 1].handler; - - return this.applyToHandlers(oldState, handlers, getHandler, targetRouteName, isIntermediate); - }, - - applyToHandlers: function (oldState, handlers, getHandler, targetRouteName, isIntermediate, checkingIfActive) { - - var i, len; - var newState = new _routerTransitionState.default(); - var objects = this.contexts.slice(0); - - var invalidateIndex = handlers.length; - - // Pivot handlers are provided for refresh transitions - if (this.pivotHandler) { - for (i = 0, len = handlers.length; i < len; ++i) { - if (getHandler(handlers[i].handler) === this.pivotHandler) { - invalidateIndex = i; - break; - } - } - } - - var pivotHandlerFound = !this.pivotHandler; - - for (i = handlers.length - 1; i >= 0; --i) { - var result = handlers[i]; - var name = result.handler; - var handler = getHandler(name); - - var oldHandlerInfo = oldState.handlerInfos[i]; - var newHandlerInfo = null; - - if (result.names.length > 0) { - if (i >= invalidateIndex) { - newHandlerInfo = this.createParamHandlerInfo(name, handler, result.names, objects, oldHandlerInfo); - } else { - newHandlerInfo = this.getHandlerInfoForDynamicSegment(name, handler, result.names, objects, oldHandlerInfo, targetRouteName, i); - } - } else { - // This route has no dynamic segment. - // Therefore treat as a param-based handlerInfo - // with empty params. This will cause the `model` - // hook to be called with empty params, which is desirable. - newHandlerInfo = this.createParamHandlerInfo(name, handler, result.names, objects, oldHandlerInfo); - } - - if (checkingIfActive) { - // If we're performing an isActive check, we want to - // serialize URL params with the provided context, but - // ignore mismatches between old and new context. - newHandlerInfo = newHandlerInfo.becomeResolved(null, newHandlerInfo.context); - var oldContext = oldHandlerInfo && oldHandlerInfo.context; - if (result.names.length > 0 && newHandlerInfo.context === oldContext) { - // If contexts match in isActive test, assume params also match. - // This allows for flexibility in not requiring that every last - // handler provide a `serialize` method - newHandlerInfo.params = oldHandlerInfo && oldHandlerInfo.params; - } - newHandlerInfo.context = oldContext; - } - - var handlerToUse = oldHandlerInfo; - if (i >= invalidateIndex || newHandlerInfo.shouldSupercede(oldHandlerInfo)) { - invalidateIndex = Math.min(i, invalidateIndex); - handlerToUse = newHandlerInfo; - } - - if (isIntermediate && !checkingIfActive) { - handlerToUse = handlerToUse.becomeResolved(null, handlerToUse.context); - } - - newState.handlerInfos.unshift(handlerToUse); - } - - if (objects.length > 0) { - throw new Error("More context objects were passed than there are dynamic segments for the route: " + targetRouteName); - } - - if (!isIntermediate) { - this.invalidateChildren(newState.handlerInfos, invalidateIndex); - } - - _routerUtils.merge(newState.queryParams, this.queryParams || {}); - - return newState; - }, - - invalidateChildren: function (handlerInfos, invalidateIndex) { - for (var i = invalidateIndex, l = handlerInfos.length; i < l; ++i) { - var handlerInfo = handlerInfos[i]; - handlerInfos[i] = handlerInfos[i].getUnresolved(); - } - }, - - getHandlerInfoForDynamicSegment: function (name, handler, names, objects, oldHandlerInfo, targetRouteName, i) { - - var numNames = names.length; - var objectToUse; - if (objects.length > 0) { - - // Use the objects provided for this transition. - objectToUse = objects[objects.length - 1]; - if (_routerUtils.isParam(objectToUse)) { - return this.createParamHandlerInfo(name, handler, names, objects, oldHandlerInfo); - } else { - objects.pop(); - } - } else if (oldHandlerInfo && oldHandlerInfo.name === name) { - // Reuse the matching oldHandlerInfo - return oldHandlerInfo; - } else { - if (this.preTransitionState) { - var preTransitionHandlerInfo = this.preTransitionState.handlerInfos[i]; - objectToUse = preTransitionHandlerInfo && preTransitionHandlerInfo.context; - } else { - // Ideally we should throw this error to provide maximal - // information to the user that not enough context objects - // were provided, but this proves too cumbersome in Ember - // in cases where inner template helpers are evaluated - // before parent helpers un-render, in which cases this - // error somewhat prematurely fires. - //throw new Error("Not enough context objects were provided to complete a transition to " + targetRouteName + ". Specifically, the " + name + " route needs an object that can be serialized into its dynamic URL segments [" + names.join(', ') + "]"); - return oldHandlerInfo; - } - } - - return _routerHandlerInfoFactory.default('object', { - name: name, - handler: handler, - context: objectToUse, - names: names - }); - }, - - createParamHandlerInfo: function (name, handler, names, objects, oldHandlerInfo) { - var params = {}; - - // Soak up all the provided string/numbers - var numNames = names.length; - while (numNames--) { - - // Only use old params if the names match with the new handler - var oldParams = oldHandlerInfo && name === oldHandlerInfo.name && oldHandlerInfo.params || {}; - - var peek = objects[objects.length - 1]; - var paramName = names[numNames]; - if (_routerUtils.isParam(peek)) { - params[paramName] = "" + objects.pop(); - } else { - // If we're here, this means only some of the params - // were string/number params, so try and use a param - // value from a previous handler. - if (oldParams.hasOwnProperty(paramName)) { - params[paramName] = oldParams[paramName]; - } else { - throw new Error("You didn't provide enough string/numeric parameters to satisfy all of the dynamic segments for route " + name); - } - } - } - - return _routerHandlerInfoFactory.default('param', { - name: name, - handler: handler, - params: params - }); - } - }); -}); -enifed('router/transition-intent/url-transition-intent', ['exports', 'router/transition-intent', 'router/transition-state', 'router/handler-info/factory', 'router/utils', 'router/unrecognized-url-error'], function (exports, _routerTransitionIntent, _routerTransitionState, _routerHandlerInfoFactory, _routerUtils, _routerUnrecognizedUrlError) { - 'use strict'; - - exports.default = _routerUtils.subclass(_routerTransitionIntent.default, { - url: null, - - initialize: function (props) { - this.url = props.url; - }, - - applyToState: function (oldState, recognizer, getHandler) { - var newState = new _routerTransitionState.default(); - - var results = recognizer.recognize(this.url), - queryParams = {}, - i, - len; - - if (!results) { - throw new _routerUnrecognizedUrlError.default(this.url); - } - - var statesDiffer = false; - - for (i = 0, len = results.length; i < len; ++i) { - var result = results[i]; - var name = result.handler; - var handler = getHandler(name); - - if (handler.inaccessibleByURL) { - throw new _routerUnrecognizedUrlError.default(this.url); - } - - var newHandlerInfo = _routerHandlerInfoFactory.default('param', { - name: name, - handler: handler, - params: result.params - }); - - var oldHandlerInfo = oldState.handlerInfos[i]; - if (statesDiffer || newHandlerInfo.shouldSupercede(oldHandlerInfo)) { - statesDiffer = true; - newState.handlerInfos[i] = newHandlerInfo; - } else { - newState.handlerInfos[i] = oldHandlerInfo; - } - } - - _routerUtils.merge(newState.queryParams, results.queryParams); - - return newState; - } - }); -}); -enifed('router/transition-intent', ['exports', 'router/utils'], function (exports, _routerUtils) { - 'use strict'; - - function TransitionIntent(props) { - this.initialize(props); - - // TODO: wat - this.data = this.data || {}; - } - - TransitionIntent.prototype = { - initialize: null, - applyToState: null - }; - - exports.default = TransitionIntent; -}); -enifed('router/transition-state', ['exports', 'router/handler-info', 'router/utils', 'rsvp/promise'], function (exports, _routerHandlerInfo, _routerUtils, _rsvpPromise) { - 'use strict'; - - function TransitionState(other) { - this.handlerInfos = []; - this.queryParams = {}; - this.params = {}; - } - - TransitionState.prototype = { - handlerInfos: null, - queryParams: null, - params: null, - - promiseLabel: function (label) { - var targetName = ''; - _routerUtils.forEach(this.handlerInfos, function (handlerInfo) { - if (targetName !== '') { - targetName += '.'; - } - targetName += handlerInfo.name; - }); - return _routerUtils.promiseLabel("'" + targetName + "': " + label); - }, - - resolve: function (shouldContinue, payload) { - var self = this; - // First, calculate params for this state. This is useful - // information to provide to the various route hooks. - var params = this.params; - _routerUtils.forEach(this.handlerInfos, function (handlerInfo) { - params[handlerInfo.name] = handlerInfo.params || {}; - }); - - payload = payload || {}; - payload.resolveIndex = 0; - - var currentState = this; - var wasAborted = false; - - // The prelude RSVP.resolve() asyncs us into the promise land. - return _rsvpPromise.default.resolve(null, this.promiseLabel("Start transition")).then(resolveOneHandlerInfo, null, this.promiseLabel('Resolve handler'))['catch'](handleError, this.promiseLabel('Handle error')); - - function innerShouldContinue() { - return _rsvpPromise.default.resolve(shouldContinue(), currentState.promiseLabel("Check if should continue"))['catch'](function (reason) { - // We distinguish between errors that occurred - // during resolution (e.g. beforeModel/model/afterModel), - // and aborts due to a rejecting promise from shouldContinue(). - wasAborted = true; - return _rsvpPromise.default.reject(reason); - }, currentState.promiseLabel("Handle abort")); - } - - function handleError(error) { - // This is the only possible - // reject value of TransitionState#resolve - var handlerInfos = currentState.handlerInfos; - var errorHandlerIndex = payload.resolveIndex >= handlerInfos.length ? handlerInfos.length - 1 : payload.resolveIndex; - return _rsvpPromise.default.reject({ - error: error, - handlerWithError: currentState.handlerInfos[errorHandlerIndex].handler, - wasAborted: wasAborted, - state: currentState - }); - } - - function proceed(resolvedHandlerInfo) { - var wasAlreadyResolved = currentState.handlerInfos[payload.resolveIndex].isResolved; - - // Swap the previously unresolved handlerInfo with - // the resolved handlerInfo - currentState.handlerInfos[payload.resolveIndex++] = resolvedHandlerInfo; - - if (!wasAlreadyResolved) { - // Call the redirect hook. The reason we call it here - // vs. afterModel is so that redirects into child - // routes don't re-run the model hooks for this - // already-resolved route. - var handler = resolvedHandlerInfo.handler; - _routerUtils.callHook(handler, 'redirect', resolvedHandlerInfo.context, payload); - } - - // Proceed after ensuring that the redirect hook - // didn't abort this transition by transitioning elsewhere. - return innerShouldContinue().then(resolveOneHandlerInfo, null, currentState.promiseLabel('Resolve handler')); - } - - function resolveOneHandlerInfo() { - if (payload.resolveIndex === currentState.handlerInfos.length) { - // This is is the only possible - // fulfill value of TransitionState#resolve - return { - error: null, - state: currentState - }; - } - - var handlerInfo = currentState.handlerInfos[payload.resolveIndex]; - - return handlerInfo.resolve(innerShouldContinue, payload).then(proceed, null, currentState.promiseLabel('Proceed')); - } - } - }; - - exports.default = TransitionState; -}); -enifed('router/transition', ['exports', 'rsvp/promise', 'router/handler-info', 'router/utils'], function (exports, _rsvpPromise, _routerHandlerInfo, _routerUtils) { - 'use strict'; - - /** - @private - - A Transition is a thennable (a promise-like object) that represents - an attempt to transition to another route. It can be aborted, either - explicitly via `abort` or by attempting another transition while a - previous one is still underway. An aborted transition can also - be `retry()`d later. - */ - function Transition(router, intent, state, error) { - var transition = this; - this.state = state || router.state; - this.intent = intent; - this.router = router; - this.data = this.intent && this.intent.data || {}; - this.resolvedModels = {}; - this.queryParams = {}; - - if (error) { - this.promise = _rsvpPromise.default.reject(error); - this.error = error; - return; - } - - if (state) { - this.params = state.params; - this.queryParams = state.queryParams; - this.handlerInfos = state.handlerInfos; - - var len = state.handlerInfos.length; - if (len) { - this.targetName = state.handlerInfos[len - 1].name; - } - - for (var i = 0; i < len; ++i) { - var handlerInfo = state.handlerInfos[i]; - - // TODO: this all seems hacky - if (!handlerInfo.isResolved) { - break; - } - this.pivotHandler = handlerInfo.handler; - } - - this.sequence = Transition.currentSequence++; - this.promise = state.resolve(checkForAbort, this)['catch'](function (result) { - if (result.wasAborted || transition.isAborted) { - return _rsvpPromise.default.reject(logAbort(transition)); - } else { - transition.trigger('error', result.error, transition, result.handlerWithError); - transition.abort(); - return _rsvpPromise.default.reject(result.error); - } - }, _routerUtils.promiseLabel('Handle Abort')); - } else { - this.promise = _rsvpPromise.default.resolve(this.state); - this.params = {}; - } - - function checkForAbort() { - if (transition.isAborted) { - return _rsvpPromise.default.reject(undefined, _routerUtils.promiseLabel("Transition aborted - reject")); - } - } - } - - Transition.currentSequence = 0; - - Transition.prototype = { - targetName: null, - urlMethod: 'update', - intent: null, - params: null, - pivotHandler: null, - resolveIndex: 0, - handlerInfos: null, - resolvedModels: null, - isActive: true, - state: null, - queryParamsOnly: false, - - isTransition: true, - - isExiting: function (handler) { - var handlerInfos = this.handlerInfos; - for (var i = 0, len = handlerInfos.length; i < len; ++i) { - var handlerInfo = handlerInfos[i]; - if (handlerInfo.name === handler || handlerInfo.handler === handler) { - return false; - } - } - return true; - }, - - /** - @public - The Transition's internal promise. Calling `.then` on this property - is that same as calling `.then` on the Transition object itself, but - this property is exposed for when you want to pass around a - Transition's promise, but not the Transition object itself, since - Transition object can be externally `abort`ed, while the promise - cannot. - */ - promise: null, - - /** - @public - Custom state can be stored on a Transition's `data` object. - This can be useful for decorating a Transition within an earlier - hook and shared with a later hook. Properties set on `data` will - be copied to new transitions generated by calling `retry` on this - transition. - */ - data: null, - - /** - @public - A standard promise hook that resolves if the transition - succeeds and rejects if it fails/redirects/aborts. - Forwards to the internal `promise` property which you can - use in situations where you want to pass around a thennable, - but not the Transition itself. - @param {Function} onFulfilled - @param {Function} onRejected - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - then: function (onFulfilled, onRejected, label) { - return this.promise.then(onFulfilled, onRejected, label); - }, - - /** - @public - Forwards to the internal `promise` property which you can - use in situations where you want to pass around a thennable, - but not the Transition itself. - @method catch - @param {Function} onRejection - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - catch: function (onRejection, label) { - return this.promise.catch(onRejection, label); - }, - - /** - @public - Forwards to the internal `promise` property which you can - use in situations where you want to pass around a thennable, - but not the Transition itself. - @method finally - @param {Function} callback - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - finally: function (callback, label) { - return this.promise.finally(callback, label); - }, - - /** - @public - Aborts the Transition. Note you can also implicitly abort a transition - by initiating another transition while a previous one is underway. - */ - abort: function () { - if (this.isAborted) { - return this; - } - _routerUtils.log(this.router, this.sequence, this.targetName + ": transition was aborted"); - this.intent.preTransitionState = this.router.state; - this.isAborted = true; - this.isActive = false; - this.router.activeTransition = null; - return this; - }, - - /** - @public - Retries a previously-aborted transition (making sure to abort the - transition if it's still active). Returns a new transition that - represents the new attempt to transition. - */ - retry: function () { - // TODO: add tests for merged state retry()s - this.abort(); - return this.router.transitionByIntent(this.intent, false); - }, - - /** - @public - Sets the URL-changing method to be employed at the end of a - successful transition. By default, a new Transition will just - use `updateURL`, but passing 'replace' to this method will - cause the URL to update using 'replaceWith' instead. Omitting - a parameter will disable the URL change, allowing for transitions - that don't update the URL at completion (this is also used for - handleURL, since the URL has already changed before the - transition took place). - @param {String} method the type of URL-changing method to use - at the end of a transition. Accepted values are 'replace', - falsy values, or any other non-falsy value (which is - interpreted as an updateURL transition). - @return {Transition} this transition - */ - method: function (method) { - this.urlMethod = method; - return this; - }, - - /** - @public - Fires an event on the current list of resolved/resolving - handlers within this transition. Useful for firing events - on route hierarchies that haven't fully been entered yet. - Note: This method is also aliased as `send` - @param {Boolean} [ignoreFailure=false] a boolean specifying whether unhandled events throw an error - @param {String} name the name of the event to fire - */ - trigger: function (ignoreFailure) { - var args = _routerUtils.slice.call(arguments); - if (typeof ignoreFailure === 'boolean') { - args.shift(); - } else { - // Throw errors on unhandled trigger events by default - ignoreFailure = false; - } - _routerUtils.trigger(this.router, this.state.handlerInfos.slice(0, this.resolveIndex + 1), ignoreFailure, args); - }, - - /** - @public - Transitions are aborted and their promises rejected - when redirects occur; this method returns a promise - that will follow any redirects that occur and fulfill - with the value fulfilled by any redirecting transitions - that occur. - @return {Promise} a promise that fulfills with the same - value that the final redirecting transition fulfills with - */ - followRedirects: function () { - var router = this.router; - return this.promise['catch'](function (reason) { - if (router.activeTransition) { - return router.activeTransition.followRedirects(); - } - return _rsvpPromise.default.reject(reason); - }); - }, - - toString: function () { - return "Transition (sequence " + this.sequence + ")"; - }, - - /** - @private - */ - log: function (message) { - _routerUtils.log(this.router, this.sequence, message); - } - }; - - // Alias 'trigger' as 'send' - Transition.prototype.send = Transition.prototype.trigger; - - /** - @private - - Logs and returns a TransitionAborted error. - */ - function logAbort(transition) { - _routerUtils.log(transition.router, transition.sequence, "detected abort."); - return new TransitionAborted(); - } - - function TransitionAborted(message) { - this.message = message || "TransitionAborted"; - this.name = "TransitionAborted"; - } - - exports.Transition = Transition; - exports.logAbort = logAbort; - exports.TransitionAborted = TransitionAborted; -}); -enifed("router/unrecognized-url-error", ["exports", "router/utils"], function (exports, _routerUtils) { - "use strict"; - - /** - Promise reject reasons passed to promise rejection - handlers for failed transitions. - */ - function UnrecognizedURLError(message) { - this.message = message || "UnrecognizedURLError"; - this.name = "UnrecognizedURLError"; - Error.call(this); - } - - UnrecognizedURLError.prototype = _routerUtils.oCreate(Error.prototype); - - exports.default = UnrecognizedURLError; -}); -enifed('router/utils', ['exports'], function (exports) { - 'use strict'; - - exports.extractQueryParams = extractQueryParams; - exports.log = log; - exports.bind = bind; - exports.forEach = forEach; - exports.trigger = trigger; - exports.getChangelist = getChangelist; - exports.promiseLabel = promiseLabel; - exports.subclass = subclass; - var slice = Array.prototype.slice; - - var _isArray; - if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === "[object Array]"; - }; - } else { - _isArray = Array.isArray; - } - - var isArray = _isArray; - - exports.isArray = isArray; - function merge(hash, other) { - for (var prop in other) { - if (other.hasOwnProperty(prop)) { - hash[prop] = other[prop]; - } - } - } - - var oCreate = Object.create || function (proto) { - function F() {} - F.prototype = proto; - return new F(); - }; - - exports.oCreate = oCreate; - /** - @private - - Extracts query params from the end of an array - **/ - - function extractQueryParams(array) { - var len = array && array.length, - head, - queryParams; - - if (len && len > 0 && array[len - 1] && array[len - 1].hasOwnProperty('queryParams')) { - queryParams = array[len - 1].queryParams; - head = slice.call(array, 0, len - 1); - return [head, queryParams]; - } else { - return [array, null]; - } - } - - /** - @private - - Coerces query param properties and array elements into strings. - **/ - function coerceQueryParamsToString(queryParams) { - for (var key in queryParams) { - if (typeof queryParams[key] === 'number') { - queryParams[key] = '' + queryParams[key]; - } else if (isArray(queryParams[key])) { - for (var i = 0, l = queryParams[key].length; i < l; i++) { - queryParams[key][i] = '' + queryParams[key][i]; - } - } - } - } - /** - @private - */ - - function log(router, sequence, msg) { - if (!router.log) { - return; - } - - if (arguments.length === 3) { - router.log("Transition #" + sequence + ": " + msg); - } else { - msg = sequence; - router.log(msg); - } - } - - function bind(context, fn) { - var boundArgs = arguments; - return function (value) { - var args = slice.call(boundArgs, 2); - args.push(value); - return fn.apply(context, args); - }; - } - - function isParam(object) { - return typeof object === "string" || object instanceof String || typeof object === "number" || object instanceof Number; - } - - function forEach(array, callback) { - for (var i = 0, l = array.length; i < l && false !== callback(array[i]); i++) {} - } - - function trigger(router, handlerInfos, ignoreFailure, args) { - if (router.triggerEvent) { - router.triggerEvent(handlerInfos, ignoreFailure, args); - return; - } - - var name = args.shift(); - - if (!handlerInfos) { - if (ignoreFailure) { - return; - } - throw new Error("Could not trigger event '" + name + "'. There are no active handlers"); - } - - var eventWasHandled = false; - - for (var i = handlerInfos.length - 1; i >= 0; i--) { - var handlerInfo = handlerInfos[i], - handler = handlerInfo.handler; - - if (handler.events && handler.events[name]) { - if (handler.events[name].apply(handler, args) === true) { - eventWasHandled = true; - } else { - return; - } - } - } - - if (!eventWasHandled && !ignoreFailure) { - throw new Error("Nothing handled the event '" + name + "'."); - } - } - - function getChangelist(oldObject, newObject) { - var key; - var results = { - all: {}, - changed: {}, - removed: {} - }; - - merge(results.all, newObject); - - var didChange = false; - coerceQueryParamsToString(oldObject); - coerceQueryParamsToString(newObject); - - // Calculate removals - for (key in oldObject) { - if (oldObject.hasOwnProperty(key)) { - if (!newObject.hasOwnProperty(key)) { - didChange = true; - results.removed[key] = oldObject[key]; - } - } - } - - // Calculate changes - for (key in newObject) { - if (newObject.hasOwnProperty(key)) { - if (isArray(oldObject[key]) && isArray(newObject[key])) { - if (oldObject[key].length !== newObject[key].length) { - results.changed[key] = newObject[key]; - didChange = true; - } else { - for (var i = 0, l = oldObject[key].length; i < l; i++) { - if (oldObject[key][i] !== newObject[key][i]) { - results.changed[key] = newObject[key]; - didChange = true; - } - } - } - } else { - if (oldObject[key] !== newObject[key]) { - results.changed[key] = newObject[key]; - didChange = true; - } - } - } - } - - return didChange && results; - } - - function promiseLabel(label) { - return 'Router: ' + label; - } - - function subclass(parentConstructor, proto) { - function C(props) { - parentConstructor.call(this, props || {}); - } - C.prototype = oCreate(parentConstructor.prototype); - merge(C.prototype, proto); - return C; - } - - function resolveHook(obj, hookName) { - if (!obj) { - return; - } - var underscored = "_" + hookName; - return obj[underscored] && underscored || obj[hookName] && hookName; - } - - function callHook(obj, _hookName, arg1, arg2) { - var hookName = resolveHook(obj, _hookName); - return hookName && obj[hookName].call(obj, arg1, arg2); - } - - function applyHook(obj, _hookName, args) { - var hookName = resolveHook(obj, _hookName); - if (hookName) { - if (args.length === 0) { - return obj[hookName].call(obj); - } else if (args.length === 1) { - return obj[hookName].call(obj, args[0]); - } else if (args.length === 2) { - return obj[hookName].call(obj, args[0], args[1]); - } else { - return obj[hookName].apply(obj, args); - } - } - } - - exports.merge = merge; - exports.slice = slice; - exports.isParam = isParam; - exports.coerceQueryParamsToString = coerceQueryParamsToString; - exports.callHook = callHook; - exports.resolveHook = resolveHook; - exports.applyHook = applyHook; -}); -enifed('router', ['exports', 'router/router'], function (exports, _routerRouter) { - 'use strict'; - - exports.default = _routerRouter.default; -}); -enifed('rsvp/-internal', ['exports', 'rsvp/utils', 'rsvp/instrument', 'rsvp/config'], function (exports, _rsvpUtils, _rsvpInstrument, _rsvpConfig) { - 'use strict'; - - function withOwnPromise() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function noop() {} - - var PENDING = void 0; - var FULFILLED = 1; - var REJECTED = 2; - - var GET_THEN_ERROR = new ErrorObject(); - - function getThen(promise) { - try { - return promise.then; - } catch (error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } - } - - function tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch (e) { - return e; - } - } - - function handleForeignThenable(promise, thenable, then) { - _rsvpConfig.config.async(function (promise) { - var sealed = false; - var error = tryThen(then, thenable, function (value) { - if (sealed) { - return; - } - sealed = true; - if (thenable !== value) { - resolve(promise, value); - } else { - fulfill(promise, value); - } - }, function (reason) { - if (sealed) { - return; - } - sealed = true; - - reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - reject(promise, error); - } - }, promise); - } - - function handleOwnThenable(promise, thenable) { - if (thenable._state === FULFILLED) { - fulfill(promise, thenable._result); - } else if (thenable._state === REJECTED) { - thenable._onError = null; - reject(promise, thenable._result); - } else { - subscribe(thenable, undefined, function (value) { - if (thenable !== value) { - resolve(promise, value); - } else { - fulfill(promise, value); - } - }, function (reason) { - reject(promise, reason); - }); - } - } - - function handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - handleOwnThenable(promise, maybeThenable); - } else { - var then = getThen(maybeThenable); - - if (then === GET_THEN_ERROR) { - reject(promise, GET_THEN_ERROR.error); - } else if (then === undefined) { - fulfill(promise, maybeThenable); - } else if (_rsvpUtils.isFunction(then)) { - handleForeignThenable(promise, maybeThenable, then); - } else { - fulfill(promise, maybeThenable); - } - } - } - - function resolve(promise, value) { - if (promise === value) { - fulfill(promise, value); - } else if (_rsvpUtils.objectOrFunction(value)) { - handleMaybeThenable(promise, value); - } else { - fulfill(promise, value); - } - } - - function publishRejection(promise) { - if (promise._onError) { - promise._onError(promise._result); - } - - publish(promise); - } - - function fulfill(promise, value) { - if (promise._state !== PENDING) { - return; - } - - promise._result = value; - promise._state = FULFILLED; - - if (promise._subscribers.length === 0) { - if (_rsvpConfig.config.instrument) { - _rsvpInstrument.default('fulfilled', promise); - } - } else { - _rsvpConfig.config.async(publish, promise); - } - } - - function reject(promise, reason) { - if (promise._state !== PENDING) { - return; - } - promise._state = REJECTED; - promise._result = reason; - _rsvpConfig.config.async(publishRejection, promise); - } - - function subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onError = null; - - subscribers[length] = child; - subscribers[length + FULFILLED] = onFulfillment; - subscribers[length + REJECTED] = onRejection; - - if (length === 0 && parent._state) { - _rsvpConfig.config.async(publish, parent); - } - } - - function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (_rsvpConfig.config.instrument) { - _rsvpInstrument.default(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); - } - - if (subscribers.length === 0) { - return; - } - - var child, - callback, - detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function ErrorObject() { - this.error = null; - } - - var TRY_CATCH_ERROR = new ErrorObject(); - - function tryCatch(callback, detail) { - try { - return callback(detail); - } catch (e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } - } - - function invokeCallback(settled, promise, callback, detail) { - var hasCallback = _rsvpUtils.isFunction(callback), - value, - error, - succeeded, - failed; - - if (hasCallback) { - value = tryCatch(callback, detail); - - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - reject(promise, withOwnPromise()); - return; - } - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== PENDING) { - // noop - } else if (hasCallback && succeeded) { - resolve(promise, value); - } else if (failed) { - reject(promise, error); - } else if (settled === FULFILLED) { - fulfill(promise, value); - } else if (settled === REJECTED) { - reject(promise, value); - } - } - - function initializePromise(promise, resolver) { - var resolved = false; - try { - resolver(function resolvePromise(value) { - if (resolved) { - return; - } - resolved = true; - resolve(promise, value); - }, function rejectPromise(reason) { - if (resolved) { - return; - } - resolved = true; - reject(promise, reason); - }); - } catch (e) { - reject(promise, e); - } - } - - exports.noop = noop; - exports.resolve = resolve; - exports.reject = reject; - exports.fulfill = fulfill; - exports.subscribe = subscribe; - exports.publish = publish; - exports.publishRejection = publishRejection; - exports.initializePromise = initializePromise; - exports.invokeCallback = invokeCallback; - exports.FULFILLED = FULFILLED; - exports.REJECTED = REJECTED; - exports.PENDING = PENDING; -}); -enifed('rsvp/all-settled', ['exports', 'rsvp/enumerator', 'rsvp/promise', 'rsvp/utils'], function (exports, _rsvpEnumerator, _rsvpPromise, _rsvpUtils) { - 'use strict'; - - exports.default = allSettled; - - function AllSettled(Constructor, entries, label) { - this._superConstructor(Constructor, entries, false, /* don't abort on reject */label); - } - - AllSettled.prototype = _rsvpUtils.o_create(_rsvpEnumerator.default.prototype); - AllSettled.prototype._superConstructor = _rsvpEnumerator.default; - AllSettled.prototype._makeResult = _rsvpEnumerator.makeSettledResult; - AllSettled.prototype._validationError = function () { - return new Error('allSettled must be called with an array'); - }; - - /** - `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing - a fail-fast method, it waits until all the promises have returned and - shows you all the results. This is useful if you want to handle multiple - promises' failure states together as a set. - - Returns a promise that is fulfilled when all the given promises have been - settled. The return promise is fulfilled with an array of the states of - the promises passed into the `promises` array argument. - - Each state object will either indicate fulfillment or rejection, and - provide the corresponding value or reason. The states will take one of - the following formats: - - ```javascript - { state: 'fulfilled', value: value } - or - { state: 'rejected', reason: reason } - ``` - - Example: - - ```javascript - var promise1 = RSVP.Promise.resolve(1); - var promise2 = RSVP.Promise.reject(new Error('2')); - var promise3 = RSVP.Promise.reject(new Error('3')); - var promises = [ promise1, promise2, promise3 ]; - - RSVP.allSettled(promises).then(function(array){ - // array == [ - // { state: 'fulfilled', value: 1 }, - // { state: 'rejected', reason: Error }, - // { state: 'rejected', reason: Error } - // ] - // Note that for the second item, reason.message will be '2', and for the - // third item, reason.message will be '3'. - }, function(error) { - // Not run. (This block would only be called if allSettled had failed, - // for instance if passed an incorrect argument type.) - }); - ``` - - @method allSettled - @static - @for RSVP - @param {Array} entries - @param {String} label - optional string that describes the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled with an array of the settled - states of the constituent promises. - */ - - function allSettled(entries, label) { - return new AllSettled(_rsvpPromise.default, entries, label).promise; - } -}); -enifed("rsvp/all", ["exports", "rsvp/promise"], function (exports, _rsvpPromise) { - "use strict"; - - exports.default = all; - - /** - This is a convenient alias for `RSVP.Promise.all`. - - @method all - @static - @for RSVP - @param {Array} array Array of promises. - @param {String} label An optional label. This is useful - for tooling. - */ - - function all(array, label) { - return _rsvpPromise.default.all(array, label); - } -}); -enifed('rsvp/asap', ['exports'], function (exports) { - 'use strict'; - - exports.default = asap; - var len = 0; - var toString = ({}).toString; - var vertxNext; - - function asap(callback, arg) { - queue[len] = callback; - queue[len + 1] = arg; - len += 2; - if (len === 2) { - // If len is 1, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - scheduleFlush(); - } - } - - var browserWindow = typeof window !== 'undefined' ? window : undefined; - var browserGlobal = browserWindow || {}; - var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; - var isNode = typeof window === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; - - // node - function useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function () { - nextTick(flush); - }; - } - - // vertx - function useVertxTimer() { - return function () { - vertxNext(flush); - }; - } - - function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function () { - node.data = iterations = ++iterations % 2; - }; - } - - // web worker - function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function useSetTimeout() { - return function () { - setTimeout(flush, 1); - }; - } - - var queue = new Array(1000); - function flush() { - for (var i = 0; i < len; i += 2) { - var callback = queue[i]; - var arg = queue[i + 1]; - - callback(arg); - - queue[i] = undefined; - queue[i + 1] = undefined; - } - - len = 0; - } - - function attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch (e) { - return useSetTimeout(); - } - } - - var scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (isNode) { - scheduleFlush = useNextTick(); - } else if (BrowserMutationObserver) { - scheduleFlush = useMutationObserver(); - } else if (isWorker) { - scheduleFlush = useMessageChannel(); - } else if (browserWindow === undefined && typeof require === 'function') { - scheduleFlush = attemptVertex(); - } else { - scheduleFlush = useSetTimeout(); - } -}); -enifed('rsvp/config', ['exports', 'rsvp/events'], function (exports, _rsvpEvents) { - 'use strict'; - - var config = { - instrument: false - }; - - _rsvpEvents.default['mixin'](config); - - function configure(name, value) { - if (name === 'onerror') { - // handle for legacy users that expect the actual - // error to be passed to their function added via - // `RSVP.configure('onerror', someFunctionHere);` - config['on']('error', value); - return; - } - - if (arguments.length === 2) { - config[name] = value; - } else { - return config[name]; - } - } - - exports.config = config; - exports.configure = configure; -}); -enifed('rsvp/defer', ['exports', 'rsvp/promise'], function (exports, _rsvpPromise) { - 'use strict'; - - exports.default = defer; - - /** - `RSVP.defer` returns an object similar to jQuery's `$.Deferred`. - `RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s - interface. New code should use the `RSVP.Promise` constructor instead. - - The object returned from `RSVP.defer` is a plain object with three properties: - - * promise - an `RSVP.Promise`. - * reject - a function that causes the `promise` property on this object to - become rejected - * resolve - a function that causes the `promise` property on this object to - become fulfilled. - - Example: - - ```javascript - var deferred = RSVP.defer(); - - deferred.resolve("Success!"); - - deferred.promise.then(function(value){ - // value here is "Success!" - }); - ``` - - @method defer - @static - @for RSVP - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Object} - */ - - function defer(label) { - var deferred = {}; - - deferred['promise'] = new _rsvpPromise.default(function (resolve, reject) { - deferred['resolve'] = resolve; - deferred['reject'] = reject; - }, label); - - return deferred; - } -}); -enifed('rsvp/enumerator', ['exports', 'rsvp/utils', 'rsvp/-internal'], function (exports, _rsvpUtils, _rsvpInternal) { - 'use strict'; - - exports.makeSettledResult = makeSettledResult; - - function makeSettledResult(state, position, value) { - if (state === _rsvpInternal.FULFILLED) { - return { - state: 'fulfilled', - value: value - }; - } else { - return { - state: 'rejected', - reason: value - }; - } - } - - function Enumerator(Constructor, input, abortOnReject, label) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(_rsvpInternal.noop, label); - enumerator._abortOnReject = abortOnReject; - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - _rsvpInternal.fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - _rsvpInternal.fulfill(enumerator.promise, enumerator._result); - } - } - } else { - _rsvpInternal.reject(enumerator.promise, enumerator._validationError()); - } - } - - exports.default = Enumerator; - - Enumerator.prototype._validateInput = function (input) { - return _rsvpUtils.isArray(input); - }; - - Enumerator.prototype._validationError = function () { - return new Error('Array Methods must be provided an Array'); - }; - - Enumerator.prototype._init = function () { - this._result = new Array(this.length); - }; - - Enumerator.prototype._enumerate = function () { - var enumerator = this; - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === _rsvpInternal.PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } - }; - - Enumerator.prototype._eachEntry = function (entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - if (_rsvpUtils.isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== _rsvpInternal.PENDING) { - entry._onError = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = enumerator._makeResult(_rsvpInternal.FULFILLED, i, entry); - } - }; - - Enumerator.prototype._settledAt = function (state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === _rsvpInternal.PENDING) { - enumerator._remaining--; - - if (enumerator._abortOnReject && state === _rsvpInternal.REJECTED) { - _rsvpInternal.reject(promise, value); - } else { - enumerator._result[i] = enumerator._makeResult(state, i, value); - } - } - - if (enumerator._remaining === 0) { - _rsvpInternal.fulfill(promise, enumerator._result); - } - }; - - Enumerator.prototype._makeResult = function (state, i, value) { - return value; - }; - - Enumerator.prototype._willSettleAt = function (promise, i) { - var enumerator = this; - - _rsvpInternal.subscribe(promise, undefined, function (value) { - enumerator._settledAt(_rsvpInternal.FULFILLED, i, value); - }, function (reason) { - enumerator._settledAt(_rsvpInternal.REJECTED, i, reason); - }); - }; -}); -enifed('rsvp/events', ['exports'], function (exports) { - 'use strict'; - - function indexOf(callbacks, callback) { - for (var i = 0, l = callbacks.length; i < l; i++) { - if (callbacks[i] === callback) { - return i; - } - } - - return -1; - } - - function callbacksFor(object) { - var callbacks = object._promiseCallbacks; - - if (!callbacks) { - callbacks = object._promiseCallbacks = {}; - } - - return callbacks; - } - - /** - @class RSVP.EventTarget - */ - exports.default = { - - /** - `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For - Example: - ```javascript - var object = {}; - RSVP.EventTarget.mixin(object); - object.on('finished', function(event) { - // handle event - }); - object.trigger('finished', { detail: value }); - ``` - `EventTarget.mixin` also works with prototypes: - ```javascript - var Person = function() {}; - RSVP.EventTarget.mixin(Person.prototype); - var yehuda = new Person(); - var tom = new Person(); - yehuda.on('poke', function(event) { - console.log('Yehuda says OW'); - }); - tom.on('poke', function(event) { - console.log('Tom says OW'); - }); - yehuda.trigger('poke'); - tom.trigger('poke'); - ``` - @method mixin - @for RSVP.EventTarget - @private - @param {Object} object object to extend with EventTarget methods - */ - 'mixin': function (object) { - object['on'] = this['on']; - object['off'] = this['off']; - object['trigger'] = this['trigger']; - object._promiseCallbacks = undefined; - return object; - }, - - /** - Registers a callback to be executed when `eventName` is triggered - ```javascript - object.on('event', function(eventInfo){ - // handle the event - }); - object.trigger('event'); - ``` - @method on - @for RSVP.EventTarget - @private - @param {String} eventName name of the event to listen for - @param {Function} callback function to be called when the event is triggered. - */ - 'on': function (eventName, callback) { - if (typeof callback !== 'function') { - throw new TypeError('Callback must be a function'); - } - - var allCallbacks = callbacksFor(this), - callbacks; - - callbacks = allCallbacks[eventName]; - - if (!callbacks) { - callbacks = allCallbacks[eventName] = []; - } - - if (indexOf(callbacks, callback) === -1) { - callbacks.push(callback); - } - }, - - /** - You can use `off` to stop firing a particular callback for an event: - ```javascript - function doStuff() { // do stuff! } - object.on('stuff', doStuff); - object.trigger('stuff'); // doStuff will be called - // Unregister ONLY the doStuff callback - object.off('stuff', doStuff); - object.trigger('stuff'); // doStuff will NOT be called - ``` - If you don't pass a `callback` argument to `off`, ALL callbacks for the - event will not be executed when the event fires. For example: - ```javascript - var callback1 = function(){}; - var callback2 = function(){}; - object.on('stuff', callback1); - object.on('stuff', callback2); - object.trigger('stuff'); // callback1 and callback2 will be executed. - object.off('stuff'); - object.trigger('stuff'); // callback1 and callback2 will not be executed! - ``` - @method off - @for RSVP.EventTarget - @private - @param {String} eventName event to stop listening to - @param {Function} callback optional argument. If given, only the function - given will be removed from the event's callback queue. If no `callback` - argument is given, all callbacks will be removed from the event's callback - queue. - */ - 'off': function (eventName, callback) { - var allCallbacks = callbacksFor(this), - callbacks, - index; - - if (!callback) { - allCallbacks[eventName] = []; - return; - } - - callbacks = allCallbacks[eventName]; - - index = indexOf(callbacks, callback); - - if (index !== -1) { - callbacks.splice(index, 1); - } - }, - - /** - Use `trigger` to fire custom events. For example: - ```javascript - object.on('foo', function(){ - console.log('foo event happened!'); - }); - object.trigger('foo'); - // 'foo event happened!' logged to the console - ``` - You can also pass a value as a second argument to `trigger` that will be - passed as an argument to all event listeners for the event: - ```javascript - object.on('foo', function(value){ - console.log(value.name); - }); - object.trigger('foo', { name: 'bar' }); - // 'bar' logged to the console - ``` - @method trigger - @for RSVP.EventTarget - @private - @param {String} eventName name of the event to be triggered - @param {*} options optional value to be passed to any event handlers for - the given `eventName` - */ - 'trigger': function (eventName, options) { - var allCallbacks = callbacksFor(this), - callbacks, - callback; - - if (callbacks = allCallbacks[eventName]) { - // Don't cache the callbacks.length since it may grow - for (var i = 0; i < callbacks.length; i++) { - callback = callbacks[i]; - - callback(options); - } - } - } - }; -}); -enifed('rsvp/filter', ['exports', 'rsvp/promise', 'rsvp/utils'], function (exports, _rsvpPromise, _rsvpUtils) { - 'use strict'; - - exports.default = filter; - - /** - `RSVP.filter` is similar to JavaScript's native `filter` method, except that it - waits for all promises to become fulfilled before running the `filterFn` on - each item in given to `promises`. `RSVP.filter` returns a promise that will - become fulfilled with the result of running `filterFn` on the values the - promises become fulfilled with. - - For example: - - ```javascript - - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.resolve(2); - var promise3 = RSVP.resolve(3); - - var promises = [promise1, promise2, promise3]; - - var filterFn = function(item){ - return item > 1; - }; - - RSVP.filter(promises, filterFn).then(function(result){ - // result is [ 2, 3 ] - }); - ``` - - If any of the `promises` given to `RSVP.filter` are rejected, the first promise - that is rejected will be given as an argument to the returned promise's - rejection handler. For example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.reject(new Error('2')); - var promise3 = RSVP.reject(new Error('3')); - var promises = [ promise1, promise2, promise3 ]; - - var filterFn = function(item){ - return item > 1; - }; - - RSVP.filter(promises, filterFn).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(reason) { - // reason.message === '2' - }); - ``` - - `RSVP.filter` will also wait for any promises returned from `filterFn`. - For instance, you may want to fetch a list of users then return a subset - of those users based on some asynchronous operation: - - ```javascript - - var alice = { name: 'alice' }; - var bob = { name: 'bob' }; - var users = [ alice, bob ]; - - var promises = users.map(function(user){ - return RSVP.resolve(user); - }); - - var filterFn = function(user){ - // Here, Alice has permissions to create a blog post, but Bob does not. - return getPrivilegesForUser(user).then(function(privs){ - return privs.can_create_blog_post === true; - }); - }; - RSVP.filter(promises, filterFn).then(function(users){ - // true, because the server told us only Alice can create a blog post. - users.length === 1; - // false, because Alice is the only user present in `users` - users[0] === bob; - }); - ``` - - @method filter - @static - @for RSVP - @param {Array} promises - @param {Function} filterFn - function to be called on each resolved value to - filter the final results. - @param {String} label optional string describing the promise. Useful for - tooling. - @return {Promise} - */ - - function filter(promises, filterFn, label) { - return _rsvpPromise.default.all(promises, label).then(function (values) { - if (!_rsvpUtils.isFunction(filterFn)) { - throw new TypeError("You must pass a function as filter's second argument."); - } - - var length = values.length; - var filtered = new Array(length); - - for (var i = 0; i < length; i++) { - filtered[i] = filterFn(values[i]); - } - - return _rsvpPromise.default.all(filtered, label).then(function (filtered) { - var results = new Array(length); - var newLength = 0; - - for (var i = 0; i < length; i++) { - if (filtered[i]) { - results[newLength] = values[i]; - newLength++; - } - } - - results.length = newLength; - - return results; - }); - }); - } -}); -enifed('rsvp/hash-settled', ['exports', 'rsvp/promise', 'rsvp/enumerator', 'rsvp/promise-hash', 'rsvp/utils'], function (exports, _rsvpPromise, _rsvpEnumerator, _rsvpPromiseHash, _rsvpUtils) { - 'use strict'; - - exports.default = hashSettled; - - function HashSettled(Constructor, object, label) { - this._superConstructor(Constructor, object, false, label); - } - - HashSettled.prototype = _rsvpUtils.o_create(_rsvpPromiseHash.default.prototype); - HashSettled.prototype._superConstructor = _rsvpEnumerator.default; - HashSettled.prototype._makeResult = _rsvpEnumerator.makeSettledResult; - - HashSettled.prototype._validationError = function () { - return new Error('hashSettled must be called with an object'); - }; - - /** - `RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object - instead of an array for its `promises` argument. - - Unlike `RSVP.all` or `RSVP.hash`, which implement a fail-fast method, - but like `RSVP.allSettled`, `hashSettled` waits until all the - constituent promises have returned and then shows you all the results - with their states and values/reasons. This is useful if you want to - handle multiple promises' failure states together as a set. - - Returns a promise that is fulfilled when all the given promises have been - settled, or rejected if the passed parameters are invalid. - - The returned promise is fulfilled with a hash that has the same key names as - the `promises` object argument. If any of the values in the object are not - promises, they will be copied over to the fulfilled object and marked with state - 'fulfilled'. - - Example: - - ```javascript - var promises = { - myPromise: RSVP.Promise.resolve(1), - yourPromise: RSVP.Promise.resolve(2), - theirPromise: RSVP.Promise.resolve(3), - notAPromise: 4 - }; - - RSVP.hashSettled(promises).then(function(hash){ - // hash here is an object that looks like: - // { - // myPromise: { state: 'fulfilled', value: 1 }, - // yourPromise: { state: 'fulfilled', value: 2 }, - // theirPromise: { state: 'fulfilled', value: 3 }, - // notAPromise: { state: 'fulfilled', value: 4 } - // } - }); - ``` - - If any of the `promises` given to `RSVP.hash` are rejected, the state will - be set to 'rejected' and the reason for rejection provided. - - Example: - - ```javascript - var promises = { - myPromise: RSVP.Promise.resolve(1), - rejectedPromise: RSVP.Promise.reject(new Error('rejection')), - anotherRejectedPromise: RSVP.Promise.reject(new Error('more rejection')), - }; - - RSVP.hashSettled(promises).then(function(hash){ - // hash here is an object that looks like: - // { - // myPromise: { state: 'fulfilled', value: 1 }, - // rejectedPromise: { state: 'rejected', reason: Error }, - // anotherRejectedPromise: { state: 'rejected', reason: Error }, - // } - // Note that for rejectedPromise, reason.message == 'rejection', - // and for anotherRejectedPromise, reason.message == 'more rejection'. - }); - ``` - - An important note: `RSVP.hashSettled` is intended for plain JavaScript objects that - are just a set of keys and values. `RSVP.hashSettled` will NOT preserve prototype - chains. - - Example: - - ```javascript - function MyConstructor(){ - this.example = RSVP.Promise.resolve('Example'); - } - - MyConstructor.prototype = { - protoProperty: RSVP.Promise.resolve('Proto Property') - }; - - var myObject = new MyConstructor(); - - RSVP.hashSettled(myObject).then(function(hash){ - // protoProperty will not be present, instead you will just have an - // object that looks like: - // { - // example: { state: 'fulfilled', value: 'Example' } - // } - // - // hash.hasOwnProperty('protoProperty'); // false - // 'undefined' === typeof hash.protoProperty - }); - ``` - - @method hashSettled - @for RSVP - @param {Object} object - @param {String} label optional string that describes the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when when all properties of `promises` - have been settled. - @static - */ - - function hashSettled(object, label) { - return new HashSettled(_rsvpPromise.default, object, label).promise; - } -}); -enifed('rsvp/hash', ['exports', 'rsvp/promise', 'rsvp/promise-hash'], function (exports, _rsvpPromise, _rsvpPromiseHash) { - 'use strict'; - - exports.default = hash; - - /** - `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array - for its `promises` argument. - - Returns a promise that is fulfilled when all the given promises have been - fulfilled, or rejected if any of them become rejected. The returned promise - is fulfilled with a hash that has the same key names as the `promises` object - argument. If any of the values in the object are not promises, they will - simply be copied over to the fulfilled object. - - Example: - - ```javascript - var promises = { - myPromise: RSVP.resolve(1), - yourPromise: RSVP.resolve(2), - theirPromise: RSVP.resolve(3), - notAPromise: 4 - }; - - RSVP.hash(promises).then(function(hash){ - // hash here is an object that looks like: - // { - // myPromise: 1, - // yourPromise: 2, - // theirPromise: 3, - // notAPromise: 4 - // } - }); - ```` - - If any of the `promises` given to `RSVP.hash` are rejected, the first promise - that is rejected will be given as the reason to the rejection handler. - - Example: - - ```javascript - var promises = { - myPromise: RSVP.resolve(1), - rejectedPromise: RSVP.reject(new Error('rejectedPromise')), - anotherRejectedPromise: RSVP.reject(new Error('anotherRejectedPromise')), - }; - - RSVP.hash(promises).then(function(hash){ - // Code here never runs because there are rejected promises! - }, function(reason) { - // reason.message === 'rejectedPromise' - }); - ``` - - An important note: `RSVP.hash` is intended for plain JavaScript objects that - are just a set of keys and values. `RSVP.hash` will NOT preserve prototype - chains. - - Example: - - ```javascript - function MyConstructor(){ - this.example = RSVP.resolve('Example'); - } - - MyConstructor.prototype = { - protoProperty: RSVP.resolve('Proto Property') - }; - - var myObject = new MyConstructor(); - - RSVP.hash(myObject).then(function(hash){ - // protoProperty will not be present, instead you will just have an - // object that looks like: - // { - // example: 'Example' - // } - // - // hash.hasOwnProperty('protoProperty'); // false - // 'undefined' === typeof hash.protoProperty - }); - ``` - - @method hash - @static - @for RSVP - @param {Object} object - @param {String} label optional string that describes the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all properties of `promises` - have been fulfilled, or rejected if any of them become rejected. - */ - - function hash(object, label) { - return new _rsvpPromiseHash.default(_rsvpPromise.default, object, label).promise; - } -}); -enifed('rsvp/instrument', ['exports', 'rsvp/config', 'rsvp/utils'], function (exports, _rsvpConfig, _rsvpUtils) { - 'use strict'; - - exports.default = instrument; - - var queue = []; - - function scheduleFlush() { - setTimeout(function () { - var entry; - for (var i = 0; i < queue.length; i++) { - entry = queue[i]; - - var payload = entry.payload; - - payload.guid = payload.key + payload.id; - payload.childGuid = payload.key + payload.childId; - if (payload.error) { - payload.stack = payload.error.stack; - } - - _rsvpConfig.config['trigger'](entry.name, entry.payload); - } - queue.length = 0; - }, 50); - } - - function instrument(eventName, promise, child) { - if (1 === queue.push({ - name: eventName, - payload: { - key: promise._guidKey, - id: promise._id, - eventName: eventName, - detail: promise._result, - childId: child && child._id, - label: promise._label, - timeStamp: _rsvpUtils.now(), - error: _rsvpConfig.config["instrument-with-stack"] ? new Error(promise._label) : null - } })) { - scheduleFlush(); - } - } -}); -enifed('rsvp/map', ['exports', 'rsvp/promise', 'rsvp/utils'], function (exports, _rsvpPromise, _rsvpUtils) { - 'use strict'; - - exports.default = map; - - /** - `RSVP.map` is similar to JavaScript's native `map` method, except that it - waits for all promises to become fulfilled before running the `mapFn` on - each item in given to `promises`. `RSVP.map` returns a promise that will - become fulfilled with the result of running `mapFn` on the values the promises - become fulfilled with. - - For example: - - ```javascript - - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.resolve(2); - var promise3 = RSVP.resolve(3); - var promises = [ promise1, promise2, promise3 ]; - - var mapFn = function(item){ - return item + 1; - }; - - RSVP.map(promises, mapFn).then(function(result){ - // result is [ 2, 3, 4 ] - }); - ``` - - If any of the `promises` given to `RSVP.map` are rejected, the first promise - that is rejected will be given as an argument to the returned promise's - rejection handler. For example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.reject(new Error('2')); - var promise3 = RSVP.reject(new Error('3')); - var promises = [ promise1, promise2, promise3 ]; - - var mapFn = function(item){ - return item + 1; - }; - - RSVP.map(promises, mapFn).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(reason) { - // reason.message === '2' - }); - ``` - - `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, - say you want to get all comments from a set of blog posts, but you need - the blog posts first because they contain a url to those comments. - - ```javscript - - var mapFn = function(blogPost){ - // getComments does some ajax and returns an RSVP.Promise that is fulfilled - // with some comments data - return getComments(blogPost.comments_url); - }; - - // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled - // with some blog post data - RSVP.map(getBlogPosts(), mapFn).then(function(comments){ - // comments is the result of asking the server for the comments - // of all blog posts returned from getBlogPosts() - }); - ``` - - @method map - @static - @for RSVP - @param {Array} promises - @param {Function} mapFn function to be called on each fulfilled promise. - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled with the result of calling - `mapFn` on each fulfilled promise or value when they become fulfilled. - The promise will be rejected if any of the given `promises` become rejected. - @static - */ - - function map(promises, mapFn, label) { - return _rsvpPromise.default.all(promises, label).then(function (values) { - if (!_rsvpUtils.isFunction(mapFn)) { - throw new TypeError("You must pass a function as map's second argument."); - } - - var length = values.length; - var results = new Array(length); - - for (var i = 0; i < length; i++) { - results[i] = mapFn(values[i]); - } - - return _rsvpPromise.default.all(results, label); - }); - } -}); -enifed('rsvp/node', ['exports', 'rsvp/promise', 'rsvp/-internal', 'rsvp/utils'], function (exports, _rsvpPromise, _rsvpInternal, _rsvpUtils) { - 'use strict'; - - exports.default = denodeify; - - function Result() { - this.value = undefined; - } - - var ERROR = new Result(); - var GET_THEN_ERROR = new Result(); - - function getThen(obj) { - try { - return obj.then; - } catch (error) { - ERROR.value = error; - return ERROR; - } - } - - function tryApply(f, s, a) { - try { - f.apply(s, a); - } catch (error) { - ERROR.value = error; - return ERROR; - } - } - - function makeObject(_, argumentNames) { - var obj = {}; - var name; - var i; - var length = _.length; - var args = new Array(length); - - for (var x = 0; x < length; x++) { - args[x] = _[x]; - } - - for (i = 0; i < argumentNames.length; i++) { - name = argumentNames[i]; - obj[name] = args[i + 1]; - } - - return obj; - } - - function arrayResult(_) { - var length = _.length; - var args = new Array(length - 1); - - for (var i = 1; i < length; i++) { - args[i - 1] = _[i]; - } - - return args; - } - - function wrapThenable(then, promise) { - return { - then: function (onFulFillment, onRejection) { - return then.call(promise, onFulFillment, onRejection); - } - }; - } - - /** - `RSVP.denodeify` takes a 'node-style' function and returns a function that - will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the - browser when you'd prefer to use promises over using callbacks. For example, - `denodeify` transforms the following: - - ```javascript - var fs = require('fs'); - - fs.readFile('myfile.txt', function(err, data){ - if (err) return handleError(err); - handleData(data); - }); - ``` - - into: - - ```javascript - var fs = require('fs'); - var readFile = RSVP.denodeify(fs.readFile); - - readFile('myfile.txt').then(handleData, handleError); - ``` - - If the node function has multiple success parameters, then `denodeify` - just returns the first one: - - ```javascript - var request = RSVP.denodeify(require('request')); - - request('http://example.com').then(function(res) { - // ... - }); - ``` - - However, if you need all success parameters, setting `denodeify`'s - second parameter to `true` causes it to return all success parameters - as an array: - - ```javascript - var request = RSVP.denodeify(require('request'), true); - - request('http://example.com').then(function(result) { - // result[0] -> res - // result[1] -> body - }); - ``` - - Or if you pass it an array with names it returns the parameters as a hash: - - ```javascript - var request = RSVP.denodeify(require('request'), ['res', 'body']); - - request('http://example.com').then(function(result) { - // result.res - // result.body - }); - ``` - - Sometimes you need to retain the `this`: - - ```javascript - var app = require('express')(); - var render = RSVP.denodeify(app.render.bind(app)); - ``` - - The denodified function inherits from the original function. It works in all - environments, except IE 10 and below. Consequently all properties of the original - function are available to you. However, any properties you change on the - denodeified function won't be changed on the original function. Example: - - ```javascript - var request = RSVP.denodeify(require('request')), - cookieJar = request.jar(); // <- Inheritance is used here - - request('http://example.com', {jar: cookieJar}).then(function(res) { - // cookieJar.cookies holds now the cookies returned by example.com - }); - ``` - - Using `denodeify` makes it easier to compose asynchronous operations instead - of using callbacks. For example, instead of: - - ```javascript - var fs = require('fs'); - - fs.readFile('myfile.txt', function(err, data){ - if (err) { ... } // Handle error - fs.writeFile('myfile2.txt', data, function(err){ - if (err) { ... } // Handle error - console.log('done') - }); - }); - ``` - - you can chain the operations together using `then` from the returned promise: - - ```javascript - var fs = require('fs'); - var readFile = RSVP.denodeify(fs.readFile); - var writeFile = RSVP.denodeify(fs.writeFile); - - readFile('myfile.txt').then(function(data){ - return writeFile('myfile2.txt', data); - }).then(function(){ - console.log('done') - }).catch(function(error){ - // Handle error - }); - ``` - - @method denodeify - @static - @for RSVP - @param {Function} nodeFunc a 'node-style' function that takes a callback as - its last argument. The callback expects an error to be passed as its first - argument (if an error occurred, otherwise null), and the value from the - operation as its second argument ('function(err, value){ }'). - @param {Boolean|Array} [options] An optional paramter that if set - to `true` causes the promise to fulfill with the callback's success arguments - as an array. This is useful if the node function has multiple success - paramters. If you set this paramter to an array with names, the promise will - fulfill with a hash with these names as keys and the success parameters as - values. - @return {Function} a function that wraps `nodeFunc` to return an - `RSVP.Promise` - @static - */ - - function denodeify(nodeFunc, options) { - var fn = function () { - var self = this; - var l = arguments.length; - var args = new Array(l + 1); - var arg; - var promiseInput = false; - - for (var i = 0; i < l; ++i) { - arg = arguments[i]; - - if (!promiseInput) { - // TODO: clean this up - promiseInput = needsPromiseInput(arg); - if (promiseInput === GET_THEN_ERROR) { - var p = new _rsvpPromise.default(_rsvpInternal.noop); - _rsvpInternal.reject(p, GET_THEN_ERROR.value); - return p; - } else if (promiseInput && promiseInput !== true) { - arg = wrapThenable(promiseInput, arg); - } - } - args[i] = arg; - } - - var promise = new _rsvpPromise.default(_rsvpInternal.noop); - - args[l] = function (err, val) { - if (err) _rsvpInternal.reject(promise, err);else if (options === undefined) _rsvpInternal.resolve(promise, val);else if (options === true) _rsvpInternal.resolve(promise, arrayResult(arguments));else if (_rsvpUtils.isArray(options)) _rsvpInternal.resolve(promise, makeObject(arguments, options));else _rsvpInternal.resolve(promise, val); - }; - - if (promiseInput) { - return handlePromiseInput(promise, args, nodeFunc, self); - } else { - return handleValueInput(promise, args, nodeFunc, self); - } - }; - - fn.__proto__ = nodeFunc; - - return fn; - } - - function handleValueInput(promise, args, nodeFunc, self) { - var result = tryApply(nodeFunc, self, args); - if (result === ERROR) { - _rsvpInternal.reject(promise, result.value); - } - return promise; - } - - function handlePromiseInput(promise, args, nodeFunc, self) { - return _rsvpPromise.default.all(args).then(function (args) { - var result = tryApply(nodeFunc, self, args); - if (result === ERROR) { - _rsvpInternal.reject(promise, result.value); - } - return promise; - }); - } - - function needsPromiseInput(arg) { - if (arg && typeof arg === 'object') { - if (arg.constructor === _rsvpPromise.default) { - return true; - } else { - return getThen(arg); - } - } else { - return false; - } - } -}); -enifed('rsvp/platform', ['exports'], function (exports) { - 'use strict'; - - var platform; - - /* global self */ - if (typeof self === 'object') { - platform = self; - - /* global global */ - } else if (typeof global === 'object') { - platform = global; - } else { - throw new Error('no global: `self` or `global` found'); - } - - exports.default = platform; -}); -enifed('rsvp/promise/all', ['exports', 'rsvp/enumerator'], function (exports, _rsvpEnumerator) { - 'use strict'; - - exports.default = all; - - /** - `RSVP.Promise.all` accepts an array of promises, and returns a new promise which - is fulfilled with an array of fulfillment values for the passed promises, or - rejected with the reason of the first passed promise to be rejected. It casts all - elements of the passed iterable to promises as it runs this algorithm. - - Example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.resolve(2); - var promise3 = RSVP.resolve(3); - var promises = [ promise1, promise2, promise3 ]; - - RSVP.Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` - - If any of the `promises` given to `RSVP.all` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - Example: - - ```javascript - var promise1 = RSVP.resolve(1); - var promise2 = RSVP.reject(new Error("2")); - var promise3 = RSVP.reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; - - RSVP.Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` - - @method all - @static - @param {Array} entries array of promises - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all `promises` have been - fulfilled, or rejected if any of them become rejected. - @static - */ - - function all(entries, label) { - return new _rsvpEnumerator.default(this, entries, true, /* abort on reject */label).promise; - } -}); -enifed('rsvp/promise/race', ['exports', 'rsvp/utils', 'rsvp/-internal'], function (exports, _rsvpUtils, _rsvpInternal) { - 'use strict'; - - exports.default = race; - - /** - `RSVP.Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. - - Example: - - ```javascript - var promise1 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - var promise2 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 2'); - }, 100); - }); - - RSVP.Promise.race([promise1, promise2]).then(function(result){ - // result === 'promise 2' because it was resolved before promise1 - // was resolved. - }); - ``` - - `RSVP.Promise.race` is deterministic in that only the state of the first - settled promise matters. For example, even if other promises given to the - `promises` array argument are resolved, but the first settled promise has - become rejected before the other promises became fulfilled, the returned - promise will become rejected: - - ```javascript - var promise1 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - var promise2 = new RSVP.Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); - - RSVP.Promise.race([promise1, promise2]).then(function(result){ - // Code here never runs - }, function(reason){ - // reason.message === 'promise 2' because promise 2 became rejected before - // promise 1 became fulfilled - }); - ``` - - An example real-world use case is implementing timeouts: - - ```javascript - RSVP.Promise.race([ajax('foo.json'), timeout(5000)]) - ``` - - @method race - @static - @param {Array} entries array of promises to observe - @param {String} label optional string for describing the promise returned. - Useful for tooling. - @return {Promise} a promise which settles in the same way as the first passed - promise to settle. - */ - - function race(entries, label) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(_rsvpInternal.noop, label); - - if (!_rsvpUtils.isArray(entries)) { - _rsvpInternal.reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - _rsvpInternal.resolve(promise, value); - } - - function onRejection(reason) { - _rsvpInternal.reject(promise, reason); - } - - for (var i = 0; promise._state === _rsvpInternal.PENDING && i < length; i++) { - _rsvpInternal.subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; - } -}); -enifed('rsvp/promise/reject', ['exports', 'rsvp/-internal'], function (exports, _rsvpInternal) { - 'use strict'; - - exports.default = reject; - - /** - `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. - It is shorthand for the following: - - ```javascript - var promise = new RSVP.Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = RSVP.Promise.reject(new Error('WHOOPS')); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - @method reject - @static - @param {*} reason value that the returned promise will be rejected with. - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. - */ - - function reject(reason, label) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(_rsvpInternal.noop, label); - _rsvpInternal.reject(promise, reason); - return promise; - } -}); -enifed('rsvp/promise/resolve', ['exports', 'rsvp/-internal'], function (exports, _rsvpInternal) { - 'use strict'; - - exports.default = resolve; - - /** - `RSVP.Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: - - ```javascript - var promise = new RSVP.Promise(function(resolve, reject){ - resolve(1); - }); - - promise.then(function(value){ - // value === 1 - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = RSVP.Promise.resolve(1); - - promise.then(function(value){ - // value === 1 - }); - ``` - - @method resolve - @static - @param {*} object value that the returned promise will be resolved with - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` - */ - - function resolve(object, label) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(_rsvpInternal.noop, label); - _rsvpInternal.resolve(promise, object); - return promise; - } -}); -enifed('rsvp/promise-hash', ['exports', 'rsvp/enumerator', 'rsvp/-internal', 'rsvp/utils'], function (exports, _rsvpEnumerator, _rsvpInternal, _rsvpUtils) { - 'use strict'; - - function PromiseHash(Constructor, object, label) { - this._superConstructor(Constructor, object, true, label); - } - - exports.default = PromiseHash; - - PromiseHash.prototype = _rsvpUtils.o_create(_rsvpEnumerator.default.prototype); - PromiseHash.prototype._superConstructor = _rsvpEnumerator.default; - PromiseHash.prototype._init = function () { - this._result = {}; - }; - - PromiseHash.prototype._validateInput = function (input) { - return input && typeof input === 'object'; - }; - - PromiseHash.prototype._validationError = function () { - return new Error('Promise.hash must be called with an object'); - }; - - PromiseHash.prototype._enumerate = function () { - var enumerator = this; - var promise = enumerator.promise; - var input = enumerator._input; - var results = []; - - for (var key in input) { - if (promise._state === _rsvpInternal.PENDING && Object.prototype.hasOwnProperty.call(input, key)) { - results.push({ - position: key, - entry: input[key] - }); - } - } - - var length = results.length; - enumerator._remaining = length; - var result; - - for (var i = 0; promise._state === _rsvpInternal.PENDING && i < length; i++) { - result = results[i]; - enumerator._eachEntry(result.entry, result.position); - } - }; -}); -enifed('rsvp/promise', ['exports', 'rsvp/config', 'rsvp/instrument', 'rsvp/utils', 'rsvp/-internal', 'rsvp/promise/all', 'rsvp/promise/race', 'rsvp/promise/resolve', 'rsvp/promise/reject'], function (exports, _rsvpConfig, _rsvpInstrument, _rsvpUtils, _rsvpInternal, _rsvpPromiseAll, _rsvpPromiseRace, _rsvpPromiseResolve, _rsvpPromiseReject) { - 'use strict'; - - exports.default = Promise; - - var guidKey = 'rsvp_' + _rsvpUtils.now() + '-'; - var counter = 0; - - function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class RSVP.Promise - @param {function} resolver - @param {String} label optional string for labeling the promise. - Useful for tooling. - @constructor - */ - - function Promise(resolver, label) { - var promise = this; - - promise._id = counter++; - promise._label = label; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; - - if (_rsvpConfig.config.instrument) { - _rsvpInstrument.default('created', promise); - } - - if (_rsvpInternal.noop !== resolver) { - if (!_rsvpUtils.isFunction(resolver)) { - needsResolver(); - } - - if (!(promise instanceof Promise)) { - needsNew(); - } - - _rsvpInternal.initializePromise(promise, resolver); - } - } - - Promise.cast = _rsvpPromiseResolve.default; // deprecated - Promise.all = _rsvpPromiseAll.default; - Promise.race = _rsvpPromiseRace.default; - Promise.resolve = _rsvpPromiseResolve.default; - Promise.reject = _rsvpPromiseReject.default; - - Promise.prototype = { - constructor: Promise, - - _guidKey: guidKey, - - _onError: function (reason) { - var promise = this; - _rsvpConfig.config.after(function () { - if (promise._onError) { - _rsvpConfig.config['trigger']('error', reason); - } - }); - }, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfillment - @param {Function} onRejection - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - then: function (onFulfillment, onRejection, label) { - var parent = this; - var state = parent._state; - - if (state === _rsvpInternal.FULFILLED && !onFulfillment || state === _rsvpInternal.REJECTED && !onRejection) { - if (_rsvpConfig.config.instrument) { - _rsvpInstrument.default('chained', parent, parent); - } - return parent; - } - - parent._onError = null; - - var child = new parent.constructor(_rsvpInternal.noop, label); - var result = parent._result; - - if (_rsvpConfig.config.instrument) { - _rsvpInstrument.default('chained', parent, child); - } - - if (state) { - var callback = arguments[state - 1]; - _rsvpConfig.config.async(function () { - _rsvpInternal.invokeCallback(state, child, callback, result); - }); - } else { - _rsvpInternal.subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - 'catch': function (onRejection, label) { - return this.then(undefined, onRejection, label); - }, - - /** - `finally` will be invoked regardless of the promise's fate just as native - try/catch/finally behaves - - Synchronous example: - - ```js - findAuthor() { - if (Math.random() > 0.5) { - throw new Error(); - } - return new Author(); - } - - try { - return findAuthor(); // succeed or fail - } catch(error) { - return findOtherAuther(); - } finally { - // always runs - // doesn't affect the return value - } - ``` - - Asynchronous example: - - ```js - findAuthor().catch(function(reason){ - return findOtherAuther(); - }).finally(function(){ - // author was either found, or not - }); - ``` - - @method finally - @param {Function} callback - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} - */ - 'finally': function (callback, label) { - var promise = this; - var constructor = promise.constructor; - - return promise.then(function (value) { - return constructor.resolve(callback()).then(function () { - return value; - }); - }, function (reason) { - return constructor.resolve(callback()).then(function () { - throw reason; - }); - }, label); - } - }; -}); -enifed('rsvp/race', ['exports', 'rsvp/promise'], function (exports, _rsvpPromise) { - 'use strict'; - - exports.default = race; - - /** - This is a convenient alias for `RSVP.Promise.race`. - - @method race - @static - @for RSVP - @param {Array} array Array of promises. - @param {String} label An optional label. This is useful - for tooling. - */ - - function race(array, label) { - return _rsvpPromise.default.race(array, label); - } -}); -enifed('rsvp/reject', ['exports', 'rsvp/promise'], function (exports, _rsvpPromise) { - 'use strict'; - - exports.default = reject; - - /** - This is a convenient alias for `RSVP.Promise.reject`. - - @method reject - @static - @for RSVP - @param {*} reason value that the returned promise will be rejected with. - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. - */ - - function reject(reason, label) { - return _rsvpPromise.default.reject(reason, label); - } -}); -enifed('rsvp/resolve', ['exports', 'rsvp/promise'], function (exports, _rsvpPromise) { - 'use strict'; - - exports.default = resolve; - - /** - This is a convenient alias for `RSVP.Promise.resolve`. - - @method resolve - @static - @for RSVP - @param {*} value value that the returned promise will be resolved with - @param {String} label optional string for identifying the returned promise. - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` - */ - - function resolve(value, label) { - return _rsvpPromise.default.resolve(value, label); - } -}); -enifed("rsvp/rethrow", ["exports"], function (exports) { - /** - `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event - loop in order to aid debugging. - - Promises A+ specifies that any exceptions that occur with a promise must be - caught by the promises implementation and bubbled to the last handler. For - this reason, it is recommended that you always specify a second rejection - handler function to `then`. However, `RSVP.rethrow` will throw the exception - outside of the promise, so it bubbles up to your console if in the browser, - or domain/cause uncaught exception in Node. `rethrow` will also throw the - error again so the error can be handled by the promise per the spec. - - ```javascript - function throws(){ - throw new Error('Whoops!'); - } - - var promise = new RSVP.Promise(function(resolve, reject){ - throws(); - }); - - promise.catch(RSVP.rethrow).then(function(){ - // Code here doesn't run because the promise became rejected due to an - // error! - }, function (err){ - // handle the error here - }); - ``` - - The 'Whoops' error will be thrown on the next turn of the event loop - and you can watch for it in your console. You can also handle it using a - rejection handler given to `.then` or `.catch` on the returned promise. - - @method rethrow - @static - @for RSVP - @param {Error} reason reason the promise became rejected. - @throws Error - @static - */ - "use strict"; - - exports.default = rethrow; - - function rethrow(reason) { - setTimeout(function () { - throw reason; - }); - throw reason; - } -}); -enifed('rsvp/utils', ['exports'], function (exports) { - 'use strict'; - - exports.objectOrFunction = objectOrFunction; - exports.isFunction = isFunction; - exports.isMaybeThenable = isMaybeThenable; - - function objectOrFunction(x) { - return typeof x === 'function' || typeof x === 'object' && x !== null; - } - - function isFunction(x) { - return typeof x === 'function'; - } - - function isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var _isArray; - if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - _isArray = Array.isArray; - } - - var isArray = _isArray; - - exports.isArray = isArray; - // Date.now is not available in browsers < IE9 - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility - var now = Date.now || function () { - return new Date().getTime(); - }; - - exports.now = now; - function F() {} - - var o_create = Object.create || function (o) { - if (arguments.length > 1) { - throw new Error('Second argument not supported'); - } - if (typeof o !== 'object') { - throw new TypeError('Argument must be an object'); - } - F.prototype = o; - return new F(); - }; - exports.o_create = o_create; -}); -enifed('rsvp', ['exports', 'rsvp/promise', 'rsvp/events', 'rsvp/node', 'rsvp/all', 'rsvp/all-settled', 'rsvp/race', 'rsvp/hash', 'rsvp/hash-settled', 'rsvp/rethrow', 'rsvp/defer', 'rsvp/config', 'rsvp/map', 'rsvp/resolve', 'rsvp/reject', 'rsvp/filter', 'rsvp/asap'], function (exports, _rsvpPromise, _rsvpEvents, _rsvpNode, _rsvpAll, _rsvpAllSettled, _rsvpRace, _rsvpHash, _rsvpHashSettled, _rsvpRethrow, _rsvpDefer, _rsvpConfig, _rsvpMap, _rsvpResolve, _rsvpReject, _rsvpFilter, _rsvpAsap) { - 'use strict'; - - // defaults - _rsvpConfig.config.async = _rsvpAsap.default; - _rsvpConfig.config.after = function (cb) { - setTimeout(cb, 0); - }; - var cast = _rsvpResolve.default; - function async(callback, arg) { - _rsvpConfig.config.async(callback, arg); - } - - function on() { - _rsvpConfig.config['on'].apply(_rsvpConfig.config, arguments); - } - - function off() { - _rsvpConfig.config['off'].apply(_rsvpConfig.config, arguments); - } - - // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` - if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') { - var callbacks = window['__PROMISE_INSTRUMENTATION__']; - _rsvpConfig.configure('instrument', true); - for (var eventName in callbacks) { - if (callbacks.hasOwnProperty(eventName)) { - on(eventName, callbacks[eventName]); - } - } - } - - exports.cast = cast; - exports.Promise = _rsvpPromise.default; - exports.EventTarget = _rsvpEvents.default; - exports.all = _rsvpAll.default; - exports.allSettled = _rsvpAllSettled.default; - exports.race = _rsvpRace.default; - exports.hash = _rsvpHash.default; - exports.hashSettled = _rsvpHashSettled.default; - exports.rethrow = _rsvpRethrow.default; - exports.defer = _rsvpDefer.default; - exports.denodeify = _rsvpNode.default; - exports.configure = _rsvpConfig.configure; - exports.on = on; - exports.off = off; - exports.resolve = _rsvpResolve.default; - exports.reject = _rsvpReject.default; - exports.async = async; - exports.map = _rsvpMap.default; - exports.filter = _rsvpFilter.default; -}); -enifed('rsvp.umd', ['exports', 'rsvp/platform', 'rsvp'], function (exports, _rsvpPlatform, _rsvp) { - 'use strict'; - - var RSVP = { - 'race': _rsvp.race, - 'Promise': _rsvp.Promise, - 'allSettled': _rsvp.allSettled, - 'hash': _rsvp.hash, - 'hashSettled': _rsvp.hashSettled, - 'denodeify': _rsvp.denodeify, - 'on': _rsvp.on, - 'off': _rsvp.off, - 'map': _rsvp.map, - 'filter': _rsvp.filter, - 'resolve': _rsvp.resolve, - 'reject': _rsvp.reject, - 'all': _rsvp.all, - 'rethrow': _rsvp.rethrow, - 'defer': _rsvp.defer, - 'EventTarget': _rsvp.EventTarget, - 'configure': _rsvp.configure, - 'async': _rsvp.async - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function () { - return RSVP; - }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = RSVP; - } else if (typeof _rsvpPlatform.default !== 'undefined') { - _rsvpPlatform.default['RSVP'] = RSVP; - } -}); -enifed("vertex", ["exports"], function (exports) { - /** - * DAG Vertex - * - * @class Vertex - * @constructor - */ - - "use strict"; - - exports.default = Vertex; - - function Vertex(name) { - this.name = name; - this.incoming = {}; - this.incomingNames = []; - this.hasOutgoing = false; - this.value = null; - } -}); -enifed("visit", ["exports"], function (exports) { - "use strict"; - - exports.default = visit; - - function visit(vertex, fn, visited, path) { - var name = vertex.name; - var vertices = vertex.incoming; - var names = vertex.incomingNames; - var len = names.length; - var i; - - if (!visited) { - visited = {}; - } - if (!path) { - path = []; - } - if (visited.hasOwnProperty(name)) { - return; - } - path.push(name); - visited[name] = true; - for (i = 0; i < len; i++) { - visit(vertices[names[i]], fn, visited, path); - } - fn(vertex, path); - path.pop(); - } -}); -requireModule("ember"); - -}()); - -;(function() { -/* globals define, Ember, DS, jQuery */ - - function processEmberShims() { - var shims = { - 'ember': { - 'default': Ember - }, - 'ember-application': { - 'default': Ember.Application - }, - 'ember-array': { - 'default': Ember.Array - }, - 'ember-array/mutable': { - 'default': Ember.MutableArray - }, - 'ember-array/utils': { - 'A': Ember.A, - 'isEmberArray': Ember.isArray, - 'wrap': Ember.makeArray - }, - 'ember-component': { - 'default': Ember.Component - }, - 'ember-components/checkbox': { - 'default': Ember.Checkbox - }, - 'ember-components/text-area': { - 'default': Ember.TextArea - }, - 'ember-components/text-field': { - 'default': Ember.TextField - }, - 'ember-controller': { - 'default': Ember.Controller - }, - 'ember-controller/inject': { - 'default': Ember.inject.controller - }, - 'ember-controller/proxy': { - 'default': Ember.ArrayProxy - }, - 'ember-controllers/sortable': { - 'default': Ember.SortableMixin - }, - 'ember-debug': { - 'log': Ember.debug, - 'inspect': Ember.inspect, - 'run': Ember.runInDebug, - 'warn': Ember.warn - }, - 'ember-debug/container-debug-adapter': { - 'default': Ember.ContainerDebugAdapter - }, - 'ember-debug/data-adapter': { - 'default': Ember.DataAdapter - }, - 'ember-deprecations': { - 'deprecate': Ember.deprecate, - 'deprecateFunc': Ember.deprecateFunc - }, - 'ember-enumerable': { - 'default': Ember.Enumerable - }, - 'ember-evented': { - 'default': Ember.Evented - }, - 'ember-evented/on': { - 'default': Ember.on - }, - 'ember-globals-resolver': { - 'default': Ember.DefaultResolver - }, - 'ember-helper': { - 'default': Ember.Helper, - 'helper': Ember.Helper && Ember.Helper.helper - }, - 'ember-instrumentation': { - 'instrument': Ember.Instrumentation.instrument, - 'reset': Ember.Instrumentation.reset, - 'subscribe': Ember.Instrumentation.subscribe, - 'unsubscribe': Ember.Instrumentation.unsubscribe - }, - 'ember-locations/hash': { - 'default': Ember.HashLocation - }, - 'ember-locations/history': { - 'default': Ember.HistoryLocation - }, - 'ember-locations/none': { - 'default': Ember.NoneLocation - }, - 'ember-map': { - 'default': Ember.Map, - 'withDefault': Ember.MapWithDefault - }, - 'ember-metal/destroy': { - 'default': Ember.destroy - }, - 'ember-metal/events': { - 'addListener': Ember.addListener, - 'removeListener': Ember.removeListener, - 'send': Ember.sendEvent - }, - 'ember-metal/get': { - 'default': Ember.get - }, - 'ember-metal/mixin': { - 'default': Ember.Mixin - }, - 'ember-metal/observer': { - 'default': Ember.observer, - 'addObserver': Ember.addObserver, - 'removeObserver': Ember.removeObserver - }, - 'ember-metal/on-load': { - 'default': Ember.onLoad, - 'run': Ember.runLoadHooks - }, - 'ember-metal/set': { - 'default': Ember.set, - 'setProperties': Ember.setProperties, - 'trySet': Ember.trySet - }, - 'ember-metal/utils': { - 'aliasMethod': Ember.aliasMethod, - 'assert': Ember.assert, - 'cacheFor': Ember.cacheFor, - 'copy': Ember.copy, - }, - 'ember-object': { - 'default': Ember.Object - }, - 'ember-platform': { - 'assign': Ember.merge, - 'create': Ember.create, - 'defineProperty': Ember.platform.defineProperty, - 'hasAccessors': Ember.platform.hasPropertyAccessors, - 'keys': Ember.keys - }, - 'ember-route': { - 'default': Ember.Route - }, - 'ember-router': { - 'default': Ember.Router - }, - 'ember-runloop': { - 'default': Ember.run, - 'begin': Ember.run.begin, - 'bind': Ember.run.bind, - 'cancel': Ember.run.cancel, - 'debounce': Ember.run.debounce, - 'end': Ember.run.end, - 'join': Ember.run.join, - 'later': Ember.run.later, - 'next': Ember.run.next, - 'once': Ember.run.once, - 'schedule': Ember.run.schedule, - 'scheduleOnce': Ember.run.scheduleOnce, - 'throttle': Ember.run.throttle - }, - 'ember-service': { - 'default': Ember.Service - }, - 'ember-service/inject': { - 'default': Ember.inject.service - }, - 'ember-set/ordered': { - 'default': Ember.OrderedSet - }, - 'ember-string': { - 'camelize': Ember.String.camelize, - 'capitalize': Ember.String.capitalize, - 'classify': Ember.String.classify, - 'dasherize': Ember.String.dasherize, - 'decamelize': Ember.String.decamelize, - 'fmt': Ember.String.fmt, - 'htmlSafe': Ember.String.htmlSafe, - 'loc': Ember.String.loc, - 'underscore': Ember.String.underscore, - 'w': Ember.String.w - }, - 'ember-utils': { - 'isBlank': Ember.isBlank, - 'isEmpty': Ember.isEmpty, - 'isNone': Ember.isNone, - 'isPresent': Ember.isPresent, - 'tryInvoke': Ember.tryInvoke, - 'typeOf': Ember.typeOf - } - }; - - // populate `ember/computed` named exports - shims['ember-computed'] = { - 'default': Ember.computed - }; - var computedMacros = [ - "empty","notEmpty", "none", "not", "bool", "match", - "equal", "gt", "gte", "lt", "lte", "alias", "oneWay", - "reads", "readOnly", "deprecatingAlias", - "and", "or", "collect", "sum", "min", "max", - "map", "sort", "setDiff", "mapBy", "mapProperty", - "filter", "filterBy", "filterProperty", "uniq", - "union", "intersect" - ]; - for (var i = 0, l = computedMacros.length; i < l; i++) { - var key = computedMacros[i]; - shims['ember-computed'][key] = Ember.computed[key]; - } - - for (var moduleName in shims) { - generateModule(moduleName, shims[moduleName]); - } - } - - function processTestShims() { - if (Ember.Test) { - var testShims = { - 'ember-test': { - 'default': Ember.Test - }, - 'ember-test/adapter': { - 'default': Ember.Test.Adapter - }, - 'ember-test/qunit-adapter': { - 'default': Ember.Test.QUnitAdapter - } - }; - - for (var moduleName in testShims) { - generateModule(moduleName, testShims[moduleName]); - } - } - } - - function generateModule(name, values) { - define(name, [], function() { - 'use strict'; - - return values; - }); - } - - function generateLazyModule(namespace, name, globalName) { - define(name, [], function() { - 'use strict'; - - var exportObject = {}; - - if (typeof globalName === 'object') { - for (var i = 0, l = globalName.length; i < l; i++) { - exportObject[globalName[i]] = window[namespace][globalName[i]]; - } - } else { - exportObject['default'] = (globalName !== '') ? window[namespace][globalName] : window[namespace]; - } - - return exportObject; - }); - } - - processEmberShims(); - processTestShims(); - generateModule('jquery', { 'default': self.jQuery }); - generateModule('rsvp', { 'default': Ember.RSVP }); -})(); - -;/* globals define */ -define('ember/load-initializers', ['exports', 'ember-load-initializers', 'ember'], function(exports, loadInitializers, Ember) { - Ember['default'].deprecate( - 'Usage of `' + 'ember/load-initializers' + '` module is deprecated, please update to `ember-load-initializers`.', - false, - { id: 'ember-load-initializers.legacy-shims', until: '3.0.0' } - ); - - exports['default'] = loadInitializers['default']; -}); - -;/* globals define */ - -function createDeprecatedModule(moduleId) { - define(moduleId, ['exports', 'ember-resolver/resolver', 'ember'], function(exports, Resolver, Ember) { - Ember['default'].deprecate( - 'Usage of `' + moduleId + '` module is deprecated, please update to `ember-resolver`.', - false, - { id: 'ember-resolver.legacy-shims', until: '3.0.0' } - ); - - exports['default'] = Resolver['default']; - }); -} - -createDeprecatedModule('ember/resolver'); -createDeprecatedModule('resolver'); - -;define('ember-ajax/errors', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports.AjaxError = AjaxError; - exports.InvalidError = InvalidError; - exports.UnauthorizedError = UnauthorizedError; - exports.ForbiddenError = ForbiddenError; - - var EmberError = _ember['default'].Error; - - /** - @class AjaxError - @namespace DS - */ - - function AjaxError(errors) { - var message = arguments.length <= 1 || arguments[1] === undefined ? 'Ajax operation failed' : arguments[1]; - - EmberError.call(this, message); - - this.errors = errors || [{ - title: 'Ajax Error', - detail: message - }]; - } - - AjaxError.prototype = Object.create(EmberError.prototype); - - function InvalidError(errors) { - AjaxError.call(this, errors, 'Request was rejected because it was invalid'); - } - - InvalidError.prototype = Object.create(AjaxError.prototype); - - function UnauthorizedError(errors) { - AjaxError.call(this, errors, 'Ajax authorization failed'); - } - - UnauthorizedError.prototype = Object.create(AjaxError.prototype); - - function ForbiddenError(errors) { - AjaxError.call(this, errors, 'Request was rejected because user is not permitted to perform this operation.'); - } - - ForbiddenError.prototype = Object.create(AjaxError.prototype); -}); -define('ember-ajax/index', ['exports', 'ember-ajax/request'], function (exports, _emberAjaxRequest) { - 'use strict'; - - Object.defineProperty(exports, 'default', { - enumerable: true, - get: function get() { - return _emberAjaxRequest['default']; - } - }); -}); -define('ember-ajax/make-promise', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports['default'] = makePromise; - - var run = _ember['default'].run; - var RSVP = _ember['default'].RSVP; - - function makePromise(settings) { - var type = settings.type || 'GET'; - return new RSVP.Promise(function (resolve, reject) { - settings.success = makeSuccess(resolve); - settings.error = makeError(reject); - _ember['default'].$.ajax(settings); - }, 'ember-ajax: ' + type + ' to ' + settings.url); - } - - function makeSuccess(resolve) { - return function success(response, textStatus, jqXHR) { - run(null, resolve, { - response: response, - textStatus: textStatus, - jqXHR: jqXHR - }); - }; - } - - function makeError(reject) { - return function error(jqXHR, textStatus, errorThrown) { - run(null, reject, { - jqXHR: jqXHR, - textStatus: textStatus, - errorThrown: errorThrown - }); - }; - } -}); -define('ember-ajax/raw', ['exports', 'ember-ajax/make-promise', 'ember-ajax/utils/parse-args', 'ember'], function (exports, _emberAjaxMakePromise, _emberAjaxUtilsParseArgs, _ember) { - 'use strict'; - - var _slicedToArray = (function () { - function sliceIterator(arr, i) { - var _arr = [];var _n = true;var _d = false;var _e = undefined;try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value);if (i && _arr.length === i) break; - } - } catch (err) { - _d = true;_e = err; - } finally { - try { - if (!_n && _i['return']) _i['return'](); - } finally { - if (_d) throw _e; - } - }return _arr; - }return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError('Invalid attempt to destructure non-iterable instance'); - } - }; - })(); - - exports['default'] = raw; - - var deprecate = _ember['default'].deprecate; - - /* - * Same as `request` except it resolves an object with `{response, textStatus, - * jqXHR}`, useful if you need access to the jqXHR object for headers, etc. - */ - function raw() { - deprecate('ember-ajax/raw is deprecated and will be removed in ember-ajax@2.0.0', false, { id: 'ember-ajax.raw' }); - - var _parseArgs$apply = _emberAjaxUtilsParseArgs['default'].apply(null, arguments); - - var _parseArgs$apply2 = _slicedToArray(_parseArgs$apply, 3); - - var url = _parseArgs$apply2[0]; - var type = _parseArgs$apply2[1]; - var settings = _parseArgs$apply2[2]; - - if (!settings) { - settings = {}; - } - settings.url = url; - settings.type = type; - return (0, _emberAjaxMakePromise['default'])(settings); - } -}); -define('ember-ajax/request', ['exports', 'ember-ajax/raw', 'ember'], function (exports, _emberAjaxRaw, _ember) { - 'use strict'; - - exports['default'] = request; - - var deprecate = _ember['default'].deprecate; - - /* - * jQuery.ajax wrapper, supports the same signature except providing - * `success` and `error` handlers will throw an error (use promises instead) - * and it resolves only the response (no access to jqXHR or textStatus). - */ - function request() { - deprecate('ember-ajax/request is deprecated and will be removed in ember-ajax@2.0.0', false, { id: 'ember-ajax.raw' }); - return _emberAjaxRaw['default'].apply(undefined, arguments).then(function (result) { - return result.response; - }, null, 'ember-ajax: unwrap raw ajax response'); - } -}); -define('ember-ajax/services/ajax', ['exports', 'ember', 'ember-ajax/errors', 'ember-ajax/utils/parse-response-headers'], function (exports, _ember, _emberAjaxErrors, _emberAjaxUtilsParseResponseHeaders) { - 'use strict'; - - var deprecate = _ember['default'].deprecate; - var get = _ember['default'].get; - var isBlank = _ember['default'].isBlank; - - /** - ### Headers customization - - Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary - headers can be set as key/value pairs on the `RESTAdapter`'s `headers` - object and Ember Data will send them along with each ajax request. - - ```app/services/ajax - import AjaxService from 'ember-ajax/services/ajax'; - - export default AjaxService.extend({ - headers: { - "API_KEY": "secret key", - "ANOTHER_HEADER": "Some header value" - } - }); - ``` - - `headers` can also be used as a computed property to support dynamic - headers. - - ```app/services/ajax.js - import Ember from 'ember'; - import AjaxService from 'ember-ajax/services/ajax'; - - export default AjaxService.extend({ - session: Ember.inject.service(), - headers: Ember.computed("session.authToken", function() { - return { - "API_KEY": this.get("session.authToken"), - "ANOTHER_HEADER": "Some header value" - }; - }) - }); - ``` - - In some cases, your dynamic headers may require data from some - object outside of Ember's observer system (for example - `document.cookie`). You can use the - [volatile](/api/classes/Ember.ComputedProperty.html#method_volatile) - function to set the property into a non-cached mode causing the headers to - be recomputed with every request. - - ```app/services/ajax.js - import Ember from 'ember'; - import AjaxService from 'ember-ajax/services/ajax'; - - export default AjaxService.extend({ - session: Ember.inject.service(), - headers: Ember.computed("session.authToken", function() { - return { - "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), - "ANOTHER_HEADER": "Some header value" - }; - }).volatile() - }); - ``` - - **/ - exports['default'] = _ember['default'].Service.extend({ - - request: function request(url, options) { - var _this = this; - - var opts; - - if (arguments.length > 2 || typeof options === 'string') { - deprecate('ember-ajax/ajax#request calling request with `type` is deprecated and will be removed in ember-ajax@1.0.0. If you want to specify a type pass an object like {type: \'DELETE\'}', false, { id: 'ember-ajax.service.request' }); - - if (arguments.length > 2) { - opts = arguments[2]; - opts.type = options; - } else { - opts = { type: options }; - } - } else { - opts = options; - } - - var hash = this.options(url, opts); - - return new _ember['default'].RSVP.Promise(function (resolve, reject) { - - hash.success = function (payload, textStatus, jqXHR) { - var response = _this.handleResponse(jqXHR.status, (0, _emberAjaxUtilsParseResponseHeaders['default'])(jqXHR.getAllResponseHeaders()), payload); - - if (response instanceof _emberAjaxErrors.AjaxError) { - reject(response); - } else { - resolve(response); - } - }; - - hash.error = function (jqXHR, textStatus, errorThrown) { - var error = undefined; - - if (!(error instanceof Error)) { - if (errorThrown instanceof Error) { - error = errorThrown; - } else { - error = _this.handleResponse(jqXHR.status, (0, _emberAjaxUtilsParseResponseHeaders['default'])(jqXHR.getAllResponseHeaders()), _this.parseErrorResponse(jqXHR.responseText) || errorThrown); - } - } - reject(error); - }; - - _ember['default'].$.ajax(hash); - }, 'ember-ajax: ' + hash.type + ' to ' + url); - }, - - // calls `request()` but forces `options.type` to `POST` - post: function post(url, options) { - return this.request(url, this._addTypeToOptionsFor(options, 'POST')); - }, - - // calls `request()` but forces `options.type` to `PUT` - put: function put(url, options) { - return this.request(url, this._addTypeToOptionsFor(options, 'PUT')); - }, - - // calls `request()` but forces `options.type` to `PATCH` - patch: function patch(url, options) { - return this.request(url, this._addTypeToOptionsFor(options, 'PATCH')); - }, - - // calls `request()` but forces `options.type` to `DELETE` - del: function del(url, options) { - return this.request(url, this._addTypeToOptionsFor(options, 'DELETE')); - }, - - // forcibly manipulates the options hash to include the HTTP method on the type key - _addTypeToOptionsFor: function _addTypeToOptionsFor(options, method) { - options = options || {}; - options.type = method; - return options; - }, - - /** - @method options - @private - @param {String} url - @param {Object} options - @return {Object} - */ - options: function options(url, _options) { - var hash = _options || {}; - hash.url = this._buildURL(url); - hash.type = hash.type || 'GET'; - hash.dataType = hash.dataType || 'json'; - hash.context = this; - - var headers = get(this, 'headers'); - if (headers !== undefined) { - hash.beforeSend = function (xhr) { - Object.keys(headers).forEach(function (key) { - return xhr.setRequestHeader(key, headers[key]); - }); - }; - } - - return hash; - }, - - _buildURL: function _buildURL(url) { - var host = get(this, 'host'); - if (isBlank(host)) { - return url; - } - var startsWith = String.prototype.startsWith || function (searchString, position) { - position = position || 0; - return this.indexOf(searchString, position) === position; - }; - if (startsWith.call(url, '/')) { - return '' + host + url; - } else { - return host + '/' + url; - } - }, - - /** - Takes an ajax response, and returns the json payload or an error. - By default this hook just returns the json payload passed to it. - You might want to override it in two cases: - 1. Your API might return useful results in the response headers. - Response headers are passed in as the second argument. - 2. Your API might return errors as successful responses with status code - 200 and an Errors text or object. - @method handleResponse - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Object | DS.AdapterError} response - */ - handleResponse: function handleResponse(status, headers, payload) { - if (this.isSuccess(status, headers, payload)) { - return payload; - } else if (this.isUnauthorized(status, headers, payload)) { - return new _emberAjaxErrors.UnauthorizedError(payload.errors); - } else if (this.isForbidden(status, headers, payload)) { - return new _emberAjaxErrors.ForbiddenError(payload.errors); - } else if (this.isInvalid(status, headers, payload)) { - return new _emberAjaxErrors.InvalidError(payload.errors); - } - - var errors = this.normalizeErrorResponse(status, headers, payload); - - return new _emberAjaxErrors.AjaxError(errors); - }, - - /** - Default `handleResponse` implementation uses this hook to decide if the - response is a an authorized error. - @method isUnauthorized - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Boolean} - */ - isUnauthorized: function isUnauthorized(status /*, headers, payload */) { - return status === 401; - }, - - /** - Default `handleResponse` implementation uses this hook to decide if the - response is a forbidden error. - @method isForbidden - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Boolean} - */ - isForbidden: function isForbidden(status /*, headers, payload */) { - return status === 403; - }, - - /** - Default `handleResponse` implementation uses this hook to decide if the - response is a an invalid error. - @method isInvalid - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Boolean} - */ - isInvalid: function isInvalid(status /*, headers, payload */) { - return status === 422; - }, - - /** - Default `handleResponse` implementation uses this hook to decide if the - response is a success. - @method isSuccess - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Boolean} - */ - isSuccess: function isSuccess(status /*, headers, payload */) { - return status >= 200 && status < 300 || status === 304; - }, - - /** - @method parseErrorResponse - @private - @param {String} responseText - @return {Object} - */ - parseErrorResponse: function parseErrorResponse(responseText) { - var json = responseText; - - try { - json = _ember['default'].$.parseJSON(responseText); - } catch (e) {} - - return json; - }, - - /** - @method normalizeErrorResponse - @private - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Object} errors payload - */ - normalizeErrorResponse: function normalizeErrorResponse(status, headers, payload) { - if (payload && typeof payload === 'object' && payload.errors) { - return payload.errors; - } else { - return [{ - status: '' + status, - title: "The backend responded with an error", - detail: '' + payload - }]; - } - } - }); -}); -define("ember-ajax/utils/parse-args", ["exports"], function (exports) { - "use strict"; - - var _slicedToArray = (function () { - function sliceIterator(arr, i) { - var _arr = [];var _n = true;var _d = false;var _e = undefined;try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value);if (i && _arr.length === i) break; - } - } catch (err) { - _d = true;_e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - }return _arr; - }return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; - })(); - - exports["default"] = parseArgs; - - function parseArgs() { - var args = [].slice.apply(arguments); - if (args.length === 1) { - if (typeof args[0] === "string") { - var _args = _slicedToArray(args, 1); - - var url = _args[0]; - - return [url]; - } else { - var _args2 = _slicedToArray(args, 1); - - var options = _args2[0]; - var url = options.url; - - delete options.url; - var type = options.type || options.method; - delete options.type; - delete options.method; - return [url, type, options]; - } - } - if (args.length === 2) { - var _args3 = _slicedToArray(args, 1); - - var url = _args3[0]; - - if (typeof args[1] === 'object') { - var options = args[1]; - var type = options.type || options.method; - delete options.type; - delete options.method; - return [url, type, options]; - } else { - var type = args[1]; - return [url, type]; - } - } - return args; - } -}); -define('ember-ajax/utils/parse-response-headers', ['exports'], function (exports) { - 'use strict'; - - exports['default'] = parseResponseHeaders; - - function parseResponseHeaders(headerStr) { - var headers = Object.create(null); - if (!headerStr) { - return headers; - } - - var headerPairs = headerStr.split('\r\n'); - for (var i = 0; i < headerPairs.length; i++) { - var headerPair = headerPairs[i]; - // Can't use split() here because it does the wrong thing - // if the header value has the string ": " in it. - var index = headerPair.indexOf(': '); - if (index > 0) { - var key = headerPair.substring(0, index); - var val = headerPair.substring(index + 2); - headers[key] = val; - } - } - - return headers; - } -}); -define('ember-cli-app-version/components/app-version', ['exports', 'ember', 'ember-cli-app-version/templates/app-version'], function (exports, _ember, _emberCliAppVersionTemplatesAppVersion) { - 'use strict'; - - exports['default'] = _ember['default'].Component.extend({ - tagName: 'span', - layout: _emberCliAppVersionTemplatesAppVersion['default'] - }); -}); -define('ember-cli-app-version/initializer-factory', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports['default'] = initializerFactory; - - var classify = _ember['default'].String.classify; - - function initializerFactory(name, version) { - var registered = false; - - return function () { - if (!registered && name && version) { - var appName = classify(name); - _ember['default'].libraries.register(appName, version); - registered = true; - } - }; - } -}); -define("ember-cli-app-version/templates/app-version", ["exports"], function (exports) { - "use strict"; - - exports["default"] = Ember.HTMLBars.template((function () { - return { - meta: { - "fragmentReason": { - "name": "missing-wrapper", - "problems": ["wrong-type"] - }, - "revision": "Ember@2.4.1", - "loc": { - "source": null, - "start": { - "line": 1, - "column": 0 - }, - "end": { - "line": 2, - "column": 0 - } - }, - "moduleName": "modules/ember-cli-app-version/templates/app-version.hbs" - }, - isEmpty: false, - arity: 0, - cachedFragment: null, - hasRendered: false, - buildFragment: function buildFragment(dom) { - var el0 = dom.createDocumentFragment(); - var el1 = dom.createComment(""); - dom.appendChild(el0, el1); - var el1 = dom.createTextNode("\n"); - dom.appendChild(el0, el1); - return el0; - }, - buildRenderNodes: function buildRenderNodes(dom, fragment, contextualElement) { - var morphs = new Array(1); - morphs[0] = dom.createMorphAt(fragment, 0, 0, contextualElement); - dom.insertBoundary(fragment, 0); - return morphs; - }, - statements: [["content", "version", ["loc", [null, [1, 0], [1, 11]]]]], - locals: [], - templates: [] - }; - })()); -}); -define('ember-data/-private/adapters/build-url-mixin', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - var get = _ember['default'].get; - - /** - - WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 - - ## Using BuildURLMixin - - To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. - The default behaviour is designed for RESTAdapter. - - ### Example - - ```javascript - export default DS.Adapter.extend(BuildURLMixin, { - findRecord: function(store, type, id, snapshot) { - var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); - return this.ajax(url, 'GET'); - } - }); - ``` - - ### Attributes - - The `host` and `namespace` attributes will be used if defined, and are optional. - - @class BuildURLMixin - @namespace DS - */ - exports['default'] = _ember['default'].Mixin.create({ - /** - Builds a URL for a given type and optional ID. - By default, it pluralizes the type's name (for example, 'post' - becomes 'posts' and 'person' becomes 'people'). To override the - pluralization see [pathForType](#method_pathForType). - If an ID is specified, it adds the ID to the path generated - for the type, separated by a `/`. - When called by RESTAdapter.findMany() the `id` and `snapshot` parameters - will be arrays of ids and snapshots. - @method buildURL - @param {String} modelName - @param {(String|Array|Object)} id single id or array of ids or query - @param {(DS.Snapshot|Array)} snapshot single snapshot or array of snapshots - @param {String} requestType - @param {Object} query object of query parameters to send for query requests. - @return {String} url - */ - buildURL: function buildURL(modelName, id, snapshot, requestType, query) { - switch (requestType) { - case 'findRecord': - return this.urlForFindRecord(id, modelName, snapshot); - case 'findAll': - return this.urlForFindAll(modelName); - case 'query': - return this.urlForQuery(query, modelName); - case 'queryRecord': - return this.urlForQueryRecord(query, modelName); - case 'findMany': - return this.urlForFindMany(id, modelName, snapshot); - case 'findHasMany': - return this.urlForFindHasMany(id, modelName); - case 'findBelongsTo': - return this.urlForFindBelongsTo(id, modelName); - case 'createRecord': - return this.urlForCreateRecord(modelName, snapshot); - case 'updateRecord': - return this.urlForUpdateRecord(id, modelName, snapshot); - case 'deleteRecord': - return this.urlForDeleteRecord(id, modelName, snapshot); - default: - return this._buildURL(modelName, id); - } - }, - - /** - @method _buildURL - @private - @param {String} modelName - @param {String} id - @return {String} url - */ - _buildURL: function _buildURL(modelName, id) { - var url = []; - var host = get(this, 'host'); - var prefix = this.urlPrefix(); - var path; - - if (modelName) { - path = this.pathForType(modelName); - if (path) { - url.push(path); - } - } - - if (id) { - url.push(encodeURIComponent(id)); - } - if (prefix) { - url.unshift(prefix); - } - - url = url.join('/'); - if (!host && url && url.charAt(0) !== '/') { - url = '/' + url; - } - - return url; - }, - - /** - * @method urlForFindRecord - * @param {String} id - * @param {String} modelName - * @param {DS.Snapshot} snapshot - * @return {String} url - */ - urlForFindRecord: function urlForFindRecord(id, modelName, snapshot) { - return this._buildURL(modelName, id); - }, - - /** - * @method urlForFindAll - * @param {String} modelName - * @return {String} url - */ - urlForFindAll: function urlForFindAll(modelName) { - return this._buildURL(modelName); - }, - - /** - * @method urlForQuery - * @param {Object} query - * @param {String} modelName - * @return {String} url - */ - urlForQuery: function urlForQuery(query, modelName) { - return this._buildURL(modelName); - }, - - /** - * @method urlForQueryRecord - * @param {Object} query - * @param {String} modelName - * @return {String} url - */ - urlForQueryRecord: function urlForQueryRecord(query, modelName) { - return this._buildURL(modelName); - }, - - /** - * @method urlForFindMany - * @param {Array} ids - * @param {String} modelName - * @param {Array} snapshots - * @return {String} url - */ - urlForFindMany: function urlForFindMany(ids, modelName, snapshots) { - return this._buildURL(modelName); - }, - - /** - * @method urlForFindHasMany - * @param {String} id - * @param {String} modelName - * @return {String} url - */ - urlForFindHasMany: function urlForFindHasMany(id, modelName) { - return this._buildURL(modelName, id); - }, - - /** - * @method urlForFindBelongTo - * @param {String} id - * @param {String} modelName - * @return {String} url - */ - urlForFindBelongsTo: function urlForFindBelongsTo(id, modelName) { - return this._buildURL(modelName, id); - }, - - /** - * @method urlForCreateRecord - * @param {String} modelName - * @param {DS.Snapshot} snapshot - * @return {String} url - */ - urlForCreateRecord: function urlForCreateRecord(modelName, snapshot) { - return this._buildURL(modelName); - }, - - /** - * @method urlForUpdateRecord - * @param {String} id - * @param {String} modelName - * @param {DS.Snapshot} snapshot - * @return {String} url - */ - urlForUpdateRecord: function urlForUpdateRecord(id, modelName, snapshot) { - return this._buildURL(modelName, id); - }, - - /** - * @method urlForDeleteRecord - * @param {String} id - * @param {String} modelName - * @param {DS.Snapshot} snapshot - * @return {String} url - */ - urlForDeleteRecord: function urlForDeleteRecord(id, modelName, snapshot) { - return this._buildURL(modelName, id); - }, - - /** - @method urlPrefix - @private - @param {String} path - @param {String} parentURL - @return {String} urlPrefix - */ - urlPrefix: function urlPrefix(path, parentURL) { - var host = get(this, 'host'); - var namespace = get(this, 'namespace'); - - if (!host || host === '/') { - host = ''; - } - - if (path) { - // Protocol relative url - if (/^\/\//.test(path) || /http(s)?:\/\//.test(path)) { - // Do nothing, the full host is already included. - return path; - - // Absolute path - } else if (path.charAt(0) === '/') { - return '' + host + path; - // Relative path - } else { - return parentURL + '/' + path; - } - } - - // No path provided - var url = []; - if (host) { - url.push(host); - } - if (namespace) { - url.push(namespace); - } - return url.join('/'); - }, - - /** - Determines the pathname for a given type. - By default, it pluralizes the type's name (for example, - 'post' becomes 'posts' and 'person' becomes 'people'). - ### Pathname customization - For example if you have an object LineItem with an - endpoint of "/line_items/". - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.RESTAdapter.extend({ - pathForType: function(modelName) { - var decamelized = Ember.String.decamelize(modelName); - return Ember.String.pluralize(decamelized); - } - }); - ``` - @method pathForType - @param {String} modelName - @return {String} path - **/ - pathForType: function pathForType(modelName) { - var camelized = _ember['default'].String.camelize(modelName); - return _ember['default'].String.pluralize(camelized); - } - }); -}); -define('ember-data/-private/adapters/errors', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { - 'use strict'; - - exports.AdapterError = AdapterError; - exports.InvalidError = InvalidError; - exports.TimeoutError = TimeoutError; - exports.AbortError = AbortError; - exports.errorsHashToArray = errorsHashToArray; - exports.errorsArrayToHash = errorsArrayToHash; - - var EmberError = _ember['default'].Error; - - var SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/; - var SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/; - var PRIMARY_ATTRIBUTE_KEY = 'base'; - - /** - @class AdapterError - @namespace DS - */ - - function AdapterError(errors) { - var message = arguments.length <= 1 || arguments[1] === undefined ? 'Adapter operation failed' : arguments[1]; - - this.isAdapterError = true; - EmberError.call(this, message); - - this.errors = errors || [{ - title: 'Adapter Error', - detail: message - }]; - } - - AdapterError.prototype = Object.create(EmberError.prototype); - - /** - A `DS.InvalidError` is used by an adapter to signal the external API - was unable to process a request because the content was not - semantically correct or meaningful per the API. Usually this means a - record failed some form of server side validation. When a promise - from an adapter is rejected with a `DS.InvalidError` the record will - transition to the `invalid` state and the errors will be set to the - `errors` property on the record. - - For Ember Data to correctly map errors to their corresponding - properties on the model, Ember Data expects each error to be - a valid json-api error object with a `source/pointer` that matches - the property name. For example if you had a Post model that - looked like this. - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - title: DS.attr('string'), - content: DS.attr('string') - }); - ``` - - To show an error from the server related to the `title` and - `content` properties your adapter could return a promise that - rejects with a `DS.InvalidError` object that looks like this: - - ```app/adapters/post.js - import Ember from 'ember'; - import DS from 'ember-data'; - - export default DS.RESTAdapter.extend({ - updateRecord: function() { - // Fictional adapter that always rejects - return Ember.RSVP.reject(new DS.InvalidError([ - { - detail: 'Must be unique', - source: { pointer: '/data/attributes/title' } - }, - { - detail: 'Must not be blank', - source: { pointer: '/data/attributes/content'} - } - ])); - } - }); - ``` - - Your backend may use different property names for your records the - store will attempt extract and normalize the errors using the - serializer's `extractErrors` method before the errors get added to - the the model. As a result, it is safe for the `InvalidError` to - wrap the error payload unaltered. - - @class InvalidError - @namespace DS - */ - - function InvalidError(errors) { - (0, _emberDataPrivateDebug.assert)('`InvalidError` expects json-api formatted errors array.', _ember['default'].isArray(errors || [])); - AdapterError.call(this, errors, 'The adapter rejected the commit because it was invalid'); - } - - InvalidError.prototype = Object.create(AdapterError.prototype); - - /** - @class TimeoutError - @namespace DS - */ - - function TimeoutError() { - AdapterError.call(this, null, 'The adapter operation timed out'); - } - - TimeoutError.prototype = Object.create(AdapterError.prototype); - - /** - @class AbortError - @namespace DS - */ - - function AbortError() { - AdapterError.call(this, null, 'The adapter operation was aborted'); - } - - AbortError.prototype = Object.create(AdapterError.prototype); - - /** - @method errorsHashToArray - @private - */ - - function errorsHashToArray(errors) { - var out = []; - - if (_ember['default'].isPresent(errors)) { - Object.keys(errors).forEach(function (key) { - var messages = _ember['default'].makeArray(errors[key]); - for (var i = 0; i < messages.length; i++) { - var title = 'Invalid Attribute'; - var pointer = '/data/attributes/' + key; - if (key === PRIMARY_ATTRIBUTE_KEY) { - title = 'Invalid Document'; - pointer = '/data'; - } - out.push({ - title: title, - detail: messages[i], - source: { - pointer: pointer - } - }); - } - }); - } - - return out; - } - - /** - @method errorsArrayToHash - @private - */ - - function errorsArrayToHash(errors) { - var out = {}; - - if (_ember['default'].isPresent(errors)) { - errors.forEach(function (error) { - if (error.source && error.source.pointer) { - var key = error.source.pointer.match(SOURCE_POINTER_REGEXP); - - if (key) { - key = key[2]; - } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) { - key = PRIMARY_ATTRIBUTE_KEY; - } - - if (key) { - out[key] = out[key] || []; - out[key].push(error.detail || error.title); - } - } - }); - } - - return out; - } -}); -define("ember-data/-private/adapters", ["exports", "ember-data/adapters/json-api", "ember-data/adapters/rest"], function (exports, _emberDataAdaptersJsonApi, _emberDataAdaptersRest) { - /** - @module ember-data - */ - - "use strict"; - - exports.JSONAPIAdapter = _emberDataAdaptersJsonApi["default"]; - exports.RESTAdapter = _emberDataAdaptersRest["default"]; -}); -define('ember-data/-private/core', ['exports', 'ember', 'ember-data/version'], function (exports, _ember, _emberDataVersion) { - 'use strict'; - - /** - @module ember-data - */ - - /** - All Ember Data methods and functions are defined inside of this namespace. - - @class DS - @static - */ - - /** - @property VERSION - @type String - @static - */ - var DS = _ember['default'].Namespace.create({ - VERSION: _emberDataVersion['default'] - }); - - if (_ember['default'].libraries) { - _ember['default'].libraries.registerCoreLibrary('Ember Data', DS.VERSION); - } - - exports['default'] = DS; -}); -define('ember-data/-private/debug', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports.assert = assert; - exports.debug = debug; - exports.deprecate = deprecate; - exports.info = info; - exports.runInDebug = runInDebug; - exports.warn = warn; - exports.debugSeal = debugSeal; - - function assert() { - return _ember['default'].assert.apply(_ember['default'], arguments); - } - - function debug() { - return _ember['default'].debug.apply(_ember['default'], arguments); - } - - function deprecate() { - return _ember['default'].deprecate.apply(_ember['default'], arguments); - } - - function info() { - return _ember['default'].info.apply(_ember['default'], arguments); - } - - function runInDebug() { - return _ember['default'].runInDebug.apply(_ember['default'], arguments); - } - - function warn() { - return _ember['default'].warn.apply(_ember['default'], arguments); - } - - function debugSeal() { - return _ember['default'].debugSeal.apply(_ember['default'], arguments); - } -}); -define('ember-data/-private/ext/date', ['exports', 'ember'], function (exports, _ember) { - /** - @module ember-data - */ - - 'use strict'; - - /** - Date.parse with progressive enhancement for ISO 8601 - - © 2011 Colin Snover - - Released under MIT license. - - @class Date - @namespace Ember - @static - */ - _ember['default'].Date = _ember['default'].Date || {}; - - var origParse = Date.parse; - var numericKeys = [1, 4, 5, 6, 7, 10, 11]; - - /** - @method parse - @param {Date} date - @return {Number} timestamp - */ - _ember['default'].Date.parse = function (date) { - var timestamp, struct; - var minutesOffset = 0; - - // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string - // before falling back to any implementation-specific date parsing, so that’s what we do, even if native - // implementations could be faster - // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm - if (struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date)) { - // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC - for (var i = 0, k; k = numericKeys[i]; ++i) { - struct[k] = +struct[k] || 0; - } - - // allow undefined days and months - struct[2] = (+struct[2] || 1) - 1; - struct[3] = +struct[3] || 1; - - if (struct[8] !== 'Z' && struct[9] !== undefined) { - minutesOffset = struct[10] * 60 + struct[11]; - - if (struct[9] === '+') { - minutesOffset = 0 - minutesOffset; - } - } - - timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); - } else { - timestamp = origParse ? origParse(date) : NaN; - } - - return timestamp; - }; - - if (_ember['default'].EXTEND_PROTOTYPES === true || _ember['default'].EXTEND_PROTOTYPES.Date) { - Date.parse = _ember['default'].Date.parse; - } -}); -define('ember-data/-private/features', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports['default'] = isEnabled; - - function isEnabled() { - var _Ember$FEATURES; - - return (_Ember$FEATURES = _ember['default'].FEATURES).isEnabled.apply(_Ember$FEATURES, arguments); - } -}); -define("ember-data/-private/initializers/data-adapter", ["exports", "ember-data/-private/system/debug/debug-adapter"], function (exports, _emberDataPrivateSystemDebugDebugAdapter) { - "use strict"; - - exports["default"] = initializeDebugAdapter; - - /** - Configures a registry with injections on Ember applications - for the Ember-Data store. Accepts an optional namespace argument. - - @method initializeStoreInjections - @param {Ember.Registry} registry - */ - function initializeDebugAdapter(registry) { - registry.register('data-adapter:main', _emberDataPrivateSystemDebugDebugAdapter["default"]); - } -}); -define('ember-data/-private/initializers/store-injections', ['exports'], function (exports) { - 'use strict'; - - exports['default'] = initializeStoreInjections; - - /** - Configures a registry with injections on Ember applications - for the Ember-Data store. Accepts an optional namespace argument. - - @method initializeStoreInjections - @param {Ember.Registry} registry - */ - function initializeStoreInjections(registry) { - // registry.injection for Ember < 2.1.0 - // application.inject for Ember 2.1.0+ - var inject = registry.inject || registry.injection; - inject.call(registry, 'controller', 'store', 'service:store'); - inject.call(registry, 'route', 'store', 'service:store'); - inject.call(registry, 'data-adapter', 'store', 'service:store'); - } -}); -define("ember-data/-private/initializers/store", ["exports", "ember-data/-private/system/store", "ember-data/-private/serializers", "ember-data/-private/adapters"], function (exports, _emberDataPrivateSystemStore, _emberDataPrivateSerializers, _emberDataPrivateAdapters) { - "use strict"; - - exports["default"] = initializeStore; - - function has(applicationOrRegistry, fullName) { - if (applicationOrRegistry.has) { - // < 2.1.0 - return applicationOrRegistry.has(fullName); - } else { - // 2.1.0+ - return applicationOrRegistry.hasRegistration(fullName); - } - } - - /** - Configures a registry for use with an Ember-Data - store. Accepts an optional namespace argument. - - @method initializeStore - @param {Ember.Registry} registry - */ - function initializeStore(registry) { - // registry.optionsForType for Ember < 2.1.0 - // application.registerOptionsForType for Ember 2.1.0+ - var registerOptionsForType = registry.registerOptionsForType || registry.optionsForType; - registerOptionsForType.call(registry, 'serializer', { singleton: false }); - registerOptionsForType.call(registry, 'adapter', { singleton: false }); - - registry.register('serializer:-default', _emberDataPrivateSerializers.JSONSerializer); - registry.register('serializer:-rest', _emberDataPrivateSerializers.RESTSerializer); - registry.register('adapter:-rest', _emberDataPrivateAdapters.RESTAdapter); - - registry.register('adapter:-json-api', _emberDataPrivateAdapters.JSONAPIAdapter); - registry.register('serializer:-json-api', _emberDataPrivateSerializers.JSONAPISerializer); - - if (!has(registry, 'service:store')) { - registry.register('service:store', _emberDataPrivateSystemStore["default"]); - } - } -}); -define('ember-data/-private/initializers/transforms', ['exports', 'ember-data/-private/transforms'], function (exports, _emberDataPrivateTransforms) { - 'use strict'; - - exports['default'] = initializeTransforms; - - /** - Configures a registry for use with Ember-Data - transforms. - - @method initializeTransforms - @param {Ember.Registry} registry - */ - function initializeTransforms(registry) { - registry.register('transform:boolean', _emberDataPrivateTransforms.BooleanTransform); - registry.register('transform:date', _emberDataPrivateTransforms.DateTransform); - registry.register('transform:number', _emberDataPrivateTransforms.NumberTransform); - registry.register('transform:string', _emberDataPrivateTransforms.StringTransform); - } -}); -define('ember-data/-private/instance-initializers/initialize-store-service', ['exports'], function (exports) { - 'use strict'; - - exports['default'] = initializeStoreService; - - /** - Configures a registry for use with an Ember-Data - store. - - @method initializeStore - @param {Ember.ApplicationInstance} applicationOrRegistry - */ - function initializeStoreService(application) { - var container = application.lookup ? application : application.container; - // Eagerly generate the store so defaultStore is populated. - container.lookup('service:store'); - } -}); -define("ember-data/-private/serializers", ["exports", "ember-data/serializers/json-api", "ember-data/serializers/json", "ember-data/serializers/rest"], function (exports, _emberDataSerializersJsonApi, _emberDataSerializersJson, _emberDataSerializersRest) { - /** - @module ember-data - */ - - "use strict"; - - exports.JSONAPISerializer = _emberDataSerializersJsonApi["default"]; - exports.JSONSerializer = _emberDataSerializersJson["default"]; - exports.RESTSerializer = _emberDataSerializersRest["default"]; -}); -define("ember-data/-private/system/clone-null", ["exports", "ember-data/-private/system/empty-object"], function (exports, _emberDataPrivateSystemEmptyObject) { - "use strict"; - - exports["default"] = cloneNull; - - function cloneNull(source) { - var clone = new _emberDataPrivateSystemEmptyObject["default"](); - for (var key in source) { - clone[key] = source[key]; - } - return clone; - } -}); -define('ember-data/-private/system/coerce-id', ['exports'], function (exports) { - 'use strict'; - - exports['default'] = coerceId; - - // Used by the store to normalize IDs entering the store. Despite the fact - // that developers may provide IDs as numbers (e.g., `store.findRecord('person', 1)`), - // it is important that internally we use strings, since IDs may be serialized - // and lose type information. For example, Ember's router may put a record's - // ID into the URL, and if we later try to deserialize that URL and find the - // corresponding record, we will not know if it is a string or a number. - - function coerceId(id) { - return id == null || id === '' ? null : id + ''; - } -}); -define('ember-data/-private/system/container-proxy', ['exports', 'ember-data/-private/debug'], function (exports, _emberDataPrivateDebug) { - 'use strict'; - - exports['default'] = ContainerProxy; - - /* - This is used internally to enable deprecation of container paths and provide - a decent message to the user indicating how to fix the issue. - - @class ContainerProxy - @namespace DS - @private - */ - function ContainerProxy(container) { - this.container = container; - } - - ContainerProxy.prototype.aliasedFactory = function (path, preLookup) { - var _this = this; - - return { - create: function create() { - if (preLookup) { - preLookup(); - } - - return _this.container.lookup(path); - } - }; - }; - - ContainerProxy.prototype.registerAlias = function (source, dest, preLookup) { - var factory = this.aliasedFactory(dest, preLookup); - - return this.container.register(source, factory); - }; - - ContainerProxy.prototype.registerDeprecation = function (deprecated, valid) { - var preLookupCallback = function preLookupCallback() { - (0, _emberDataPrivateDebug.deprecate)('You tried to look up \'' + deprecated + '\', but this has been deprecated in favor of \'' + valid + '\'.', false, { - id: 'ds.store.deprecated-lookup', - until: '2.0.0' - }); - }; - - return this.registerAlias(deprecated, valid, preLookupCallback); - }; - - ContainerProxy.prototype.registerDeprecations = function (proxyPairs) { - var i, proxyPair, deprecated, valid; - - for (i = proxyPairs.length; i > 0; i--) { - proxyPair = proxyPairs[i - 1]; - deprecated = proxyPair['deprecated']; - valid = proxyPair['valid']; - - this.registerDeprecation(deprecated, valid); - } - }; -}); -define('ember-data/-private/system/debug/debug-adapter', ['exports', 'ember', 'ember-data/model'], function (exports, _ember, _emberDataModel) { - /** - @module ember-data - */ - 'use strict'; - - var get = _ember['default'].get; - var capitalize = _ember['default'].String.capitalize; - var underscore = _ember['default'].String.underscore; - var assert = _ember['default'].assert; - - /* - Extend `Ember.DataAdapter` with ED specific code. - - @class DebugAdapter - @namespace DS - @extends Ember.DataAdapter - @private - */ - exports['default'] = _ember['default'].DataAdapter.extend({ - getFilters: function getFilters() { - return [{ name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' }]; - }, - - detect: function detect(typeClass) { - return typeClass !== _emberDataModel['default'] && _emberDataModel['default'].detect(typeClass); - }, - - columnsForType: function columnsForType(typeClass) { - var columns = [{ - name: 'id', - desc: 'Id' - }]; - var count = 0; - var self = this; - get(typeClass, 'attributes').forEach(function (meta, name) { - if (count++ > self.attributeLimit) { - return false; - } - var desc = capitalize(underscore(name).replace('_', ' ')); - columns.push({ name: name, desc: desc }); - }); - return columns; - }, - - getRecords: function getRecords(modelClass, modelName) { - if (arguments.length < 2) { - // Legacy Ember.js < 1.13 support - var containerKey = modelClass._debugContainerKey; - if (containerKey) { - var match = containerKey.match(/model:(.*)/); - if (match) { - modelName = match[1]; - } - } - } - assert("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support", !!modelName); - return this.get('store').peekAll(modelName); - }, - - getRecordColumnValues: function getRecordColumnValues(record) { - var _this = this; - - var count = 0; - var columnValues = { id: get(record, 'id') }; - - record.eachAttribute(function (key) { - if (count++ > _this.attributeLimit) { - return false; - } - var value = get(record, key); - columnValues[key] = value; - }); - return columnValues; - }, - - getRecordKeywords: function getRecordKeywords(record) { - var keywords = []; - var keys = _ember['default'].A(['id']); - record.eachAttribute(function (key) { - return keys.push(key); - }); - keys.forEach(function (key) { - return keywords.push(get(record, key)); - }); - return keywords; - }, - - getRecordFilterValues: function getRecordFilterValues(record) { - return { - isNew: record.get('isNew'), - isModified: record.get('hasDirtyAttributes') && !record.get('isNew'), - isClean: !record.get('hasDirtyAttributes') - }; - }, - - getRecordColor: function getRecordColor(record) { - var color = 'black'; - if (record.get('isNew')) { - color = 'green'; - } else if (record.get('hasDirtyAttributes')) { - color = 'blue'; - } - return color; - }, - - observeRecord: function observeRecord(record, recordUpdated) { - var releaseMethods = _ember['default'].A(); - var keysToObserve = _ember['default'].A(['id', 'isNew', 'hasDirtyAttributes']); - - record.eachAttribute(function (key) { - return keysToObserve.push(key); - }); - var adapter = this; - - keysToObserve.forEach(function (key) { - var handler = function handler() { - recordUpdated(adapter.wrapRecord(record)); - }; - _ember['default'].addObserver(record, key, handler); - releaseMethods.push(function () { - _ember['default'].removeObserver(record, key, handler); - }); - }); - - var release = function release() { - releaseMethods.forEach(function (fn) { - return fn(); - }); - }; - - return release; - } - }); -}); -define('ember-data/-private/system/debug/debug-info', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports['default'] = _ember['default'].Mixin.create({ - - /** - Provides info about the model for debugging purposes - by grouping the properties into more semantic groups. - Meant to be used by debugging tools such as the Chrome Ember Extension. - - Groups all attributes in "Attributes" group. - - Groups all belongsTo relationships in "Belongs To" group. - - Groups all hasMany relationships in "Has Many" group. - - Groups all flags in "Flags" group. - - Flags relationship CPs as expensive properties. - @method _debugInfo - @for DS.Model - @private - */ - _debugInfo: function _debugInfo() { - var attributes = ['id']; - var relationships = { belongsTo: [], hasMany: [] }; - var expensiveProperties = []; - - this.eachAttribute(function (name, meta) { - return attributes.push(name); - }); - - this.eachRelationship(function (name, relationship) { - relationships[relationship.kind].push(name); - expensiveProperties.push(name); - }); - - var groups = [{ - name: 'Attributes', - properties: attributes, - expand: true - }, { - name: 'Belongs To', - properties: relationships.belongsTo, - expand: true - }, { - name: 'Has Many', - properties: relationships.hasMany, - expand: true - }, { - name: 'Flags', - properties: ['isLoaded', 'hasDirtyAttributes', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] - }]; - - return { - propertyInfo: { - // include all other mixins / properties (not just the grouped ones) - includeOtherProperties: true, - groups: groups, - // don't pre-calculate unless cached - expensiveProperties: expensiveProperties - } - }; - } - }); -}); -define("ember-data/-private/system/debug", ["exports", "ember-data/-private/system/debug/debug-adapter"], function (exports, _emberDataPrivateSystemDebugDebugAdapter) { - /** - @module ember-data - */ - - "use strict"; - - exports["default"] = _emberDataPrivateSystemDebugDebugAdapter["default"]; -}); -define("ember-data/-private/system/empty-object", ["exports"], function (exports) { - "use strict"; - - exports["default"] = EmptyObject; - - // This exists because `Object.create(null)` is absurdly slow compared - // to `new EmptyObject()`. In either case, you want a null prototype - // when you're treating the object instances as arbitrary dictionaries - // and don't want your keys colliding with build-in methods on the - // default object prototype. - var proto = Object.create(null, { - // without this, we will always still end up with (new - // EmptyObject()).constructor === Object - constructor: { - value: undefined, - enumerable: false, - writable: true - } - }); - function EmptyObject() {} - - EmptyObject.prototype = proto; -}); -define('ember-data/-private/system/is-array-like', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports['default'] = isArrayLike; - - /* - We're using this to detect arrays and "array-like" objects. - - This is a copy of the `isArray` method found in `ember-runtime/utils` as we're - currently unable to import non-exposed modules. - - This method was previously exposed as `Ember.isArray` but since - https://github.com/emberjs/ember.js/pull/11463 `Ember.isArray` is an alias of - `Array.isArray` hence removing the "array-like" part. - */ - function isArrayLike(obj) { - if (!obj || obj.setInterval) { - return false; - } - if (Array.isArray(obj)) { - return true; - } - if (_ember['default'].Array.detect(obj)) { - return true; - } - - var type = _ember['default'].typeOf(obj); - if ('array' === type) { - return true; - } - if (obj.length !== undefined && 'object' === type) { - return true; - } - return false; - } -}); -define("ember-data/-private/system/many-array", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies) { - /** - @module ember-data - */ - "use strict"; - - var get = _ember["default"].get; - var set = _ember["default"].set; - - /** - A `ManyArray` is a `MutableArray` that represents the contents of a has-many - relationship. - - The `ManyArray` is instantiated lazily the first time the relationship is - requested. - - ### Inverses - - Often, the relationships in Ember Data applications will have - an inverse. For example, imagine the following models are - defined: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('comment') - }); - ``` - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - post: DS.belongsTo('post') - }); - ``` - - If you created a new instance of `App.Post` and added - a `App.Comment` record to its `comments` has-many - relationship, you would expect the comment's `post` - property to be set to the post that contained - the has-many. - - We call the record to which a relationship belongs the - relationship's _owner_. - - @class ManyArray - @namespace DS - @extends Ember.Object - @uses Ember.MutableArray, Ember.Evented - */ - exports["default"] = _ember["default"].Object.extend(_ember["default"].MutableArray, _ember["default"].Evented, { - init: function init() { - this._super.apply(this, arguments); - this.currentState = _ember["default"].A([]); - }, - - record: null, - - canonicalState: null, - currentState: null, - - length: 0, - - objectAt: function objectAt(index) { - //Ember observers such as 'firstObject', 'lastObject' might do out of bounds accesses - if (!this.currentState[index]) { - return undefined; - } - return this.currentState[index].getRecord(); - }, - - flushCanonical: function flushCanonical() { - //TODO make this smarter, currently its plenty stupid - var toSet = this.canonicalState.filter(function (internalModel) { - return !internalModel.isDeleted(); - }); - - //a hack for not removing new records - //TODO remove once we have proper diffing - var newRecords = this.currentState.filter(function (internalModel) { - return internalModel.isNew(); - }); - toSet = toSet.concat(newRecords); - var oldLength = this.length; - this.arrayContentWillChange(0, this.length, toSet.length); - this.set('length', toSet.length); - this.currentState = toSet; - this.arrayContentDidChange(0, oldLength, this.length); - //TODO Figure out to notify only on additions and maybe only if unloaded - this.relationship.notifyHasManyChanged(); - this.record.updateRecordArrays(); - }, - /** - `true` if the relationship is polymorphic, `false` otherwise. - @property {Boolean} isPolymorphic - @private - */ - isPolymorphic: false, - - /** - The loading state of this array - @property {Boolean} isLoaded - */ - isLoaded: false, - - /** - The relationship which manages this array. - @property {ManyRelationship} relationship - @private - */ - relationship: null, - - /** - Metadata associated with the request for async hasMany relationships. - Example - Given that the server returns the following JSON payload when fetching a - hasMany relationship: - ```js - { - "comments": [{ - "id": 1, - "comment": "This is the first comment", - }, { - // ... - }], - "meta": { - "page": 1, - "total": 5 - } - } - ``` - You can then access the metadata via the `meta` property: - ```js - post.get('comments').then(function(comments) { - var meta = comments.get('meta'); - // meta.page => 1 - // meta.total => 5 - }); - ``` - @property {Object} meta - @public - */ - meta: null, - - internalReplace: function internalReplace(idx, amt, objects) { - if (!objects) { - objects = []; - } - this.arrayContentWillChange(idx, amt, objects.length); - this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects)); - this.set('length', this.currentState.length); - this.arrayContentDidChange(idx, amt, objects.length); - if (objects) { - //TODO(Igor) probably needed only for unloaded records - this.relationship.notifyHasManyChanged(); - } - this.record.updateRecordArrays(); - }, - - //TODO(Igor) optimize - internalRemoveRecords: function internalRemoveRecords(records) { - var index; - for (var i = 0; i < records.length; i++) { - index = this.currentState.indexOf(records[i]); - this.internalReplace(index, 1); - } - }, - - //TODO(Igor) optimize - internalAddRecords: function internalAddRecords(records, idx) { - if (idx === undefined) { - idx = this.currentState.length; - } - this.internalReplace(idx, 0, records); - }, - - replace: function replace(idx, amt, objects) { - var records; - if (amt > 0) { - records = this.currentState.slice(idx, idx + amt); - this.get('relationship').removeRecords(records); - } - if (objects) { - this.get('relationship').addRecords(objects.map(function (obj) { - return obj._internalModel; - }), idx); - } - }, - /** - Used for async `hasMany` arrays - to keep track of when they will resolve. - @property {Ember.RSVP.Promise} promise - @private - */ - promise: null, - - /** - @method loadingRecordsCount - @param {Number} count - @private - */ - loadingRecordsCount: function loadingRecordsCount(count) { - this.loadingRecordsCount = count; - }, - - /** - @method loadedRecord - @private - */ - loadedRecord: function loadedRecord() { - this.loadingRecordsCount--; - if (this.loadingRecordsCount === 0) { - set(this, 'isLoaded', true); - this.trigger('didLoad'); - } - }, - - /** - @method reload - @public - */ - reload: function reload() { - return this.relationship.reload(); - }, - - /** - Saves all of the records in the `ManyArray`. - Example - ```javascript - store.findRecord('inbox', 1).then(function(inbox) { - inbox.get('messages').then(function(messages) { - messages.forEach(function(message) { - message.set('isRead', true); - }); - messages.save() - }); - }); - ``` - @method save - @return {DS.PromiseArray} promise - */ - save: function save() { - var manyArray = this; - var promiseLabel = "DS: ManyArray#save " + get(this, 'type'); - var promise = _ember["default"].RSVP.all(this.invoke("save"), promiseLabel).then(function (array) { - return manyArray; - }, null, "DS: ManyArray#save return ManyArray"); - - return _emberDataPrivateSystemPromiseProxies.PromiseArray.create({ promise: promise }); - }, - - /** - Create a child record within the owner - @method createRecord - @private - @param {Object} hash - @return {DS.Model} record - */ - createRecord: function createRecord(hash) { - var store = get(this, 'store'); - var type = get(this, 'type'); - var record; - - (0, _emberDataPrivateDebug.assert)("You cannot add '" + type.modelName + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic')); - record = store.createRecord(type.modelName, hash); - this.pushObject(record); - - return record; - } - }); -}); -define('ember-data/-private/system/merge', ['exports'], function (exports) { - 'use strict'; - - exports['default'] = merge; - - function merge(original, updates) { - if (!updates || typeof updates !== 'object') { - return original; - } - - var props = Object.keys(updates); - var prop; - var length = props.length; - - for (var i = 0; i < length; i++) { - prop = props[i]; - original[prop] = updates[prop]; - } - - return original; - } -}); -define("ember-data/-private/system/model/attr", ["exports", "ember", "ember-data/-private/debug"], function (exports, _ember, _emberDataPrivateDebug) { - "use strict"; - - var get = _ember["default"].get; - var Map = _ember["default"].Map; - - /** - @module ember-data - */ - - /** - @class Model - @namespace DS - */ - - var AttrClassMethodsMixin = _ember["default"].Mixin.create({ - /** - A map whose keys are the attributes of the model (properties - described by DS.attr) and whose values are the meta object for the - property. - Example - ```app/models/person.js - import DS from 'ember-data'; - export default DS.Model.extend({ - firstName: attr('string'), - lastName: attr('string'), - birthday: attr('date') - }); - ``` - ```javascript - import Ember from 'ember'; - import Person from 'app/models/person'; - var attributes = Ember.get(Person, 'attributes') - attributes.forEach(function(meta, name) { - console.log(name, meta); - }); - // prints: - // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} - // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} - // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} - ``` - @property attributes - @static - @type {Ember.Map} - @readOnly - */ - attributes: _ember["default"].computed(function () { - var _this = this; - - var map = Map.create(); - - this.eachComputedProperty(function (name, meta) { - if (meta.isAttribute) { - (0, _emberDataPrivateDebug.assert)("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('')` from " + _this.toString(), name !== 'id'); - - meta.name = name; - map.set(name, meta); - } - }); - - return map; - }).readOnly(), - - /** - A map whose keys are the attributes of the model (properties - described by DS.attr) and whose values are type of transformation - applied to each attribute. This map does not include any - attributes that do not have an transformation type. - Example - ```app/models/person.js - import DS from 'ember-data'; - export default DS.Model.extend({ - firstName: attr(), - lastName: attr('string'), - birthday: attr('date') - }); - ``` - ```javascript - import Ember from 'ember'; - import Person from 'app/models/person'; - var transformedAttributes = Ember.get(Person, 'transformedAttributes') - transformedAttributes.forEach(function(field, type) { - console.log(field, type); - }); - // prints: - // lastName string - // birthday date - ``` - @property transformedAttributes - @static - @type {Ember.Map} - @readOnly - */ - transformedAttributes: _ember["default"].computed(function () { - var map = Map.create(); - - this.eachAttribute(function (key, meta) { - if (meta.type) { - map.set(key, meta.type); - } - }); - - return map; - }).readOnly(), - - /** - Iterates through the attributes of the model, calling the passed function on each - attribute. - The callback method you provide should have the following signature (all - parameters are optional): - ```javascript - function(name, meta); - ``` - - `name` the name of the current property in the iteration - - `meta` the meta object for the attribute property in the iteration - Note that in addition to a callback, you can also pass an optional target - object that will be set as `this` on the context. - Example - ```javascript - import DS from 'ember-data'; - var Person = DS.Model.extend({ - firstName: attr('string'), - lastName: attr('string'), - birthday: attr('date') - }); - Person.eachAttribute(function(name, meta) { - console.log(name, meta); - }); - // prints: - // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} - // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} - // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} - ``` - @method eachAttribute - @param {Function} callback The callback to execute - @param {Object} [binding] the value to which the callback's `this` should be bound - @static - */ - eachAttribute: function eachAttribute(callback, binding) { - get(this, 'attributes').forEach(function (meta, name) { - callback.call(binding, name, meta); - }); - }, - - /** - Iterates through the transformedAttributes of the model, calling - the passed function on each attribute. Note the callback will not be - called for any attributes that do not have an transformation type. - The callback method you provide should have the following signature (all - parameters are optional): - ```javascript - function(name, type); - ``` - - `name` the name of the current property in the iteration - - `type` a string containing the name of the type of transformed - applied to the attribute - Note that in addition to a callback, you can also pass an optional target - object that will be set as `this` on the context. - Example - ```javascript - import DS from 'ember-data'; - var Person = DS.Model.extend({ - firstName: attr(), - lastName: attr('string'), - birthday: attr('date') - }); - Person.eachTransformedAttribute(function(name, type) { - console.log(name, type); - }); - // prints: - // lastName string - // birthday date - ``` - @method eachTransformedAttribute - @param {Function} callback The callback to execute - @param {Object} [binding] the value to which the callback's `this` should be bound - @static - */ - eachTransformedAttribute: function eachTransformedAttribute(callback, binding) { - get(this, 'transformedAttributes').forEach(function (type, name) { - callback.call(binding, name, type); - }); - } - }); - - exports.AttrClassMethodsMixin = AttrClassMethodsMixin; - - var AttrInstanceMethodsMixin = _ember["default"].Mixin.create({ - eachAttribute: function eachAttribute(callback, binding) { - this.constructor.eachAttribute(callback, binding); - } - }); - exports.AttrInstanceMethodsMixin = AttrInstanceMethodsMixin; -}); -define("ember-data/-private/system/model/errors/invalid", ["exports", "ember"], function (exports, _ember) { - "use strict"; - - exports["default"] = InvalidError; - - var EmberError = _ember["default"].Error; - - /** - A `DS.InvalidError` is used by an adapter to signal the external API - was unable to process a request because the content was not - semantically correct or meaningful per the API. Usually this means a - record failed some form of server side validation. When a promise - from an adapter is rejected with a `DS.InvalidError` the record will - transition to the `invalid` state and the errors will be set to the - `errors` property on the record. - - For Ember Data to correctly map errors to their corresponding - properties on the model, Ember Data expects each error to be - namespaced under a key that matches the property name. For example - if you had a Post model that looked like this. - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - title: DS.attr('string'), - content: DS.attr('string') - }); - ``` - - To show an error from the server related to the `title` and - `content` properties your adapter could return a promise that - rejects with a `DS.InvalidError` object that looks like this: - - ```app/adapters/post.js - import Ember from 'ember'; - import DS from 'ember-data'; - - export default DS.RESTAdapter.extend({ - updateRecord: function() { - // Fictional adapter that always rejects - return Ember.RSVP.reject(new DS.InvalidError({ - title: ['Must be unique'], - content: ['Must not be blank'], - })); - } - }); - ``` - - Your backend may use different property names for your records the - store will attempt extract and normalize the errors using the - serializer's `extractErrors` method before the errors get added to - the the model. As a result, it is safe for the `InvalidError` to - wrap the error payload unaltered. - - Example - - ```app/adapters/application.js - import Ember from 'ember'; - import DS from 'ember-data'; - - export default DS.RESTAdapter.extend({ - ajaxError: function(jqXHR) { - var error = this._super(jqXHR); - - // 422 is used by this fictional server to signal a validation error - if (jqXHR && jqXHR.status === 422) { - var jsonErrors = Ember.$.parseJSON(jqXHR.responseText); - return new DS.InvalidError(jsonErrors); - } else { - // The ajax request failed however it is not a result of this - // record being in an invalid state so we do not return a - // `InvalidError` object. - return error; - } - } - }); - ``` - - @class InvalidError - @namespace DS - */ - function InvalidError(errors) { - EmberError.call(this, "The backend rejected the commit because it was invalid: " + _ember["default"].inspect(errors)); - this.errors = errors; - } - - InvalidError.prototype = Object.create(EmberError.prototype); -}); -define('ember-data/-private/system/model/errors', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { - 'use strict'; - - var get = _ember['default'].get; - var set = _ember['default'].set; - var isEmpty = _ember['default'].isEmpty; - var makeArray = _ember['default'].makeArray; - - var MapWithDefault = _ember['default'].MapWithDefault; - - /** - @module ember-data - */ - - /** - Holds validation errors for a given record organized by attribute names. - - Every DS.Model has an `errors` property that is an instance of - `DS.Errors`. This can be used to display validation error - messages returned from the server when a `record.save()` rejects. - - For Example, if you had an `User` model that looked like this: - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - username: attr('string'), - email: attr('string') - }); - ``` - And you attempted to save a record that did not validate on the backend. - - ```javascript - var user = store.createRecord('user', { - username: 'tomster', - email: 'invalidEmail' - }); - user.save(); - ``` - - Your backend data store might return a response with status code 422 (Unprocessable Entity) - and that looks like this. This response will be used to populate the error object. - - ```javascript - { - "errors": [ - { - "detail": "This username is already taken!", - "source": { - "pointer": "data/attributes/username" - } - }, { - "detail": "Doesn't look like a valid email.", - "source": { - "pointer": "data/attributes/email" - } - } - ] - } - ``` - - For additional information on the error object, see the [JSON API spec](http://jsonapi.org/format/#error-objects). - - Errors can be displayed to the user by accessing their property name - to get an array of all the error objects for that property. Each - error object is a JavaScript object with two keys: - - - `message` A string containing the error message from the backend - - `attribute` The name of the property associated with this error message - - ```handlebars - Username: {{input value=username}} - {{#each model.errors.username as |error|}} - - {{error.message}} - - {{/each}} - - Email: {{input value=email}} - {{#each model.errors.email as |error|}} - - {{error.message}} - - {{/each}} - ``` - - You can also access the special `messages` property on the error - object to get an array of all the error strings. - - ```handlebars - {{#each model.errors.messages as |message|}} - - {{message}} - - {{/each}} - ``` - - The JSON API spec also allows for object level errors to be placed - in an object with pointer `data`. - - ```javascript - { - "errors": [ - { - "detail": "Some generic non property error message", - "source": { - "pointer": "data" - } - } - ] - } - ``` - - You can access these errors by using the `base` property on the errors - object. - - ```handlebars - {{#each model.errors.base as |error|}} - - {{error.message}} - - {{/each}} - ``` - - @class Errors - @namespace DS - @extends Ember.Object - @uses Ember.Enumerable - @uses Ember.Evented - */ - exports['default'] = _ember['default'].ArrayProxy.extend(_ember['default'].Evented, { - /** - Register with target handler - @method registerHandlers - @param {Object} target - @param {Function} becameInvalid - @param {Function} becameValid - @deprecated - */ - registerHandlers: function registerHandlers(target, becameInvalid, becameValid) { - (0, _emberDataPrivateDebug.deprecate)('Record errors will no longer be evented.', false, { - id: 'ds.errors.registerHandlers', - until: '3.0.0' - }); - - this._registerHandlers(target, becameInvalid, becameValid); - }, - - /** - Register with target handler - @method _registerHandlers - @private - */ - _registerHandlers: function _registerHandlers(target, becameInvalid, becameValid) { - this.on('becameInvalid', target, becameInvalid); - this.on('becameValid', target, becameValid); - }, - - /** - @property errorsByAttributeName - @type {Ember.MapWithDefault} - @private - */ - errorsByAttributeName: _ember['default'].computed(function () { - return MapWithDefault.create({ - defaultValue: function defaultValue() { - return _ember['default'].A(); - } - }); - }), - - /** - Returns errors for a given attribute - ```javascript - var user = store.createRecord('user', { - username: 'tomster', - email: 'invalidEmail' - }); - user.save().catch(function(){ - user.get('errors').errorsFor('email'); // returns: - // [{attribute: "email", message: "Doesn't look like a valid email."}] - }); - ``` - @method errorsFor - @param {String} attribute - @return {Array} - */ - errorsFor: function errorsFor(attribute) { - return get(this, 'errorsByAttributeName').get(attribute); - }, - - /** - An array containing all of the error messages for this - record. This is useful for displaying all errors to the user. - ```handlebars - {{#each model.errors.messages as |message|}} - - {{message}} - - {{/each}} - ``` - @property messages - @type {Array} - */ - messages: _ember['default'].computed.mapBy('content', 'message'), - - /** - @property content - @type {Array} - @private - */ - content: _ember['default'].computed(function () { - return _ember['default'].A(); - }), - - /** - @method unknownProperty - @private - */ - unknownProperty: function unknownProperty(attribute) { - var errors = this.errorsFor(attribute); - if (isEmpty(errors)) { - return null; - } - return errors; - }, - - /** - Total number of errors. - @property length - @type {Number} - @readOnly - */ - - /** - @property isEmpty - @type {Boolean} - @readOnly - */ - isEmpty: _ember['default'].computed.not('length').readOnly(), - - /** - Adds error messages to a given attribute and sends - `becameInvalid` event to the record. - Example: - ```javascript - if (!user.get('username') { - user.get('errors').add('username', 'This field is required'); - } - ``` - @method add - @param {String} attribute - @param {(Array|String)} messages - @deprecated - */ - add: function add(attribute, messages) { - (0, _emberDataPrivateDebug.warn)('Interacting with a record errors object will no longer change the record state.', false, { - id: 'ds.errors.add' - }); - - var wasEmpty = get(this, 'isEmpty'); - - this._add(attribute, messages); - - if (wasEmpty && !get(this, 'isEmpty')) { - this.trigger('becameInvalid'); - } - }, - - /** - Adds error messages to a given attribute without sending event. - @method _add - @private - */ - _add: function _add(attribute, messages) { - messages = this._findOrCreateMessages(attribute, messages); - this.addObjects(messages); - get(this, 'errorsByAttributeName').get(attribute).addObjects(messages); - - this.notifyPropertyChange(attribute); - }, - - /** - @method _findOrCreateMessages - @private - */ - _findOrCreateMessages: function _findOrCreateMessages(attribute, messages) { - var errors = this.errorsFor(attribute); - var messagesArray = makeArray(messages); - var _messages = new Array(messagesArray.length); - - for (var i = 0; i < messagesArray.length; i++) { - var message = messagesArray[i]; - var err = errors.findBy('message', message); - if (err) { - _messages[i] = err; - } else { - _messages[i] = { - attribute: attribute, - message: message - }; - } - } - - return _messages; - }, - - /** - Removes all error messages from the given attribute and sends - `becameValid` event to the record if there no more errors left. - Example: - ```app/models/user.js - import DS from 'ember-data'; - export default DS.Model.extend({ - email: DS.attr('string'), - twoFactorAuth: DS.attr('boolean'), - phone: DS.attr('string') - }); - ``` - ```app/routes/user/edit.js - import Ember from 'ember'; - export default Ember.Route.extend({ - actions: { - save: function(user) { - if (!user.get('twoFactorAuth')) { - user.get('errors').remove('phone'); - } - user.save(); - } - } - }); - ``` - @method remove - @param {String} attribute - @deprecated - */ - remove: function remove(attribute) { - (0, _emberDataPrivateDebug.warn)('Interacting with a record errors object will no longer change the record state.', false, { - id: 'ds.errors.remove' - }); - - if (get(this, 'isEmpty')) { - return; - } - - this._remove(attribute); - - if (get(this, 'isEmpty')) { - this.trigger('becameValid'); - } - }, - - /** - Removes all error messages from the given attribute without sending event. - @method _remove - @private - */ - _remove: function _remove(attribute) { - if (get(this, 'isEmpty')) { - return; - } - - var content = this.rejectBy('attribute', attribute); - set(this, 'content', content); - get(this, 'errorsByAttributeName')['delete'](attribute); - - this.notifyPropertyChange(attribute); - }, - - /** - Removes all error messages and sends `becameValid` event - to the record. - Example: - ```app/routes/user/edit.js - import Ember from 'ember'; - export default Ember.Route.extend({ - actions: { - retrySave: function(user) { - user.get('errors').clear(); - user.save(); - } - } - }); - ``` - @method clear - @deprecated - */ - clear: function clear() { - (0, _emberDataPrivateDebug.warn)('Interacting with a record errors object will no longer change the record state.', false, { - id: 'ds.errors.clear' - }); - - if (get(this, 'isEmpty')) { - return; - } - - this._clear(); - this.trigger('becameValid'); - }, - - /** - Removes all error messages. - to the record. - @method _clear - @private - */ - _clear: function _clear() { - if (get(this, 'isEmpty')) { - return; - } - - var errorsByAttributeName = get(this, 'errorsByAttributeName'); - var attributes = _ember['default'].A(); - - errorsByAttributeName.forEach(function (_, attribute) { - attributes.push(attribute); - }); - - errorsByAttributeName.clear(); - attributes.forEach(function (attribute) { - this.notifyPropertyChange(attribute); - }, this); - - _ember['default'].ArrayProxy.prototype.clear.call(this); - }, - - /** - Checks if there is error messages for the given attribute. - ```app/routes/user/edit.js - import Ember from 'ember'; - export default Ember.Route.extend({ - actions: { - save: function(user) { - if (user.get('errors').has('email')) { - return alert('Please update your email before attempting to save.'); - } - user.save(); - } - } - }); - ``` - @method has - @param {String} attribute - @return {Boolean} true if there some errors on given attribute - */ - has: function has(attribute) { - return !isEmpty(this.errorsFor(attribute)); - } - }); -}); -define("ember-data/-private/system/model/internal-model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/merge", "ember-data/-private/system/model/states", "ember-data/-private/system/relationships/state/create", "ember-data/-private/system/snapshot", "ember-data/-private/system/empty-object", "ember-data/-private/features", "ember-data/-private/utils", "ember-data/-private/system/references"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemMerge, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemRelationshipsStateCreate, _emberDataPrivateSystemSnapshot, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures, _emberDataPrivateUtils, _emberDataPrivateSystemReferences) { - "use strict"; - - var _slicedToArray = (function () { - function sliceIterator(arr, i) { - var _arr = [];var _n = true;var _d = false;var _e = undefined;try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value);if (i && _arr.length === i) break; - } - } catch (err) { - _d = true;_e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - }return _arr; - }return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; - })(); - - exports["default"] = InternalModel; - - var Promise = _ember["default"].RSVP.Promise; - var get = _ember["default"].get; - var set = _ember["default"].set; - var copy = _ember["default"].copy; - - var _extractPivotNameCache = new _emberDataPrivateSystemEmptyObject["default"](); - var _splitOnDotCache = new _emberDataPrivateSystemEmptyObject["default"](); - - function splitOnDot(name) { - return _splitOnDotCache[name] || (_splitOnDotCache[name] = name.split('.')); - } - - function extractPivotName(name) { - return _extractPivotNameCache[name] || (_extractPivotNameCache[name] = splitOnDot(name)[0]); - } - - function retrieveFromCurrentState(key) { - return function () { - return get(this.currentState, key); - }; - } - - var guid = 0; - /* - `InternalModel` is the Model class that we use internally inside Ember Data to represent models. - Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class. - - We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as - a performance optimization. - - `InternalModel` should never be exposed to application code. At the boundaries of the system, in places - like `find`, `push`, etc. we convert between Models and InternalModels. - - We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model` - if they are needed. - - @private - @class InternalModel - */ - function InternalModel(type, id, store, _, data) { - this.type = type; - this.id = id; - this.store = store; - this._data = data || new _emberDataPrivateSystemEmptyObject["default"](); - this.modelName = type.modelName; - this.dataHasInitialized = false; - //Look into making this lazy - this._deferredTriggers = []; - this._attributes = new _emberDataPrivateSystemEmptyObject["default"](); - this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); - this._relationships = new _emberDataPrivateSystemRelationshipsStateCreate["default"](this); - this._recordArrays = undefined; - this.currentState = _emberDataPrivateSystemModelStates["default"].empty; - this.recordReference = new _emberDataPrivateSystemReferences.RecordReference(store, this); - this.references = {}; - this.isReloading = false; - this.isError = false; - this.error = null; - this.__ember_meta__ = null; - this[_ember["default"].GUID_KEY] = guid++ + 'internal-model'; - /* - implicit relationships are relationship which have not been declared but the inverse side exists on - another record somewhere - For example if there was - ```app/models/comment.js - import DS from 'ember-data'; - export default DS.Model.extend({ - name: DS.attr() - }) - ``` - but there is also - ```app/models/post.js - import DS from 'ember-data'; - export default DS.Model.extend({ - name: DS.attr(), - comments: DS.hasMany('comment') - }) - ``` - would have a implicit post relationship in order to be do things like remove ourselves from the post - when we are deleted - */ - this._implicitRelationships = new _emberDataPrivateSystemEmptyObject["default"](); - } - - InternalModel.prototype = { - isEmpty: retrieveFromCurrentState('isEmpty'), - isLoading: retrieveFromCurrentState('isLoading'), - isLoaded: retrieveFromCurrentState('isLoaded'), - hasDirtyAttributes: retrieveFromCurrentState('hasDirtyAttributes'), - isSaving: retrieveFromCurrentState('isSaving'), - isDeleted: retrieveFromCurrentState('isDeleted'), - isNew: retrieveFromCurrentState('isNew'), - isValid: retrieveFromCurrentState('isValid'), - dirtyType: retrieveFromCurrentState('dirtyType'), - - constructor: InternalModel, - materializeRecord: function materializeRecord() { - (0, _emberDataPrivateDebug.assert)("Materialized " + this.modelName + " record with id:" + this.id + "more than once", this.record === null || this.record === undefined); - - // lookupFactory should really return an object that creates - // instances with the injections applied - var createOptions = { - store: this.store, - _internalModel: this, - id: this.id, - currentState: get(this, 'currentState'), - isError: this.isError, - adapterError: this.error - }; - - if (_ember["default"].setOwner) { - // ensure that `Ember.getOwner(this)` works inside a model instance - _ember["default"].setOwner(createOptions, (0, _emberDataPrivateUtils.getOwner)(this.store)); - } else { - createOptions.container = this.store.container; - } - - this.record = this.type._create(createOptions); - - this._triggerDeferredTriggers(); - }, - - recordObjectWillDestroy: function recordObjectWillDestroy() { - this.record = null; - }, - - deleteRecord: function deleteRecord() { - this.send('deleteRecord'); - }, - - save: function save(options) { - var promiseLabel = "DS: Model#save " + this; - var resolver = _ember["default"].RSVP.defer(promiseLabel); - - this.store.scheduleSave(this, resolver, options); - return resolver.promise; - }, - - startedReloading: function startedReloading() { - this.isReloading = true; - if (this.record) { - set(this.record, 'isReloading', true); - } - }, - - finishedReloading: function finishedReloading() { - this.isReloading = false; - if (this.record) { - set(this.record, 'isReloading', false); - } - }, - - reload: function reload() { - this.startedReloading(); - var record = this; - var promiseLabel = "DS: Model#reload of " + this; - return new Promise(function (resolve) { - record.send('reloadRecord', resolve); - }, promiseLabel).then(function () { - record.didCleanError(); - return record; - }, function (error) { - record.didError(error); - throw error; - }, "DS: Model#reload complete, update flags")["finally"](function () { - record.finishedReloading(); - record.updateRecordArrays(); - }); - }, - - getRecord: function getRecord() { - if (!this.record) { - this.materializeRecord(); - } - return this.record; - }, - - unloadRecord: function unloadRecord() { - this.send('unloadRecord'); - }, - - eachRelationship: function eachRelationship(callback, binding) { - return this.type.eachRelationship(callback, binding); - }, - - eachAttribute: function eachAttribute(callback, binding) { - return this.type.eachAttribute(callback, binding); - }, - - inverseFor: function inverseFor(key) { - return this.type.inverseFor(key); - }, - - setupData: function setupData(data) { - var changedKeys = this._changedKeys(data.attributes); - (0, _emberDataPrivateSystemMerge["default"])(this._data, data.attributes); - this.pushedData(); - if (this.record) { - this.record._notifyProperties(changedKeys); - } - this.didInitalizeData(); - }, - - becameReady: function becameReady() { - _ember["default"].run.schedule('actions', this.store.recordArrayManager, this.store.recordArrayManager.recordWasLoaded, this); - }, - - didInitalizeData: function didInitalizeData() { - if (!this.dataHasInitialized) { - this.becameReady(); - this.dataHasInitialized = true; - } - }, - - destroy: function destroy() { - if (this.record) { - return this.record.destroy(); - } - }, - - /* - @method createSnapshot - @private - */ - createSnapshot: function createSnapshot(options) { - return new _emberDataPrivateSystemSnapshot["default"](this, options); - }, - - /* - @method loadingData - @private - @param {Promise} promise - */ - loadingData: function loadingData(promise) { - this.send('loadingData', promise); - }, - - /* - @method loadedData - @private - */ - loadedData: function loadedData() { - this.send('loadedData'); - this.didInitalizeData(); - }, - - /* - @method notFound - @private - */ - notFound: function notFound() { - this.send('notFound'); - }, - - /* - @method pushedData - @private - */ - pushedData: function pushedData() { - this.send('pushedData'); - }, - - flushChangedAttributes: function flushChangedAttributes() { - this._inFlightAttributes = this._attributes; - this._attributes = new _emberDataPrivateSystemEmptyObject["default"](); - }, - - hasChangedAttributes: function hasChangedAttributes() { - return Object.keys(this._attributes).length > 0; - }, - - /* - Checks if the attributes which are considered as changed are still - different to the state which is acknowledged by the server. - This method is needed when data for the internal model is pushed and the - pushed data might acknowledge dirty attributes as confirmed. - @method updateChangedAttributes - @private - */ - updateChangedAttributes: function updateChangedAttributes() { - var changedAttributes = this.changedAttributes(); - var changedAttributeNames = Object.keys(changedAttributes); - - for (var i = 0, _length = changedAttributeNames.length; i < _length; i++) { - var attribute = changedAttributeNames[i]; - - var _changedAttributes$attribute = _slicedToArray(changedAttributes[attribute], 2); - - var oldData = _changedAttributes$attribute[0]; - var newData = _changedAttributes$attribute[1]; - - if (oldData === newData) { - delete this._attributes[attribute]; - } - } - }, - - /* - Returns an object, whose keys are changed properties, and value is an - [oldProp, newProp] array. - @method changedAttributes - @private - */ - changedAttributes: function changedAttributes() { - var oldData = this._data; - var currentData = this._attributes; - var inFlightData = this._inFlightAttributes; - var newData = (0, _emberDataPrivateSystemMerge["default"])(copy(inFlightData), currentData); - var diffData = new _emberDataPrivateSystemEmptyObject["default"](); - - var newDataKeys = Object.keys(newData); - - for (var i = 0, _length2 = newDataKeys.length; i < _length2; i++) { - var key = newDataKeys[i]; - diffData[key] = [oldData[key], newData[key]]; - } - - return diffData; - }, - - /* - @method adapterWillCommit - @private - */ - adapterWillCommit: function adapterWillCommit() { - this.send('willCommit'); - }, - - /* - @method adapterDidDirty - @private - */ - adapterDidDirty: function adapterDidDirty() { - this.send('becomeDirty'); - this.updateRecordArraysLater(); - }, - - /* - @method send - @private - @param {String} name - @param {Object} context - */ - send: function send(name, context) { - var currentState = get(this, 'currentState'); - - if (!currentState[name]) { - this._unhandledEvent(currentState, name, context); - } - - return currentState[name](this, context); - }, - - notifyHasManyAdded: function notifyHasManyAdded(key, record, idx) { - if (this.record) { - this.record.notifyHasManyAdded(key, record, idx); - } - }, - - notifyHasManyRemoved: function notifyHasManyRemoved(key, record, idx) { - if (this.record) { - this.record.notifyHasManyRemoved(key, record, idx); - } - }, - - notifyBelongsToChanged: function notifyBelongsToChanged(key, record) { - if (this.record) { - this.record.notifyBelongsToChanged(key, record); - } - }, - - notifyPropertyChange: function notifyPropertyChange(key) { - if (this.record) { - this.record.notifyPropertyChange(key); - } - }, - - rollbackAttributes: function rollbackAttributes() { - var dirtyKeys = Object.keys(this._attributes); - - this._attributes = new _emberDataPrivateSystemEmptyObject["default"](); - - if (get(this, 'isError')) { - this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); - this.didCleanError(); - } - - //Eventually rollback will always work for relationships - //For now we support it only out of deleted state, because we - //have an explicit way of knowing when the server acked the relationship change - if (this.isDeleted()) { - //TODO: Should probably move this to the state machine somehow - this.becameReady(); - } - - if (this.isNew()) { - this.clearRelationships(); - } - - if (this.isValid()) { - this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); - } - - this.send('rolledBack'); - - this.record._notifyProperties(dirtyKeys); - }, - /* - @method transitionTo - @private - @param {String} name - */ - transitionTo: function transitionTo(name) { - // POSSIBLE TODO: Remove this code and replace with - // always having direct reference to state objects - - var pivotName = extractPivotName(name); - var currentState = get(this, 'currentState'); - var state = currentState; - - do { - if (state.exit) { - state.exit(this); - } - state = state.parentState; - } while (!state.hasOwnProperty(pivotName)); - - var path = splitOnDot(name); - var setups = []; - var enters = []; - var i, l; - - for (i = 0, l = path.length; i < l; i++) { - state = state[path[i]]; - - if (state.enter) { - enters.push(state); - } - if (state.setup) { - setups.push(state); - } - } - - for (i = 0, l = enters.length; i < l; i++) { - enters[i].enter(this); - } - - set(this, 'currentState', state); - //TODO Consider whether this is the best approach for keeping these two in sync - if (this.record) { - set(this.record, 'currentState', state); - } - - for (i = 0, l = setups.length; i < l; i++) { - setups[i].setup(this); - } - - this.updateRecordArraysLater(); - }, - - _unhandledEvent: function _unhandledEvent(state, name, context) { - var errorMessage = "Attempted to handle event `" + name + "` "; - errorMessage += "on " + String(this) + " while in state "; - errorMessage += state.stateName + ". "; - - if (context !== undefined) { - errorMessage += "Called with " + _ember["default"].inspect(context) + "."; - } - - throw new _ember["default"].Error(errorMessage); - }, - - triggerLater: function triggerLater() { - var length = arguments.length; - var args = new Array(length); - - for (var i = 0; i < length; i++) { - args[i] = arguments[i]; - } - - if (this._deferredTriggers.push(args) !== 1) { - return; - } - _ember["default"].run.scheduleOnce('actions', this, '_triggerDeferredTriggers'); - }, - - _triggerDeferredTriggers: function _triggerDeferredTriggers() { - //TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record, - //but for now, we queue up all the events triggered before the record was materialized, and flush - //them once we have the record - if (!this.record) { - return; - } - for (var i = 0, l = this._deferredTriggers.length; i < l; i++) { - this.record.trigger.apply(this.record, this._deferredTriggers[i]); - } - - this._deferredTriggers.length = 0; - }, - /* - @method clearRelationships - @private - */ - clearRelationships: function clearRelationships() { - var _this = this; - - this.eachRelationship(function (name, relationship) { - if (_this._relationships.has(name)) { - var rel = _this._relationships.get(name); - rel.clear(); - rel.destroy(); - } - }); - Object.keys(this._implicitRelationships).forEach(function (key) { - _this._implicitRelationships[key].clear(); - _this._implicitRelationships[key].destroy(); - }); - }, - - /* - When a find request is triggered on the store, the user can optionally pass in - attributes and relationships to be preloaded. These are meant to behave as if they - came back from the server, except the user obtained them out of band and is informing - the store of their existence. The most common use case is for supporting client side - nested URLs, such as `/posts/1/comments/2` so the user can do - `store.findRecord('comment', 2, { preload: { post: 1 } })` without having to fetch the post. - Preloaded data can be attributes and relationships passed in either as IDs or as actual - models. - @method _preloadData - @private - @param {Object} preload - */ - _preloadData: function _preloadData(preload) { - var _this2 = this; - - //TODO(Igor) consider the polymorphic case - Object.keys(preload).forEach(function (key) { - var preloadValue = get(preload, key); - var relationshipMeta = _this2.type.metaForProperty(key); - if (relationshipMeta.isRelationship) { - _this2._preloadRelationship(key, preloadValue); - } else { - _this2._data[key] = preloadValue; - } - }); - }, - - _preloadRelationship: function _preloadRelationship(key, preloadValue) { - var relationshipMeta = this.type.metaForProperty(key); - var type = relationshipMeta.type; - if (relationshipMeta.kind === 'hasMany') { - this._preloadHasMany(key, preloadValue, type); - } else { - this._preloadBelongsTo(key, preloadValue, type); - } - }, - - _preloadHasMany: function _preloadHasMany(key, preloadValue, type) { - (0, _emberDataPrivateDebug.assert)("You need to pass in an array to set a hasMany property on a record", _ember["default"].isArray(preloadValue)); - var recordsToSet = new Array(preloadValue.length); - - for (var i = 0; i < preloadValue.length; i++) { - var recordToPush = preloadValue[i]; - recordsToSet[i] = this._convertStringOrNumberIntoInternalModel(recordToPush, type); - } - - //We use the pathway of setting the hasMany as if it came from the adapter - //because the user told us that they know this relationships exists already - this._relationships.get(key).updateRecordsFromAdapter(recordsToSet); - }, - - _preloadBelongsTo: function _preloadBelongsTo(key, preloadValue, type) { - var recordToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, type); - - //We use the pathway of setting the hasMany as if it came from the adapter - //because the user told us that they know this relationships exists already - this._relationships.get(key).setRecord(recordToSet); - }, - - _convertStringOrNumberIntoInternalModel: function _convertStringOrNumberIntoInternalModel(value, type) { - if (typeof value === 'string' || typeof value === 'number') { - return this.store._internalModelForId(type, value); - } - if (value._internalModel) { - return value._internalModel; - } - return value; - }, - - /* - @method updateRecordArrays - @private - */ - updateRecordArrays: function updateRecordArrays() { - this._updatingRecordArraysLater = false; - this.store.dataWasUpdated(this.type, this); - }, - - setId: function setId(id) { - (0, _emberDataPrivateDebug.assert)('A record\'s id cannot be changed once it is in the loaded state', this.id === null || this.id === id || this.isNew()); - this.id = id; - if (this.record.get('id') !== id) { - this.record.set('id', id); - } - }, - - didError: function didError(error) { - this.error = error; - this.isError = true; - - if (this.record) { - this.record.setProperties({ - isError: true, - adapterError: error - }); - } - }, - - didCleanError: function didCleanError() { - this.error = null; - this.isError = false; - - if (this.record) { - this.record.setProperties({ - isError: false, - adapterError: null - }); - } - }, - /* - If the adapter did not return a hash in response to a commit, - merge the changed attributes and relationships into the existing - saved data. - @method adapterDidCommit - */ - adapterDidCommit: function adapterDidCommit(data) { - if (data) { - data = data.attributes; - } - - this.didCleanError(); - var changedKeys = this._changedKeys(data); - - (0, _emberDataPrivateSystemMerge["default"])(this._data, this._inFlightAttributes); - if (data) { - (0, _emberDataPrivateSystemMerge["default"])(this._data, data); - } - - this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); - - this.send('didCommit'); - this.updateRecordArraysLater(); - - if (!data) { - return; - } - - this.record._notifyProperties(changedKeys); - }, - - /* - @method updateRecordArraysLater - @private - */ - updateRecordArraysLater: function updateRecordArraysLater() { - // quick hack (something like this could be pushed into run.once - if (this._updatingRecordArraysLater) { - return; - } - this._updatingRecordArraysLater = true; - _ember["default"].run.schedule('actions', this, this.updateRecordArrays); - }, - - addErrorMessageToAttribute: function addErrorMessageToAttribute(attribute, message) { - var record = this.getRecord(); - get(record, 'errors')._add(attribute, message); - }, - - removeErrorMessageFromAttribute: function removeErrorMessageFromAttribute(attribute) { - var record = this.getRecord(); - get(record, 'errors')._remove(attribute); - }, - - clearErrorMessages: function clearErrorMessages() { - var record = this.getRecord(); - get(record, 'errors')._clear(); - }, - - hasErrors: function hasErrors() { - var record = this.getRecord(); - var errors = get(record, 'errors'); - - return !_ember["default"].isEmpty(errors); - }, - - // FOR USE DURING COMMIT PROCESS - - /* - @method adapterDidInvalidate - @private - */ - adapterDidInvalidate: function adapterDidInvalidate(errors) { - var attribute; - - for (attribute in errors) { - if (errors.hasOwnProperty(attribute)) { - this.addErrorMessageToAttribute(attribute, errors[attribute]); - } - } - - this.send('becameInvalid'); - - this._saveWasRejected(); - }, - - /* - @method adapterDidError - @private - */ - adapterDidError: function adapterDidError(error) { - this.send('becameError'); - this.didError(error); - this._saveWasRejected(); - }, - - _saveWasRejected: function _saveWasRejected() { - var keys = Object.keys(this._inFlightAttributes); - for (var i = 0; i < keys.length; i++) { - if (this._attributes[keys[i]] === undefined) { - this._attributes[keys[i]] = this._inFlightAttributes[keys[i]]; - } - } - this._inFlightAttributes = new _emberDataPrivateSystemEmptyObject["default"](); - }, - - /* - Ember Data has 3 buckets for storing the value of an attribute on an internalModel. - `_data` holds all of the attributes that have been acknowledged by - a backend via the adapter. When rollbackAttributes is called on a model all - attributes will revert to the record's state in `_data`. - `_attributes` holds any change the user has made to an attribute - that has not been acknowledged by the adapter. Any values in - `_attributes` are have priority over values in `_data`. - `_inFlightAttributes`. When a record is being synced with the - backend the values in `_attributes` are copied to - `_inFlightAttributes`. This way if the backend acknowledges the - save but does not return the new state Ember Data can copy the - values from `_inFlightAttributes` to `_data`. Without having to - worry about changes made to `_attributes` while the save was - happenign. - Changed keys builds a list of all of the values that may have been - changed by the backend after a successful save. - It does this by iterating over each key, value pair in the payload - returned from the server after a save. If the `key` is found in - `_attributes` then the user has a local changed to the attribute - that has not been synced with the server and the key is not - included in the list of changed keys. - - If the value, for a key differs from the value in what Ember Data - believes to be the truth about the backend state (A merger of the - `_data` and `_inFlightAttributes` objects where - `_inFlightAttributes` has priority) then that means the backend - has updated the value and the key is added to the list of changed - keys. - @method _changedKeys - @private - */ - _changedKeys: function _changedKeys(updates) { - var changedKeys = []; - - if (updates) { - var original, i, value, key; - var keys = Object.keys(updates); - var length = keys.length; - - original = (0, _emberDataPrivateSystemMerge["default"])(new _emberDataPrivateSystemEmptyObject["default"](), this._data); - original = (0, _emberDataPrivateSystemMerge["default"])(original, this._inFlightAttributes); - - for (i = 0; i < length; i++) { - key = keys[i]; - value = updates[key]; - - // A value in _attributes means the user has a local change to - // this attributes. We never override this value when merging - // updates from the backend so we should not sent a change - // notification if the server value differs from the original. - if (this._attributes[key] !== undefined) { - continue; - } - - if (!_ember["default"].isEqual(original[key], value)) { - changedKeys.push(key); - } - } - } - - return changedKeys; - }, - - toString: function toString() { - if (this.record) { - return this.record.toString(); - } else { - return "<" + this.modelName + ":" + this.id + ">"; - } - } - }; - - if ((0, _emberDataPrivateFeatures["default"])('ds-references')) { - - InternalModel.prototype.referenceFor = function (type, name) { - var reference = this.references[name]; - - if (!reference) { - var relationship = this._relationships.get(name); - - if (type === "belongsTo") { - reference = new _emberDataPrivateSystemReferences.BelongsToReference(this.store, this, relationship); - } else if (type === "hasMany") { - reference = new _emberDataPrivateSystemReferences.HasManyReference(this.store, this, relationship); - } - - this.references[name] = reference; - } - - return reference; - }; - } -}); -define("ember-data/-private/system/model/model", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/model/errors", "ember-data/-private/features", "ember-data/-private/system/debug/debug-info", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many", "ember-data/-private/system/relationships/ext", "ember-data/-private/system/model/attr"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemModelErrors, _emberDataPrivateFeatures, _emberDataPrivateSystemDebugDebugInfo, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany, _emberDataPrivateSystemRelationshipsExt, _emberDataPrivateSystemModelAttr) { - "use strict"; - - /** - @module ember-data - */ - - var get = _ember["default"].get; - - function intersection(array1, array2) { - var result = []; - array1.forEach(function (element) { - if (array2.indexOf(element) >= 0) { - result.push(element); - } - }); - - return result; - } - - var RESERVED_MODEL_PROPS = ['currentState', 'data', 'store']; - - var retrieveFromCurrentState = _ember["default"].computed('currentState', function (key) { - return get(this._internalModel.currentState, key); - }).readOnly(); - - /** - - The model class that all Ember Data records descend from. - This is the public API of Ember Data models. If you are using Ember Data - in your application, this is the class you should use. - If you are working on Ember Data internals, you most likely want to be dealing - with `InternalModel` - - @class Model - @namespace DS - @extends Ember.Object - @uses Ember.Evented - */ - var Model = _ember["default"].Object.extend(_ember["default"].Evented, { - _internalModel: null, - store: null, - - /** - If this property is `true` the record is in the `empty` - state. Empty is the first state all records enter after they have - been created. Most records created by the store will quickly - transition to the `loading` state if data needs to be fetched from - the server or the `created` state if the record is created on the - client. A record can also enter the empty state if the adapter is - unable to locate the record. - @property isEmpty - @type {Boolean} - @readOnly - */ - isEmpty: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `loading` state. A - record enters this state when the store asks the adapter for its - data. It remains in this state until the adapter provides the - requested data. - @property isLoading - @type {Boolean} - @readOnly - */ - isLoading: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `loaded` state. A - record enters this state when its data is populated. Most of a - record's lifecycle is spent inside substates of the `loaded` - state. - Example - ```javascript - var record = store.createRecord('model'); - record.get('isLoaded'); // true - store.findRecord('model', 1).then(function(model) { - model.get('isLoaded'); // true - }); - ``` - @property isLoaded - @type {Boolean} - @readOnly - */ - isLoaded: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `dirty` state. The - record has local changes that have not yet been saved by the - adapter. This includes records that have been created (but not yet - saved) or deleted. - Example - ```javascript - var record = store.createRecord('model'); - record.get('hasDirtyAttributes'); // true - store.findRecord('model', 1).then(function(model) { - model.get('hasDirtyAttributes'); // false - model.set('foo', 'some value'); - model.get('hasDirtyAttributes'); // true - }); - ``` - @property hasDirtyAttributes - @type {Boolean} - @readOnly - */ - hasDirtyAttributes: _ember["default"].computed('currentState.isDirty', function () { - return this.get('currentState.isDirty'); - }), - /** - If this property is `true` the record is in the `saving` state. A - record enters the saving state when `save` is called, but the - adapter has not yet acknowledged that the changes have been - persisted to the backend. - Example - ```javascript - var record = store.createRecord('model'); - record.get('isSaving'); // false - var promise = record.save(); - record.get('isSaving'); // true - promise.then(function() { - record.get('isSaving'); // false - }); - ``` - @property isSaving - @type {Boolean} - @readOnly - */ - isSaving: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `deleted` state - and has been marked for deletion. When `isDeleted` is true and - `hasDirtyAttributes` is true, the record is deleted locally but the deletion - was not yet persisted. When `isSaving` is true, the change is - in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the - change has persisted. - Example - ```javascript - var record = store.createRecord('model'); - record.get('isDeleted'); // false - record.deleteRecord(); - // Locally deleted - record.get('isDeleted'); // true - record.get('hasDirtyAttributes'); // true - record.get('isSaving'); // false - // Persisting the deletion - var promise = record.save(); - record.get('isDeleted'); // true - record.get('isSaving'); // true - // Deletion Persisted - promise.then(function() { - record.get('isDeleted'); // true - record.get('isSaving'); // false - record.get('hasDirtyAttributes'); // false - }); - ``` - @property isDeleted - @type {Boolean} - @readOnly - */ - isDeleted: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `new` state. A - record will be in the `new` state when it has been created on the - client and the adapter has not yet report that it was successfully - saved. - Example - ```javascript - var record = store.createRecord('model'); - record.get('isNew'); // true - record.save().then(function(model) { - model.get('isNew'); // false - }); - ``` - @property isNew - @type {Boolean} - @readOnly - */ - isNew: retrieveFromCurrentState, - /** - If this property is `true` the record is in the `valid` state. - A record will be in the `valid` state when the adapter did not report any - server-side validation failures. - @property isValid - @type {Boolean} - @readOnly - */ - isValid: retrieveFromCurrentState, - /** - If the record is in the dirty state this property will report what - kind of change has caused it to move into the dirty - state. Possible values are: - - `created` The record has been created by the client and not yet saved to the adapter. - - `updated` The record has been updated by the client and not yet saved to the adapter. - - `deleted` The record has been deleted by the client and not yet saved to the adapter. - Example - ```javascript - var record = store.createRecord('model'); - record.get('dirtyType'); // 'created' - ``` - @property dirtyType - @type {String} - @readOnly - */ - dirtyType: retrieveFromCurrentState, - - /** - If `true` the adapter reported that it was unable to save local - changes to the backend for any reason other than a server-side - validation error. - Example - ```javascript - record.get('isError'); // false - record.set('foo', 'valid value'); - record.save().then(null, function() { - record.get('isError'); // true - }); - ``` - @property isError - @type {Boolean} - @readOnly - */ - isError: false, - - /** - If `true` the store is attempting to reload the record form the adapter. - Example - ```javascript - record.get('isReloading'); // false - record.reload(); - record.get('isReloading'); // true - ``` - @property isReloading - @type {Boolean} - @readOnly - */ - isReloading: false, - - /** - All ember models have an id property. This is an identifier - managed by an external source. These are always coerced to be - strings before being used internally. Note when declaring the - attributes for a model it is an error to declare an id - attribute. - ```javascript - var record = store.createRecord('model'); - record.get('id'); // null - store.findRecord('model', 1).then(function(model) { - model.get('id'); // '1' - }); - ``` - @property id - @type {String} - */ - id: null, - - /** - @property currentState - @private - @type {Object} - */ - - /** - When the record is in the `invalid` state this object will contain - any errors returned by the adapter. When present the errors hash - contains keys corresponding to the invalid property names - and values which are arrays of Javascript objects with two keys: - - `message` A string containing the error message from the backend - - `attribute` The name of the property associated with this error message - ```javascript - record.get('errors.length'); // 0 - record.set('foo', 'invalid value'); - record.save().catch(function() { - record.get('errors').get('foo'); - // [{message: 'foo should be a number.', attribute: 'foo'}] - }); - ``` - The `errors` property us useful for displaying error messages to - the user. - ```handlebars - Username: {{input value=username}} - {{#each model.errors.username as |error|}} - - {{error.message}} - - {{/each}} - Email: {{input value=email}} - {{#each model.errors.email as |error|}} - - {{error.message}} - - {{/each}} - ``` - You can also access the special `messages` property on the error - object to get an array of all the error strings. - ```handlebars - {{#each model.errors.messages as |message|}} - - {{message}} - - {{/each}} - ``` - @property errors - @type {DS.Errors} - */ - errors: _ember["default"].computed(function () { - var errors = _emberDataPrivateSystemModelErrors["default"].create(); - - errors._registerHandlers(this._internalModel, function () { - this.send('becameInvalid'); - }, function () { - this.send('becameValid'); - }); - return errors; - }).readOnly(), - - /** - This property holds the `DS.AdapterError` object with which - last adapter operation was rejected. - @property adapterError - @type {DS.AdapterError} - */ - adapterError: null, - - /** - Create a JSON representation of the record, using the serialization - strategy of the store's adapter. - `serialize` takes an optional hash as a parameter, currently - supported options are: - - `includeId`: `true` if the record's ID should be included in the - JSON representation. - @method serialize - @param {Object} options - @return {Object} an object whose values are primitive JSON values only - */ - serialize: function serialize(options) { - return this.store.serialize(this, options); - }, - - /** - Use [DS.JSONSerializer](DS.JSONSerializer.html) to - get the JSON representation of a record. - `toJSON` takes an optional hash as a parameter, currently - supported options are: - - `includeId`: `true` if the record's ID should be included in the - JSON representation. - @method toJSON - @param {Object} options - @return {Object} A JSON representation of the object. - */ - toJSON: function toJSON(options) { - // container is for lazy transform lookups - var serializer = this.store.serializerFor('-default'); - var snapshot = this._internalModel.createSnapshot(); - - return serializer.serialize(snapshot, options); - }, - - /** - Fired when the record is ready to be interacted with, - that is either loaded from the server or created locally. - @event ready - */ - ready: _ember["default"].K, - - /** - Fired when the record is loaded from the server. - @event didLoad - */ - didLoad: _ember["default"].K, - - /** - Fired when the record is updated. - @event didUpdate - */ - didUpdate: _ember["default"].K, - - /** - Fired when a new record is commited to the server. - @event didCreate - */ - didCreate: _ember["default"].K, - - /** - Fired when the record is deleted. - @event didDelete - */ - didDelete: _ember["default"].K, - - /** - Fired when the record becomes invalid. - @event becameInvalid - */ - becameInvalid: _ember["default"].K, - - /** - Fired when the record enters the error state. - @event becameError - */ - becameError: _ember["default"].K, - - /** - Fired when the record is rolled back. - @event rolledBack - */ - rolledBack: _ember["default"].K, - - /** - @property data - @private - @type {Object} - */ - data: _ember["default"].computed.readOnly('_internalModel._data'), - - //TODO Do we want to deprecate these? - /** - @method send - @private - @param {String} name - @param {Object} context - */ - send: function send(name, context) { - return this._internalModel.send(name, context); - }, - - /** - @method transitionTo - @private - @param {String} name - */ - transitionTo: function transitionTo(name) { - return this._internalModel.transitionTo(name); - }, - - /** - Marks the record as deleted but does not save it. You must call - `save` afterwards if you want to persist it. You might use this - method if you want to allow the user to still `rollbackAttributes()` - after a delete it was made. - Example - ```app/routes/model/delete.js - import Ember from 'ember'; - export default Ember.Route.extend({ - actions: { - softDelete: function() { - this.controller.get('model').deleteRecord(); - }, - confirm: function() { - this.controller.get('model').save(); - }, - undo: function() { - this.controller.get('model').rollbackAttributes(); - } - } - }); - ``` - @method deleteRecord - */ - deleteRecord: function deleteRecord() { - this._internalModel.deleteRecord(); - }, - - /** - Same as `deleteRecord`, but saves the record immediately. - Example - ```app/routes/model/delete.js - import Ember from 'ember'; - export default Ember.Route.extend({ - actions: { - delete: function() { - var controller = this.controller; - controller.get('model').destroyRecord().then(function() { - controller.transitionToRoute('model.index'); - }); - } - } - }); - ``` - @method destroyRecord - @param {Object} options - @return {Promise} a promise that will be resolved when the adapter returns - successfully or rejected if the adapter returns with an error. - */ - destroyRecord: function destroyRecord(options) { - this.deleteRecord(); - return this.save(options); - }, - - /** - @method unloadRecord - @private - */ - unloadRecord: function unloadRecord() { - if (this.isDestroyed) { - return; - } - this._internalModel.unloadRecord(); - }, - - /** - @method _notifyProperties - @private - */ - _notifyProperties: function _notifyProperties(keys) { - _ember["default"].beginPropertyChanges(); - var key; - for (var i = 0, length = keys.length; i < length; i++) { - key = keys[i]; - this.notifyPropertyChange(key); - } - _ember["default"].endPropertyChanges(); - }, - - /** - Returns an object, whose keys are changed properties, and value is - an [oldProp, newProp] array. - Example - ```app/models/mascot.js - import DS from 'ember-data'; - export default DS.Model.extend({ - name: attr('string') - }); - ``` - ```javascript - var mascot = store.createRecord('mascot'); - mascot.changedAttributes(); // {} - mascot.set('name', 'Tomster'); - mascot.changedAttributes(); // {name: [undefined, 'Tomster']} - ``` - @method changedAttributes - @return {Object} an object, whose keys are changed properties, - and value is an [oldProp, newProp] array. - */ - changedAttributes: function changedAttributes() { - return this._internalModel.changedAttributes(); - }, - - //TODO discuss with tomhuda about events/hooks - //Bring back as hooks? - /** - @method adapterWillCommit - @private - adapterWillCommit: function() { - this.send('willCommit'); - }, - /** - @method adapterDidDirty - @private - adapterDidDirty: function() { - this.send('becomeDirty'); - this.updateRecordArraysLater(); - }, - */ - - /** - If the model `hasDirtyAttributes` this function will discard any unsaved - changes. If the model `isNew` it will be removed from the store. - Example - ```javascript - record.get('name'); // 'Untitled Document' - record.set('name', 'Doc 1'); - record.get('name'); // 'Doc 1' - record.rollbackAttributes(); - record.get('name'); // 'Untitled Document' - ``` - @method rollbackAttributes - */ - rollbackAttributes: function rollbackAttributes() { - this._internalModel.rollbackAttributes(); - }, - - /* - @method _createSnapshot - @private - */ - _createSnapshot: function _createSnapshot() { - return this._internalModel.createSnapshot(); - }, - - toStringExtension: function toStringExtension() { - return get(this, 'id'); - }, - - /** - Save the record and persist any changes to the record to an - external source via the adapter. - Example - ```javascript - record.set('name', 'Tomster'); - record.save().then(function() { - // Success callback - }, function() { - // Error callback - }); - ``` - @method save - @param {Object} options - @return {Promise} a promise that will be resolved when the adapter returns - successfully or rejected if the adapter returns with an error. - */ - save: function save(options) { - var _this = this; - - return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ - promise: this._internalModel.save(options).then(function () { - return _this; - }) - }); - }, - - /** - Reload the record from the adapter. - This will only work if the record has already finished loading. - Example - ```app/routes/model/view.js - import Ember from 'ember'; - export default Ember.Route.extend({ - actions: { - reload: function() { - this.controller.get('model').reload().then(function(model) { - // do something with the reloaded model - }); - } - } - }); - ``` - @method reload - @return {Promise} a promise that will be resolved with the record when the - adapter returns successfully or rejected if the adapter returns - with an error. - */ - reload: function reload() { - var _this2 = this; - - return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ - promise: this._internalModel.reload().then(function () { - return _this2; - }) - }); - }, - - /** - Override the default event firing from Ember.Evented to - also call methods with the given name. - @method trigger - @private - @param {String} name - */ - trigger: function trigger(name) { - var length = arguments.length; - var args = new Array(length - 1); - - for (var i = 1; i < length; i++) { - args[i - 1] = arguments[i]; - } - - _ember["default"].tryInvoke(this, name, args); - this._super.apply(this, arguments); - }, - - willDestroy: function willDestroy() { - //TODO Move! - this._super.apply(this, arguments); - this._internalModel.clearRelationships(); - this._internalModel.recordObjectWillDestroy(); - //TODO should we set internalModel to null here? - }, - - // This is a temporary solution until we refactor DS.Model to not - // rely on the data property. - willMergeMixin: function willMergeMixin(props) { - var constructor = this.constructor; - (0, _emberDataPrivateDebug.assert)('`' + intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0]); - (0, _emberDataPrivateDebug.assert)("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('')` from " + constructor.toString(), Object.keys(props).indexOf('id') === -1); - }, - - attr: function attr() { - (0, _emberDataPrivateDebug.assert)("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); - }, - - belongsTo: function belongsTo() { - (0, _emberDataPrivateDebug.assert)("The `belongsTo` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); - }, - - hasMany: function hasMany() { - (0, _emberDataPrivateDebug.assert)("The `hasMany` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); - }, - - setId: _ember["default"].observer('id', function () { - this._internalModel.setId(this.get('id')); - }) - }); - - Model.reopenClass({ - /** - Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model - instances from within the store, but if end users accidentally call `create()` - (instead of `createRecord()`), we can raise an error. - @method _create - @private - @static - */ - _create: Model.create, - - /** - Override the class' `create()` method to raise an error. This - prevents end users from inadvertently calling `create()` instead - of `createRecord()`. The store is still able to create instances - by calling the `_create()` method. To create an instance of a - `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). - @method create - @private - @static - */ - create: function create() { - throw new _ember["default"].Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); - }, - - /** - Represents the model's class name as a string. This can be used to look up the model through - DS.Store's modelFor method. - `modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string. - For example: - ```javascript - store.modelFor('post').modelName; // 'post' - store.modelFor('blog-post').modelName; // 'blog-post' - ``` - The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload - keys to underscore (instead of dasherized), you might use the following code: - ```javascript - export default var PostSerializer = DS.RESTSerializer.extend({ - payloadKeyFromModelName: function(modelName) { - return Ember.String.underscore(modelName); - } - }); - ``` - @property modelName - @type String - @readonly - */ - modelName: null - }); - - // if `Ember.setOwner` is defined, accessing `this.container` is - // deprecated (but functional). In "standard" Ember usage, this - // deprecation is actually created via an `.extend` of the factory - // inside the container itself, but that only happens on models - // with MODEL_FACTORY_INJECTIONS enabled :( - if (_ember["default"].setOwner) { - Object.defineProperty(Model.prototype, 'container', { - configurable: true, - enumerable: false, - get: function get() { - (0, _emberDataPrivateDebug.deprecate)('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.', false, { id: 'ember-application.injected-container', until: '3.0.0' }); - - return this.store.container; - } - }); - } - - if ((0, _emberDataPrivateFeatures["default"])("ds-references")) { - - Model.reopen({ - - /** - Get the reference for the specified belongsTo relationship. - Example - ```javascript - // models/blog.js - export default DS.Model.extend({ - user: DS.belongsTo({ async: true }) - }); - store.push({ - type: 'blog', - id: 1, - relationships: { - user: { type: 'user', id: 1 } - } - }); - var userRef = blog.belongsTo('user'); - // check if the user relationship is loaded - var isLoaded = userRef.value() !== null; - // get the record of the reference (null if not yet available) - var user = userRef.value(); - // get the identifier of the reference - if (userRef.remoteType() === "id") { - var id = userRef.id(); - } else if (userRef.remoteType() === "link") { - var link = userRef.link(); - } - // load user (via store.findRecord or store.findBelongsTo) - userRef.load().then(...) - // or trigger a reload - userRef.reload().then(...) - // provide data for reference - userRef.push({ - type: 'user', - id: 1, - attributes: { - username: "@user" - } - }).then(function(user) { - userRef.value() === user; - }); - ``` - @method belongsTo - @param {String} name of the relationship - @return {BelongsToReference} reference for this relationship - */ - belongsTo: function belongsTo(name) { - return this._internalModel.referenceFor('belongsTo', name); - }, - - /** - Get the reference for the specified hasMany relationship. - Example - ```javascript - // models/blog.js - export default DS.Model.extend({ - comments: DS.hasMany({ async: true }) - }); - store.push({ - type: 'blog', - id: 1, - relationships: { - comments: { - data: [ - { type: 'comment', id: 1 }, - { type: 'comment', id: 2 } - ] - } - } - }); - var commentsRef = blog.hasMany('comments'); - // check if the comments are loaded already - var isLoaded = commentsRef.value() !== null; - // get the records of the reference (null if not yet available) - var comments = commentsRef.value(); - // get the identifier of the reference - if (commentsRef.remoteType() === "ids") { - var ids = commentsRef.ids(); - } else if (commentsRef.remoteType() === "link") { - var link = commentsRef.link(); - } - // load comments (via store.findMany or store.findHasMany) - commentsRef.load().then(...) - // or trigger a reload - commentsRef.reload().then(...) - // provide data for reference - commentsRef.push([{ type: 'comment', id: 1 }, { type: 'comment', id: 2 }]).then(function(comments) { - commentsRef.value() === comments; - }); - ``` - @method hasMany - @param {String} name of the relationship - @return {HasManyReference} reference for this relationship - */ - hasMany: function hasMany(name) { - return this._internalModel.referenceFor('hasMany', name); - } - }); - } - - Model.reopenClass(_emberDataPrivateSystemRelationshipsExt.RelationshipsClassMethodsMixin); - Model.reopenClass(_emberDataPrivateSystemModelAttr.AttrClassMethodsMixin); - - exports["default"] = Model.extend(_emberDataPrivateSystemDebugDebugInfo["default"], _emberDataPrivateSystemRelationshipsBelongsTo.BelongsToMixin, _emberDataPrivateSystemRelationshipsExt.DidDefinePropertyMixin, _emberDataPrivateSystemRelationshipsExt.RelationshipsInstanceMethodsMixin, _emberDataPrivateSystemRelationshipsHasMany.HasManyMixin, _emberDataPrivateSystemModelAttr.AttrInstanceMethodsMixin); -}); -define('ember-data/-private/system/model/states', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { - /** - @module ember-data - */ - 'use strict'; - - var get = _ember['default'].get; - /* - This file encapsulates the various states that a record can transition - through during its lifecycle. - */ - /** - ### State - - Each record has a `currentState` property that explicitly tracks what - state a record is in at any given time. For instance, if a record is - newly created and has not yet been sent to the adapter to be saved, - it would be in the `root.loaded.created.uncommitted` state. If a - record has had local modifications made to it that are in the - process of being saved, the record would be in the - `root.loaded.updated.inFlight` state. (This state paths will be - explained in more detail below.) - - Events are sent by the record or its store to the record's - `currentState` property. How the state reacts to these events is - dependent on which state it is in. In some states, certain events - will be invalid and will cause an exception to be raised. - - States are hierarchical and every state is a substate of the - `RootState`. For example, a record can be in the - `root.deleted.uncommitted` state, then transition into the - `root.deleted.inFlight` state. If a child state does not implement - an event handler, the state manager will attempt to invoke the event - on all parent states until the root state is reached. The state - hierarchy of a record is described in terms of a path string. You - can determine a record's current state by getting the state's - `stateName` property: - - ```javascript - record.get('currentState.stateName'); - //=> "root.created.uncommitted" - ``` - - The hierarchy of valid states that ship with ember data looks like - this: - - ```text - * root - * deleted - * saved - * uncommitted - * inFlight - * empty - * loaded - * created - * uncommitted - * inFlight - * saved - * updated - * uncommitted - * inFlight - * loading - ``` - - The `DS.Model` states are themselves stateless. What that means is - that, the hierarchical states that each of *those* points to is a - shared data structure. For performance reasons, instead of each - record getting its own copy of the hierarchy of states, each record - points to this global, immutable shared instance. How does a state - know which record it should be acting on? We pass the record - instance into the state's event handlers as the first argument. - - The record passed as the first parameter is where you should stash - state about the record if needed; you should never store data on the state - object itself. - - ### Events and Flags - - A state may implement zero or more events and flags. - - #### Events - - Events are named functions that are invoked when sent to a record. The - record will first look for a method with the given name on the - current state. If no method is found, it will search the current - state's parent, and then its grandparent, and so on until reaching - the top of the hierarchy. If the root is reached without an event - handler being found, an exception will be raised. This can be very - helpful when debugging new features. - - Here's an example implementation of a state with a `myEvent` event handler: - - ```javascript - aState: DS.State.create({ - myEvent: function(manager, param) { - console.log("Received myEvent with", param); - } - }) - ``` - - To trigger this event: - - ```javascript - record.send('myEvent', 'foo'); - //=> "Received myEvent with foo" - ``` - - Note that an optional parameter can be sent to a record's `send()` method, - which will be passed as the second parameter to the event handler. - - Events should transition to a different state if appropriate. This can be - done by calling the record's `transitionTo()` method with a path to the - desired state. The state manager will attempt to resolve the state path - relative to the current state. If no state is found at that path, it will - attempt to resolve it relative to the current state's parent, and then its - parent, and so on until the root is reached. For example, imagine a hierarchy - like this: - - * created - * uncommitted <-- currentState - * inFlight - * updated - * inFlight - - If we are currently in the `uncommitted` state, calling - `transitionTo('inFlight')` would transition to the `created.inFlight` state, - while calling `transitionTo('updated.inFlight')` would transition to - the `updated.inFlight` state. - - Remember that *only events* should ever cause a state transition. You should - never call `transitionTo()` from outside a state's event handler. If you are - tempted to do so, create a new event and send that to the state manager. - - #### Flags - - Flags are Boolean values that can be used to introspect a record's current - state in a more user-friendly way than examining its state path. For example, - instead of doing this: - - ```javascript - var statePath = record.get('stateManager.currentPath'); - if (statePath === 'created.inFlight') { - doSomething(); - } - ``` - - You can say: - - ```javascript - if (record.get('isNew') && record.get('isSaving')) { - doSomething(); - } - ``` - - If your state does not set a value for a given flag, the value will - be inherited from its parent (or the first place in the state hierarchy - where it is defined). - - The current set of flags are defined below. If you want to add a new flag, - in addition to the area below, you will also need to declare it in the - `DS.Model` class. - - - * [isEmpty](DS.Model.html#property_isEmpty) - * [isLoading](DS.Model.html#property_isLoading) - * [isLoaded](DS.Model.html#property_isLoaded) - * [isDirty](DS.Model.html#property_isDirty) - * [isSaving](DS.Model.html#property_isSaving) - * [isDeleted](DS.Model.html#property_isDeleted) - * [isNew](DS.Model.html#property_isNew) - * [isValid](DS.Model.html#property_isValid) - - @namespace DS - @class RootState - */ - - function _didSetProperty(internalModel, context) { - if (context.value === context.originalValue) { - delete internalModel._attributes[context.name]; - internalModel.send('propertyWasReset', context.name); - } else if (context.value !== context.oldValue) { - internalModel.send('becomeDirty'); - } - - internalModel.updateRecordArraysLater(); - } - - // Implementation notes: - // - // Each state has a boolean value for all of the following flags: - // - // * isLoaded: The record has a populated `data` property. When a - // record is loaded via `store.find`, `isLoaded` is false - // until the adapter sets it. When a record is created locally, - // its `isLoaded` property is always true. - // * isDirty: The record has local changes that have not yet been - // saved by the adapter. This includes records that have been - // created (but not yet saved) or deleted. - // * isSaving: The record has been committed, but - // the adapter has not yet acknowledged that the changes have - // been persisted to the backend. - // * isDeleted: The record was marked for deletion. When `isDeleted` - // is true and `isDirty` is true, the record is deleted locally - // but the deletion was not yet persisted. When `isSaving` is - // true, the change is in-flight. When both `isDirty` and - // `isSaving` are false, the change has persisted. - // * isNew: The record was created on the client and the adapter - // did not yet report that it was successfully saved. - // * isValid: The adapter did not report any server-side validation - // failures. - - // The dirty state is a abstract state whose functionality is - // shared between the `created` and `updated` states. - // - // The deleted state shares the `isDirty` flag with the - // subclasses of `DirtyState`, but with a very different - // implementation. - // - // Dirty states have three child states: - // - // `uncommitted`: the store has not yet handed off the record - // to be saved. - // `inFlight`: the store has handed off the record to be saved, - // but the adapter has not yet acknowledged success. - // `invalid`: the record has invalid information and cannot be - // send to the adapter yet. - var DirtyState = { - initialState: 'uncommitted', - - // FLAGS - isDirty: true, - - // SUBSTATES - - // When a record first becomes dirty, it is `uncommitted`. - // This means that there are local pending changes, but they - // have not yet begun to be saved, and are not invalid. - uncommitted: { - // EVENTS - didSetProperty: _didSetProperty, - - //TODO(Igor) reloading now triggers a - //loadingData event, though it seems fine? - loadingData: _ember['default'].K, - - propertyWasReset: function propertyWasReset(internalModel, name) { - if (!internalModel.hasChangedAttributes()) { - internalModel.send('rolledBack'); - } - }, - - pushedData: function pushedData(internalModel) { - internalModel.updateChangedAttributes(); - - if (!internalModel.hasChangedAttributes()) { - internalModel.transitionTo('loaded.saved'); - } - }, - - becomeDirty: _ember['default'].K, - - willCommit: function willCommit(internalModel) { - internalModel.transitionTo('inFlight'); - }, - - reloadRecord: function reloadRecord(internalModel, resolve) { - resolve(internalModel.store.reloadRecord(internalModel)); - }, - - rolledBack: function rolledBack(internalModel) { - internalModel.transitionTo('loaded.saved'); - }, - - becameInvalid: function becameInvalid(internalModel) { - internalModel.transitionTo('invalid'); - }, - - rollback: function rollback(internalModel) { - internalModel.rollbackAttributes(); - internalModel.triggerLater('ready'); - } - }, - - // Once a record has been handed off to the adapter to be - // saved, it is in the 'in flight' state. Changes to the - // record cannot be made during this window. - inFlight: { - // FLAGS - isSaving: true, - - // EVENTS - didSetProperty: _didSetProperty, - becomeDirty: _ember['default'].K, - pushedData: _ember['default'].K, - - unloadRecord: assertAgainstUnloadRecord, - - // TODO: More robust semantics around save-while-in-flight - willCommit: _ember['default'].K, - - didCommit: function didCommit(internalModel) { - var dirtyType = get(this, 'dirtyType'); - - internalModel.transitionTo('saved'); - internalModel.send('invokeLifecycleCallbacks', dirtyType); - }, - - becameInvalid: function becameInvalid(internalModel) { - internalModel.transitionTo('invalid'); - internalModel.send('invokeLifecycleCallbacks'); - }, - - becameError: function becameError(internalModel) { - internalModel.transitionTo('uncommitted'); - internalModel.triggerLater('becameError', internalModel); - } - }, - - // A record is in the `invalid` if the adapter has indicated - // the the record failed server-side invalidations. - invalid: { - // FLAGS - isValid: false, - - // EVENTS - deleteRecord: function deleteRecord(internalModel) { - internalModel.transitionTo('deleted.uncommitted'); - }, - - didSetProperty: function didSetProperty(internalModel, context) { - internalModel.removeErrorMessageFromAttribute(context.name); - - _didSetProperty(internalModel, context); - - if (!internalModel.hasErrors()) { - this.becameValid(internalModel); - } - }, - - becameInvalid: _ember['default'].K, - becomeDirty: _ember['default'].K, - pushedData: _ember['default'].K, - - willCommit: function willCommit(internalModel) { - internalModel.clearErrorMessages(); - internalModel.transitionTo('inFlight'); - }, - - rolledBack: function rolledBack(internalModel) { - internalModel.clearErrorMessages(); - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('ready'); - }, - - becameValid: function becameValid(internalModel) { - internalModel.transitionTo('uncommitted'); - }, - - invokeLifecycleCallbacks: function invokeLifecycleCallbacks(internalModel) { - internalModel.triggerLater('becameInvalid', internalModel); - } - } - }; - - // The created and updated states are created outside the state - // chart so we can reopen their substates and add mixins as - // necessary. - - function deepClone(object) { - var clone = {}; - var value; - - for (var prop in object) { - value = object[prop]; - if (value && typeof value === 'object') { - clone[prop] = deepClone(value); - } else { - clone[prop] = value; - } - } - - return clone; - } - - function mixin(original, hash) { - for (var prop in hash) { - original[prop] = hash[prop]; - } - - return original; - } - - function dirtyState(options) { - var newState = deepClone(DirtyState); - return mixin(newState, options); - } - - var createdState = dirtyState({ - dirtyType: 'created', - // FLAGS - isNew: true - }); - - createdState.invalid.rolledBack = function (internalModel) { - internalModel.transitionTo('deleted.saved'); - }; - createdState.uncommitted.rolledBack = function (internalModel) { - internalModel.transitionTo('deleted.saved'); - }; - - var updatedState = dirtyState({ - dirtyType: 'updated' - }); - - createdState.uncommitted.deleteRecord = function (internalModel) { - internalModel.transitionTo('deleted.saved'); - internalModel.send('invokeLifecycleCallbacks'); - }; - - createdState.uncommitted.rollback = function (internalModel) { - DirtyState.uncommitted.rollback.apply(this, arguments); - internalModel.transitionTo('deleted.saved'); - }; - - createdState.uncommitted.pushedData = function (internalModel) { - internalModel.transitionTo('loaded.updated.uncommitted'); - internalModel.triggerLater('didLoad'); - }; - - createdState.uncommitted.propertyWasReset = _ember['default'].K; - - function assertAgainstUnloadRecord(internalModel) { - (0, _emberDataPrivateDebug.assert)("You can only unload a record which is not inFlight. `" + internalModel + "`", false); - } - - updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord; - - updatedState.uncommitted.deleteRecord = function (internalModel) { - internalModel.transitionTo('deleted.uncommitted'); - }; - - var RootState = { - // FLAGS - isEmpty: false, - isLoading: false, - isLoaded: false, - isDirty: false, - isSaving: false, - isDeleted: false, - isNew: false, - isValid: true, - - // DEFAULT EVENTS - - // Trying to roll back if you're not in the dirty state - // doesn't change your state. For example, if you're in the - // in-flight state, rolling back the record doesn't move - // you out of the in-flight state. - rolledBack: _ember['default'].K, - unloadRecord: function unloadRecord(internalModel) { - // clear relationships before moving to deleted state - // otherwise it fails - internalModel.clearRelationships(); - internalModel.transitionTo('deleted.saved'); - }, - - propertyWasReset: _ember['default'].K, - - // SUBSTATES - - // A record begins its lifecycle in the `empty` state. - // If its data will come from the adapter, it will - // transition into the `loading` state. Otherwise, if - // the record is being created on the client, it will - // transition into the `created` state. - empty: { - isEmpty: true, - - // EVENTS - loadingData: function loadingData(internalModel, promise) { - internalModel._loadingPromise = promise; - internalModel.transitionTo('loading'); - }, - - loadedData: function loadedData(internalModel) { - internalModel.transitionTo('loaded.created.uncommitted'); - internalModel.triggerLater('ready'); - }, - - pushedData: function pushedData(internalModel) { - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('didLoad'); - internalModel.triggerLater('ready'); - } - }, - - // A record enters this state when the store asks - // the adapter for its data. It remains in this state - // until the adapter provides the requested data. - // - // Usually, this process is asynchronous, using an - // XHR to retrieve the data. - loading: { - // FLAGS - isLoading: true, - - exit: function exit(internalModel) { - internalModel._loadingPromise = null; - }, - - // EVENTS - pushedData: function pushedData(internalModel) { - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('didLoad'); - internalModel.triggerLater('ready'); - //TODO this seems out of place here - internalModel.didCleanError(); - }, - - becameError: function becameError(internalModel) { - internalModel.triggerLater('becameError', internalModel); - }, - - notFound: function notFound(internalModel) { - internalModel.transitionTo('empty'); - } - }, - - // A record enters this state when its data is populated. - // Most of a record's lifecycle is spent inside substates - // of the `loaded` state. - loaded: { - initialState: 'saved', - - // FLAGS - isLoaded: true, - - //TODO(Igor) Reloading now triggers a loadingData event, - //but it should be ok? - loadingData: _ember['default'].K, - - // SUBSTATES - - // If there are no local changes to a record, it remains - // in the `saved` state. - saved: { - setup: function setup(internalModel) { - if (internalModel.hasChangedAttributes()) { - internalModel.adapterDidDirty(); - } - }, - - // EVENTS - didSetProperty: _didSetProperty, - - pushedData: _ember['default'].K, - - becomeDirty: function becomeDirty(internalModel) { - internalModel.transitionTo('updated.uncommitted'); - }, - - willCommit: function willCommit(internalModel) { - internalModel.transitionTo('updated.inFlight'); - }, - - reloadRecord: function reloadRecord(internalModel, resolve) { - resolve(internalModel.store.reloadRecord(internalModel)); - }, - - deleteRecord: function deleteRecord(internalModel) { - internalModel.transitionTo('deleted.uncommitted'); - }, - - unloadRecord: function unloadRecord(internalModel) { - // clear relationships before moving to deleted state - // otherwise it fails - internalModel.clearRelationships(); - internalModel.transitionTo('deleted.saved'); - }, - - didCommit: function didCommit(internalModel) { - internalModel.send('invokeLifecycleCallbacks', get(internalModel, 'lastDirtyType')); - }, - - // loaded.saved.notFound would be triggered by a failed - // `reload()` on an unchanged record - notFound: _ember['default'].K - - }, - - // A record is in this state after it has been locally - // created but before the adapter has indicated that - // it has been saved. - created: createdState, - - // A record is in this state if it has already been - // saved to the server, but there are new local changes - // that have not yet been saved. - updated: updatedState - }, - - // A record is in this state if it was deleted from the store. - deleted: { - initialState: 'uncommitted', - dirtyType: 'deleted', - - // FLAGS - isDeleted: true, - isLoaded: true, - isDirty: true, - - // TRANSITIONS - setup: function setup(internalModel) { - internalModel.updateRecordArrays(); - }, - - // SUBSTATES - - // When a record is deleted, it enters the `start` - // state. It will exit this state when the record - // starts to commit. - uncommitted: { - - // EVENTS - - willCommit: function willCommit(internalModel) { - internalModel.transitionTo('inFlight'); - }, - - rollback: function rollback(internalModel) { - internalModel.rollbackAttributes(); - internalModel.triggerLater('ready'); - }, - - pushedData: _ember['default'].K, - becomeDirty: _ember['default'].K, - deleteRecord: _ember['default'].K, - - rolledBack: function rolledBack(internalModel) { - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('ready'); - } - }, - - // After a record starts committing, but - // before the adapter indicates that the deletion - // has saved to the server, a record is in the - // `inFlight` substate of `deleted`. - inFlight: { - // FLAGS - isSaving: true, - - // EVENTS - - unloadRecord: assertAgainstUnloadRecord, - - // TODO: More robust semantics around save-while-in-flight - willCommit: _ember['default'].K, - didCommit: function didCommit(internalModel) { - internalModel.transitionTo('saved'); - - internalModel.send('invokeLifecycleCallbacks'); - }, - - becameError: function becameError(internalModel) { - internalModel.transitionTo('uncommitted'); - internalModel.triggerLater('becameError', internalModel); - }, - - becameInvalid: function becameInvalid(internalModel) { - internalModel.transitionTo('invalid'); - internalModel.triggerLater('becameInvalid', internalModel); - } - }, - - // Once the adapter indicates that the deletion has - // been saved, the record enters the `saved` substate - // of `deleted`. - saved: { - // FLAGS - isDirty: false, - - setup: function setup(internalModel) { - internalModel.clearRelationships(); - var store = internalModel.store; - store._dematerializeRecord(internalModel); - }, - - invokeLifecycleCallbacks: function invokeLifecycleCallbacks(internalModel) { - internalModel.triggerLater('didDelete', internalModel); - internalModel.triggerLater('didCommit', internalModel); - }, - - willCommit: _ember['default'].K, - - didCommit: _ember['default'].K - }, - - invalid: { - isValid: false, - - didSetProperty: function didSetProperty(internalModel, context) { - internalModel.removeErrorMessageFromAttribute(context.name); - - _didSetProperty(internalModel, context); - - if (!internalModel.hasErrors()) { - this.becameValid(internalModel); - } - }, - - becameInvalid: _ember['default'].K, - becomeDirty: _ember['default'].K, - deleteRecord: _ember['default'].K, - willCommit: _ember['default'].K, - - rolledBack: function rolledBack(internalModel) { - internalModel.clearErrorMessages(); - internalModel.transitionTo('loaded.saved'); - internalModel.triggerLater('ready'); - }, - - becameValid: function becameValid(internalModel) { - internalModel.transitionTo('uncommitted'); - } - - } - }, - - invokeLifecycleCallbacks: function invokeLifecycleCallbacks(internalModel, dirtyType) { - if (dirtyType === 'created') { - internalModel.triggerLater('didCreate', internalModel); - } else { - internalModel.triggerLater('didUpdate', internalModel); - } - - internalModel.triggerLater('didCommit', internalModel); - } - }; - - function wireState(object, parent, name) { - /*jshint proto:true*/ - // TODO: Use Object.create and copy instead - object = mixin(parent ? Object.create(parent) : {}, object); - object.parentState = parent; - object.stateName = name; - - for (var prop in object) { - if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { - continue; - } - if (typeof object[prop] === 'object') { - object[prop] = wireState(object[prop], object, name + "." + prop); - } - } - - return object; - } - - RootState = wireState(RootState, null, "root"); - - exports['default'] = RootState; -}); -define("ember-data/-private/system/model", ["exports", "ember-data/-private/system/model/model", "ember-data/attr", "ember-data/-private/system/model/states", "ember-data/-private/system/model/errors"], function (exports, _emberDataPrivateSystemModelModel, _emberDataAttr, _emberDataPrivateSystemModelStates, _emberDataPrivateSystemModelErrors) { - /** - @module ember-data - */ - - "use strict"; - - exports.RootState = _emberDataPrivateSystemModelStates["default"]; - exports.attr = _emberDataAttr["default"]; - exports.Errors = _emberDataPrivateSystemModelErrors["default"]; - exports["default"] = _emberDataPrivateSystemModelModel["default"]; -}); -define('ember-data/-private/system/normalize-link', ['exports'], function (exports) { - 'use strict'; - - exports['default'] = _normalizeLink; - - /** - This method normalizes a link to an "links object". If the passed link is - already an object it's returned without any modifications. - - See http://jsonapi.org/format/#document-links for more information. - - @method _normalizeLink - @private - @param {String} link - @return {Object|null} - @for DS - */ - function _normalizeLink(link) { - switch (typeof link) { - case 'object': - return link; - case 'string': - return { href: link }; - } - return null; - } -}); -define('ember-data/-private/system/normalize-model-name', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports['default'] = normalizeModelName; - - /** - All modelNames are dasherized internally. Changing this function may - require changes to other normalization hooks (such as typeForRoot). - @method normalizeModelName - @public - @param {String} modelName - @return {String} if the adapter can generate one, an ID - @for DS - */ - function normalizeModelName(modelName) { - return _ember['default'].String.dasherize(modelName); - } -}); -define('ember-data/-private/system/ordered-set', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports['default'] = OrderedSet; - - var EmberOrderedSet = _ember['default'].OrderedSet; - var guidFor = _ember['default'].guidFor; - function OrderedSet() { - this._super$constructor(); - } - - OrderedSet.create = function () { - var Constructor = this; - return new Constructor(); - }; - - OrderedSet.prototype = Object.create(EmberOrderedSet.prototype); - OrderedSet.prototype.constructor = OrderedSet; - OrderedSet.prototype._super$constructor = EmberOrderedSet; - - OrderedSet.prototype.addWithIndex = function (obj, idx) { - var guid = guidFor(obj); - var presenceSet = this.presenceSet; - var list = this.list; - - if (presenceSet[guid] === true) { - return; - } - - presenceSet[guid] = true; - - if (idx === undefined || idx == null) { - list.push(obj); - } else { - list.splice(idx, 0, obj); - } - - this.size += 1; - - return this; - }; -}); -define('ember-data/-private/system/promise-proxies', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { - 'use strict'; - - var Promise = _ember['default'].RSVP.Promise; - var get = _ember['default'].get; - - /** - A `PromiseArray` is an object that acts like both an `Ember.Array` - and a promise. When the promise is resolved the resulting value - will be set to the `PromiseArray`'s `content` property. This makes - it easy to create data bindings with the `PromiseArray` that will be - updated when the promise resolves. - - For more information see the [Ember.PromiseProxyMixin - documentation](/api/classes/Ember.PromiseProxyMixin.html). - - Example - - ```javascript - var promiseArray = DS.PromiseArray.create({ - promise: $.getJSON('/some/remote/data.json') - }); - - promiseArray.get('length'); // 0 - - promiseArray.then(function() { - promiseArray.get('length'); // 100 - }); - ``` - - @class PromiseArray - @namespace DS - @extends Ember.ArrayProxy - @uses Ember.PromiseProxyMixin - */ - var PromiseArray = _ember['default'].ArrayProxy.extend(_ember['default'].PromiseProxyMixin); - - /** - A `PromiseObject` is an object that acts like both an `Ember.Object` - and a promise. When the promise is resolved, then the resulting value - will be set to the `PromiseObject`'s `content` property. This makes - it easy to create data bindings with the `PromiseObject` that will - be updated when the promise resolves. - - For more information see the [Ember.PromiseProxyMixin - documentation](/api/classes/Ember.PromiseProxyMixin.html). - - Example - - ```javascript - var promiseObject = DS.PromiseObject.create({ - promise: $.getJSON('/some/remote/data.json') - }); - - promiseObject.get('name'); // null - - promiseObject.then(function() { - promiseObject.get('name'); // 'Tomster' - }); - ``` - - @class PromiseObject - @namespace DS - @extends Ember.ObjectProxy - @uses Ember.PromiseProxyMixin - */ - var PromiseObject = _ember['default'].ObjectProxy.extend(_ember['default'].PromiseProxyMixin); - - var promiseObject = function promiseObject(promise, label) { - return PromiseObject.create({ - promise: Promise.resolve(promise, label) - }); - }; - - var promiseArray = function promiseArray(promise, label) { - return PromiseArray.create({ - promise: Promise.resolve(promise, label) - }); - }; - - /** - A PromiseManyArray is a PromiseArray that also proxies certain method calls - to the underlying manyArray. - Right now we proxy: - - * `reload()` - * `createRecord()` - * `on()` - * `one()` - * `trigger()` - * `off()` - * `has()` - - @class PromiseManyArray - @namespace DS - @extends Ember.ArrayProxy - */ - - function proxyToContent(method) { - return function () { - var content = get(this, 'content'); - return content[method].apply(content, arguments); - }; - } - - var PromiseManyArray = PromiseArray.extend({ - reload: function reload() { - //I don't think this should ever happen right now, but worth guarding if we refactor the async relationships - (0, _emberDataPrivateDebug.assert)('You are trying to reload an async manyArray before it has been created', get(this, 'content')); - return PromiseManyArray.create({ - promise: get(this, 'content').reload() - }); - }, - - createRecord: proxyToContent('createRecord'), - - on: proxyToContent('on'), - - one: proxyToContent('one'), - - trigger: proxyToContent('trigger'), - - off: proxyToContent('off'), - - has: proxyToContent('has') - }); - - var promiseManyArray = function promiseManyArray(promise, label) { - return PromiseManyArray.create({ - promise: Promise.resolve(promise, label) - }); - }; - - exports.PromiseArray = PromiseArray; - exports.PromiseObject = PromiseObject; - exports.PromiseManyArray = PromiseManyArray; - exports.promiseArray = promiseArray; - exports.promiseObject = promiseObject; - exports.promiseManyArray = promiseManyArray; -}); -define("ember-data/-private/system/record-array-manager", ["exports", "ember", "ember-data/-private/system/record-arrays", "ember-data/-private/system/ordered-set"], function (exports, _ember, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemOrderedSet) { - /** - @module ember-data - */ - - "use strict"; - - var MapWithDefault = _ember["default"].MapWithDefault;var get = _ember["default"].get; - - /** - @class RecordArrayManager - @namespace DS - @private - @extends Ember.Object - */ - exports["default"] = _ember["default"].Object.extend({ - init: function init() { - var _this = this; - - this.filteredRecordArrays = MapWithDefault.create({ - defaultValue: function defaultValue() { - return []; - } - }); - - this.liveRecordArrays = MapWithDefault.create({ - defaultValue: function defaultValue(typeClass) { - return _this.createRecordArray(typeClass); - } - }); - - this.changedRecords = []; - this._adapterPopulatedRecordArrays = []; - }, - - recordDidChange: function recordDidChange(record) { - if (this.changedRecords.push(record) !== 1) { - return; - } - - _ember["default"].run.schedule('actions', this, this.updateRecordArrays); - }, - - recordArraysForRecord: function recordArraysForRecord(record) { - record._recordArrays = record._recordArrays || _emberDataPrivateSystemOrderedSet["default"].create(); - return record._recordArrays; - }, - - /** - This method is invoked whenever data is loaded into the store by the - adapter or updated by the adapter, or when a record has changed. - It updates all record arrays that a record belongs to. - To avoid thrashing, it only runs at most once per run loop. - @method updateRecordArrays - */ - updateRecordArrays: function updateRecordArrays() { - var _this2 = this; - - this.changedRecords.forEach(function (internalModel) { - if (get(internalModel, 'record.isDestroyed') || get(internalModel, 'record.isDestroying') || get(internalModel, 'currentState.stateName') === 'root.deleted.saved') { - _this2._recordWasDeleted(internalModel); - } else { - _this2._recordWasChanged(internalModel); - } - }); - - this.changedRecords.length = 0; - }, - - _recordWasDeleted: function _recordWasDeleted(record) { - var recordArrays = record._recordArrays; - - if (!recordArrays) { - return; - } - - recordArrays.forEach(function (array) { - return array.removeInternalModel(record); - }); - - record._recordArrays = null; - }, - - _recordWasChanged: function _recordWasChanged(record) { - var _this3 = this; - - var typeClass = record.type; - var recordArrays = this.filteredRecordArrays.get(typeClass); - var filter; - recordArrays.forEach(function (array) { - filter = get(array, 'filterFunction'); - _this3.updateFilterRecordArray(array, filter, typeClass, record); - }); - }, - - //Need to update live arrays on loading - recordWasLoaded: function recordWasLoaded(record) { - var _this4 = this; - - var typeClass = record.type; - var recordArrays = this.filteredRecordArrays.get(typeClass); - var filter; - - recordArrays.forEach(function (array) { - filter = get(array, 'filterFunction'); - _this4.updateFilterRecordArray(array, filter, typeClass, record); - }); - - if (this.liveRecordArrays.has(typeClass)) { - var liveRecordArray = this.liveRecordArrays.get(typeClass); - this._addRecordToRecordArray(liveRecordArray, record); - } - }, - /** - Update an individual filter. - @method updateFilterRecordArray - @param {DS.FilteredRecordArray} array - @param {Function} filter - @param {DS.Model} typeClass - @param {InternalModel} record - */ - updateFilterRecordArray: function updateFilterRecordArray(array, filter, typeClass, record) { - var shouldBeInArray = filter(record.getRecord()); - var recordArrays = this.recordArraysForRecord(record); - if (shouldBeInArray) { - this._addRecordToRecordArray(array, record); - } else { - recordArrays["delete"](array); - array.removeInternalModel(record); - } - }, - - _addRecordToRecordArray: function _addRecordToRecordArray(array, record) { - var recordArrays = this.recordArraysForRecord(record); - if (!recordArrays.has(array)) { - array.addInternalModel(record); - recordArrays.add(array); - } - }, - - populateLiveRecordArray: function populateLiveRecordArray(array, modelName) { - var typeMap = this.store.typeMapFor(modelName); - var records = typeMap.records; - var record; - - for (var i = 0; i < records.length; i++) { - record = records[i]; - - if (!record.isDeleted() && !record.isEmpty()) { - this._addRecordToRecordArray(array, record); - } - } - }, - - /** - This method is invoked if the `filterFunction` property is - changed on a `DS.FilteredRecordArray`. - It essentially re-runs the filter from scratch. This same - method is invoked when the filter is created in th first place. - @method updateFilter - @param {Array} array - @param {String} modelName - @param {Function} filter - */ - updateFilter: function updateFilter(array, modelName, filter) { - var typeMap = this.store.typeMapFor(modelName); - var records = typeMap.records; - var record; - - for (var i = 0; i < records.length; i++) { - record = records[i]; - - if (!record.isDeleted() && !record.isEmpty()) { - this.updateFilterRecordArray(array, filter, modelName, record); - } - } - }, - - /** - Get the `DS.RecordArray` for a type, which contains all loaded records of - given type. - @method liveRecordArrayFor - @param {Class} typeClass - @return {DS.RecordArray} - */ - liveRecordArrayFor: function liveRecordArrayFor(typeClass) { - return this.liveRecordArrays.get(typeClass); - }, - - /** - Create a `DS.RecordArray` for a type. - @method createRecordArray - @param {Class} typeClass - @return {DS.RecordArray} - */ - createRecordArray: function createRecordArray(typeClass) { - var array = _emberDataPrivateSystemRecordArrays.RecordArray.create({ - type: typeClass, - content: _ember["default"].A(), - store: this.store, - isLoaded: true, - manager: this - }); - - return array; - }, - - /** - Create a `DS.FilteredRecordArray` for a type and register it for updates. - @method createFilteredRecordArray - @param {DS.Model} typeClass - @param {Function} filter - @param {Object} query (optional - @return {DS.FilteredRecordArray} - */ - createFilteredRecordArray: function createFilteredRecordArray(typeClass, filter, query) { - var array = _emberDataPrivateSystemRecordArrays.FilteredRecordArray.create({ - query: query, - type: typeClass, - content: _ember["default"].A(), - store: this.store, - manager: this, - filterFunction: filter - }); - - this.registerFilteredRecordArray(array, typeClass, filter); - - return array; - }, - - /** - Create a `DS.AdapterPopulatedRecordArray` for a type with given query. - @method createAdapterPopulatedRecordArray - @param {DS.Model} typeClass - @param {Object} query - @return {DS.AdapterPopulatedRecordArray} - */ - createAdapterPopulatedRecordArray: function createAdapterPopulatedRecordArray(typeClass, query) { - var array = _emberDataPrivateSystemRecordArrays.AdapterPopulatedRecordArray.create({ - type: typeClass, - query: query, - content: _ember["default"].A(), - store: this.store, - manager: this - }); - - this._adapterPopulatedRecordArrays.push(array); - - return array; - }, - - /** - Register a RecordArray for a given type to be backed by - a filter function. This will cause the array to update - automatically when records of that type change attribute - values or states. - @method registerFilteredRecordArray - @param {DS.RecordArray} array - @param {DS.Model} typeClass - @param {Function} filter - */ - registerFilteredRecordArray: function registerFilteredRecordArray(array, typeClass, filter) { - var recordArrays = this.filteredRecordArrays.get(typeClass); - recordArrays.push(array); - - this.updateFilter(array, typeClass, filter); - }, - - /** - Unregister a RecordArray. - So manager will not update this array. - @method unregisterRecordArray - @param {DS.RecordArray} array - */ - unregisterRecordArray: function unregisterRecordArray(array) { - var typeClass = array.type; - - // unregister filtered record array - var recordArrays = this.filteredRecordArrays.get(typeClass); - var removedFromFiltered = remove(recordArrays, array); - - // remove from adapter populated record array - var removedFromAdapterPopulated = remove(this._adapterPopulatedRecordArrays, array); - - if (!removedFromFiltered && !removedFromAdapterPopulated) { - - // unregister live record array - if (this.liveRecordArrays.has(typeClass)) { - var liveRecordArrayForType = this.liveRecordArrayFor(typeClass); - if (array === liveRecordArrayForType) { - this.liveRecordArrays["delete"](typeClass); - } - } - } - }, - - willDestroy: function willDestroy() { - this._super.apply(this, arguments); - - this.filteredRecordArrays.forEach(function (value) { - return flatten(value).forEach(destroy); - }); - this.liveRecordArrays.forEach(destroy); - this._adapterPopulatedRecordArrays.forEach(destroy); - } - }); - - function destroy(entry) { - entry.destroy(); - } - - function flatten(list) { - var length = list.length; - var result = _ember["default"].A(); - - for (var i = 0; i < length; i++) { - result = result.concat(list[i]); - } - - return result; - } - - function remove(array, item) { - var index = array.indexOf(item); - - if (index !== -1) { - array.splice(index, 1); - return true; - } - - return false; - } -}); -define("ember-data/-private/system/record-arrays/adapter-populated-record-array", ["exports", "ember", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/clone-null"], function (exports, _ember, _emberDataPrivateSystemRecordArraysRecordArray, _emberDataPrivateSystemCloneNull) { - "use strict"; - - /** - @module ember-data - */ - - var get = _ember["default"].get; - - /** - Represents an ordered list of records whose order and membership is - determined by the adapter. For example, a query sent to the adapter - may trigger a search on the server, whose results would be loaded - into an instance of the `AdapterPopulatedRecordArray`. - - @class AdapterPopulatedRecordArray - @namespace DS - @extends DS.RecordArray - */ - exports["default"] = _emberDataPrivateSystemRecordArraysRecordArray["default"].extend({ - query: null, - - replace: function replace() { - var type = get(this, 'type').toString(); - throw new Error("The result of a server query (on " + type + ") is immutable."); - }, - - /** - @method loadRecords - @param {Array} records - @param {Object} payload normalized payload - @private - */ - loadRecords: function loadRecords(records, payload) { - var _this = this; - - //TODO Optimize - var internalModels = _ember["default"].A(records).mapBy('_internalModel'); - this.setProperties({ - content: _ember["default"].A(internalModels), - isLoaded: true, - meta: (0, _emberDataPrivateSystemCloneNull["default"])(payload.meta) - }); - - internalModels.forEach(function (record) { - _this.manager.recordArraysForRecord(record).add(_this); - }); - - // TODO: should triggering didLoad event be the last action of the runLoop? - _ember["default"].run.once(this, 'trigger', 'didLoad'); - } - }); -}); -define('ember-data/-private/system/record-arrays/filtered-record-array', ['exports', 'ember', 'ember-data/-private/system/record-arrays/record-array'], function (exports, _ember, _emberDataPrivateSystemRecordArraysRecordArray) { - 'use strict'; - - /** - @module ember-data - */ - - var get = _ember['default'].get; - - /** - Represents a list of records whose membership is determined by the - store. As records are created, loaded, or modified, the store - evaluates them to determine if they should be part of the record - array. - - @class FilteredRecordArray - @namespace DS - @extends DS.RecordArray - */ - exports['default'] = _emberDataPrivateSystemRecordArraysRecordArray['default'].extend({ - /** - The filterFunction is a function used to test records from the store to - determine if they should be part of the record array. - Example - ```javascript - var allPeople = store.peekAll('person'); - allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] - var people = store.filter('person', function(person) { - if (person.get('name').match(/Katz$/)) { return true; } - }); - people.mapBy('name'); // ["Yehuda Katz"] - var notKatzFilter = function(person) { - return !person.get('name').match(/Katz$/); - }; - people.set('filterFunction', notKatzFilter); - people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] - ``` - @method filterFunction - @param {DS.Model} record - @return {Boolean} `true` if the record should be in the array - */ - filterFunction: null, - isLoaded: true, - - replace: function replace() { - var type = get(this, 'type').toString(); - throw new Error("The result of a client-side filter (on " + type + ") is immutable."); - }, - - /** - @method updateFilter - @private - */ - _updateFilter: function _updateFilter() { - var manager = get(this, 'manager'); - manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); - }, - - updateFilter: _ember['default'].observer('filterFunction', function () { - _ember['default'].run.once(this, this._updateFilter); - }) - }); -}); -define("ember-data/-private/system/record-arrays/record-array", ["exports", "ember", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/snapshot-record-array"], function (exports, _ember, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemSnapshotRecordArray) { - /** - @module ember-data - */ - - "use strict"; - - var get = _ember["default"].get; - var set = _ember["default"].set; - - /** - A record array is an array that contains records of a certain type. The record - array materializes records as needed when they are retrieved for the first - time. You should not create record arrays yourself. Instead, an instance of - `DS.RecordArray` or its subclasses will be returned by your application's store - in response to queries. - - @class RecordArray - @namespace DS - @extends Ember.ArrayProxy - @uses Ember.Evented - */ - - exports["default"] = _ember["default"].ArrayProxy.extend(_ember["default"].Evented, { - /** - The model type contained by this record array. - @property type - @type DS.Model - */ - type: null, - - /** - The array of client ids backing the record array. When a - record is requested from the record array, the record - for the client id at the same index is materialized, if - necessary, by the store. - @property content - @private - @type Ember.Array - */ - content: null, - - /** - The flag to signal a `RecordArray` is finished loading data. - Example - ```javascript - var people = store.peekAll('person'); - people.get('isLoaded'); // true - ``` - @property isLoaded - @type Boolean - */ - isLoaded: false, - /** - The flag to signal a `RecordArray` is currently loading data. - Example - ```javascript - var people = store.peekAll('person'); - people.get('isUpdating'); // false - people.update(); - people.get('isUpdating'); // true - ``` - @property isUpdating - @type Boolean - */ - isUpdating: false, - - /** - The store that created this record array. - @property store - @private - @type DS.Store - */ - store: null, - - /** - Retrieves an object from the content by index. - @method objectAtContent - @private - @param {Number} index - @return {DS.Model} record - */ - objectAtContent: function objectAtContent(index) { - var content = get(this, 'content'); - var internalModel = content.objectAt(index); - return internalModel && internalModel.getRecord(); - }, - - /** - Used to get the latest version of all of the records in this array - from the adapter. - Example - ```javascript - var people = store.peekAll('person'); - people.get('isUpdating'); // false - people.update(); - people.get('isUpdating'); // true - ``` - @method update - */ - update: function update() { - if (get(this, 'isUpdating')) { - return; - } - - var store = get(this, 'store'); - var modelName = get(this, 'type.modelName'); - var query = get(this, 'query'); - - if (query) { - return store._query(modelName, query, this); - } - - return store.findAll(modelName, { reload: true }); - }, - - /** - Adds an internal model to the `RecordArray` without duplicates - @method addInternalModel - @private - @param {InternalModel} internalModel - @param {number} an optional index to insert at - */ - addInternalModel: function addInternalModel(internalModel, idx) { - var content = get(this, 'content'); - if (idx === undefined) { - content.addObject(internalModel); - } else if (!content.contains(internalModel)) { - content.insertAt(idx, internalModel); - } - }, - - /** - Removes an internalModel to the `RecordArray`. - @method removeInternalModel - @private - @param {InternalModel} internalModel - */ - removeInternalModel: function removeInternalModel(internalModel) { - get(this, 'content').removeObject(internalModel); - }, - - /** - Saves all of the records in the `RecordArray`. - Example - ```javascript - var messages = store.peekAll('message'); - messages.forEach(function(message) { - message.set('hasBeenSeen', true); - }); - messages.save(); - ``` - @method save - @return {DS.PromiseArray} promise - */ - save: function save() { - var recordArray = this; - var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); - var promise = _ember["default"].RSVP.all(this.invoke("save"), promiseLabel).then(function (array) { - return recordArray; - }, null, "DS: RecordArray#save return RecordArray"); - - return _emberDataPrivateSystemPromiseProxies.PromiseArray.create({ promise: promise }); - }, - - _dissociateFromOwnRecords: function _dissociateFromOwnRecords() { - var _this = this; - - this.get('content').forEach(function (record) { - var recordArrays = record._recordArrays; - - if (recordArrays) { - recordArrays["delete"](_this); - } - }); - }, - - /** - @method _unregisterFromManager - @private - */ - _unregisterFromManager: function _unregisterFromManager() { - var manager = get(this, 'manager'); - manager.unregisterRecordArray(this); - }, - - willDestroy: function willDestroy() { - this._unregisterFromManager(); - this._dissociateFromOwnRecords(); - set(this, 'content', undefined); - this._super.apply(this, arguments); - }, - - createSnapshot: function createSnapshot(options) { - var meta = this.get('meta'); - return new _emberDataPrivateSystemSnapshotRecordArray["default"](this, meta, options); - } - }); -}); -define("ember-data/-private/system/record-arrays", ["exports", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/record-arrays/filtered-record-array", "ember-data/-private/system/record-arrays/adapter-populated-record-array"], function (exports, _emberDataPrivateSystemRecordArraysRecordArray, _emberDataPrivateSystemRecordArraysFilteredRecordArray, _emberDataPrivateSystemRecordArraysAdapterPopulatedRecordArray) { - /** - @module ember-data - */ - - "use strict"; - - exports.RecordArray = _emberDataPrivateSystemRecordArraysRecordArray["default"]; - exports.FilteredRecordArray = _emberDataPrivateSystemRecordArraysFilteredRecordArray["default"]; - exports.AdapterPopulatedRecordArray = _emberDataPrivateSystemRecordArraysAdapterPopulatedRecordArray["default"]; -}); -define('ember-data/-private/system/references/belongs-to', ['exports', 'ember-data/model', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/utils'], function (exports, _emberDataModel, _ember, _emberDataPrivateSystemReferencesReference, _emberDataPrivateUtils) { - 'use strict'; - - var BelongsToReference = function BelongsToReference(store, parentInternalModel, belongsToRelationship) { - this._super$constructor(store, parentInternalModel); - this.belongsToRelationship = belongsToRelationship; - this.type = belongsToRelationship.relationshipMeta.type; - this.parent = parentInternalModel.recordReference; - - // TODO inverse - }; - - BelongsToReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference['default'].prototype); - BelongsToReference.prototype.constructor = BelongsToReference; - BelongsToReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference['default']; - - BelongsToReference.prototype.remoteType = function () { - if (this.belongsToRelationship.link) { - return "link"; - } - - return "id"; - }; - - BelongsToReference.prototype.id = function () { - var inverseRecord = this.belongsToRelationship.inverseRecord; - return inverseRecord && inverseRecord.id; - }; - - BelongsToReference.prototype.link = function () { - return this.belongsToRelationship.link; - }; - - BelongsToReference.prototype.meta = function () { - return this.belongsToRelationship.meta; - }; - - BelongsToReference.prototype.push = function (objectOrPromise) { - var _this = this; - - return _ember['default'].RSVP.resolve(objectOrPromise).then(function (data) { - var record; - - if (data instanceof _emberDataModel['default']) { - record = data; - } else { - record = _this.store.push(data); - } - - (0, _emberDataPrivateUtils.assertPolymorphicType)(_this.internalModel, _this.belongsToRelationship.relationshipMeta, record._internalModel); - - _this.belongsToRelationship.setCanonicalRecord(record._internalModel); - - return record; - }); - }; - - BelongsToReference.prototype.value = function () { - var inverseRecord = this.belongsToRelationship.inverseRecord; - return inverseRecord && inverseRecord.record; - }; - - BelongsToReference.prototype.load = function () { - var _this2 = this; - - if (this.remoteType() === "id") { - return this.belongsToRelationship.getRecord(); - } - - if (this.remoteType() === "link") { - return this.belongsToRelationship.findLink().then(function (internalModel) { - return _this2.value(); - }); - } - }; - - BelongsToReference.prototype.reload = function () { - var _this3 = this; - - return this.belongsToRelationship.reload().then(function (internalModel) { - return _this3.value(); - }); - }; - - exports['default'] = BelongsToReference; -}); -define('ember-data/-private/system/references/has-many', ['exports', 'ember', 'ember-data/-private/system/references/reference'], function (exports, _ember, _emberDataPrivateSystemReferencesReference) { - 'use strict'; - - var get = _ember['default'].get; - - var HasManyReference = function HasManyReference(store, parentInternalModel, hasManyRelationship) { - this._super$constructor(store, parentInternalModel); - this.hasManyRelationship = hasManyRelationship; - this.type = hasManyRelationship.relationshipMeta.type; - this.parent = parentInternalModel.recordReference; - - // TODO inverse - }; - - HasManyReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference['default'].prototype); - HasManyReference.prototype.constructor = HasManyReference; - HasManyReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference['default']; - - HasManyReference.prototype.remoteType = function () { - if (this.hasManyRelationship.link) { - return "link"; - } - - return "ids"; - }; - - HasManyReference.prototype.link = function () { - return this.hasManyRelationship.link; - }; - - HasManyReference.prototype.ids = function () { - var members = this.hasManyRelationship.members; - var ids = members.toArray().map(function (internalModel) { - return internalModel.id; - }); - - return ids; - }; - - HasManyReference.prototype.meta = function () { - return this.hasManyRelationship.manyArray.meta; - }; - - HasManyReference.prototype.push = function (objectOrPromise) { - var _this = this; - - return _ember['default'].RSVP.resolve(objectOrPromise).then(function (payload) { - var array = payload; - if (typeof payload === "object" && payload.data) { - array = payload.data; - } - - var internalModels = array.map(function (obj) { - var record = _this.store.push(obj); - return record._internalModel; - }); - - // TODO add assertion for polymorphic type - - _this.hasManyRelationship.computeChanges(internalModels); - - return _this.hasManyRelationship.manyArray; - }); - }; - - HasManyReference.prototype._isLoaded = function () { - var hasData = get(this.hasManyRelationship, 'hasData'); - if (!hasData) { - return false; - } - - var members = this.hasManyRelationship.members.toArray(); - var isEveryLoaded = members.every(function (internalModel) { - return internalModel.isLoaded() === true; - }); - - return isEveryLoaded; - }; - - HasManyReference.prototype.value = function () { - if (this._isLoaded()) { - return this.hasManyRelationship.manyArray; - } - - return null; - }; - - HasManyReference.prototype.load = function () { - if (!this._isLoaded()) { - return this.hasManyRelationship.getRecords(); - } - - var manyArray = this.hasManyRelationship.manyArray; - return _ember['default'].RSVP.resolve(manyArray); - }; - - HasManyReference.prototype.reload = function () { - return this.hasManyRelationship.reload(); - }; - - exports['default'] = HasManyReference; -}); -define('ember-data/-private/system/references/record', ['exports', 'ember', 'ember-data/-private/system/references/reference'], function (exports, _ember, _emberDataPrivateSystemReferencesReference) { - 'use strict'; - - var RecordReference = function RecordReference(store, internalModel) { - this._super$constructor(store, internalModel); - this.type = internalModel.modelName; - this._id = internalModel.id; - }; - - RecordReference.prototype = Object.create(_emberDataPrivateSystemReferencesReference['default'].prototype); - RecordReference.prototype.constructor = RecordReference; - RecordReference.prototype._super$constructor = _emberDataPrivateSystemReferencesReference['default']; - - RecordReference.prototype.id = function () { - return this._id; - }; - - RecordReference.prototype.remoteType = function () { - return 'identity'; - }; - - RecordReference.prototype.push = function (objectOrPromise) { - var _this = this; - - return _ember['default'].RSVP.resolve(objectOrPromise).then(function (data) { - var record = _this.store.push(data); - return record; - }); - }; - - RecordReference.prototype.value = function () { - return this.internalModel.record; - }; - - RecordReference.prototype.load = function () { - return this.store.findRecord(this.type, this._id); - }; - - RecordReference.prototype.reload = function () { - var record = this.value(); - if (record) { - return record.reload(); - } - - return this.load(); - }; - - exports['default'] = RecordReference; -}); -define("ember-data/-private/system/references/reference", ["exports"], function (exports) { - "use strict"; - - var Reference = function Reference(store, internalModel) { - this.store = store; - this.internalModel = internalModel; - }; - - Reference.prototype = { - constructor: Reference - }; - - exports["default"] = Reference; -}); -define('ember-data/-private/system/references', ['exports', 'ember-data/-private/system/references/record', 'ember-data/-private/system/references/belongs-to', 'ember-data/-private/system/references/has-many'], function (exports, _emberDataPrivateSystemReferencesRecord, _emberDataPrivateSystemReferencesBelongsTo, _emberDataPrivateSystemReferencesHasMany) { - 'use strict'; - - exports.RecordReference = _emberDataPrivateSystemReferencesRecord['default']; - exports.BelongsToReference = _emberDataPrivateSystemReferencesBelongsTo['default']; - exports.HasManyReference = _emberDataPrivateSystemReferencesHasMany['default']; -}); -define('ember-data/-private/system/relationship-meta', ['exports', 'ember-inflector', 'ember-data/-private/system/normalize-model-name'], function (exports, _emberInflector, _emberDataPrivateSystemNormalizeModelName) { - 'use strict'; - - exports.typeForRelationshipMeta = typeForRelationshipMeta; - exports.relationshipFromMeta = relationshipFromMeta; - - function typeForRelationshipMeta(meta) { - var modelName; - - modelName = meta.type || meta.key; - if (meta.kind === 'hasMany') { - modelName = (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName)); - } - return modelName; - } - - function relationshipFromMeta(meta) { - return { - key: meta.key, - kind: meta.kind, - type: typeForRelationshipMeta(meta), - options: meta.options, - parentType: meta.parentType, - isRelationship: true - }; - } -}); -define("ember-data/-private/system/relationships/belongs-to", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/normalize-model-name"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeModelName) { - "use strict"; - - exports["default"] = belongsTo; - - /** - `DS.belongsTo` is used to define One-To-One and One-To-Many - relationships on a [DS.Model](/api/data/classes/DS.Model.html). - - - `DS.belongsTo` takes an optional hash as a second parameter, currently - supported options are: - - - `async`: A boolean value used to explicitly declare this to be an async relationship. - - `inverse`: A string used to identify the inverse property on a - related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) - - #### One-To-One - To declare a one-to-one relationship between two models, use - `DS.belongsTo`: - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - profile: DS.belongsTo('profile') - }); - ``` - - ```app/models/profile.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - user: DS.belongsTo('user') - }); - ``` - - #### One-To-Many - To declare a one-to-many relationship between two models, use - `DS.belongsTo` in combination with `DS.hasMany`, like this: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('comment') - }); - ``` - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - post: DS.belongsTo('post') - }); - ``` - - You can avoid passing a string as the first parameter. In that case Ember Data - will infer the type from the key name. - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - post: DS.belongsTo() - }); - ``` - - will lookup for a Post type. - - @namespace - @method belongsTo - @for DS - @param {String} modelName (optional) type of the relationship - @param {Object} options (optional) a hash of options - @return {Ember.computed} relationship - */ - function belongsTo(modelName, options) { - var opts, userEnteredModelName; - if (typeof modelName === 'object') { - opts = modelName; - userEnteredModelName = undefined; - } else { - opts = options; - userEnteredModelName = modelName; - } - - if (typeof userEnteredModelName === 'string') { - userEnteredModelName = (0, _emberDataPrivateSystemNormalizeModelName["default"])(userEnteredModelName); - } - - (0, _emberDataPrivateDebug.assert)("The first argument to DS.belongsTo must be a string representing a model type key, not an instance of " + _ember["default"].inspect(userEnteredModelName) + ". E.g., to define a relation to the Person model, use DS.belongsTo('person')", typeof userEnteredModelName === 'string' || typeof userEnteredModelName === 'undefined'); - - opts = opts || {}; - - var meta = { - type: userEnteredModelName, - isRelationship: true, - options: opts, - kind: 'belongsTo', - key: null - }; - - return _ember["default"].computed({ - get: function get(key) { - if (opts.hasOwnProperty('serialize')) { - (0, _emberDataPrivateDebug.warn)("You provided a serialize option on the \"" + key + "\" property in the \"" + this._internalModel.modelName + "\" class, this belongs in the serializer. See DS.Serializer and it's implementations http://emberjs.com/api/data/classes/DS.Serializer.html", false, { - id: 'ds.model.serialize-option-in-belongs-to' - }); - } - - if (opts.hasOwnProperty('embedded')) { - (0, _emberDataPrivateDebug.warn)("You provided an embedded option on the \"" + key + "\" property in the \"" + this._internalModel.modelName + "\" class, this belongs in the serializer. See DS.EmbeddedRecordsMixin http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html", false, { - id: 'ds.model.embedded-option-in-belongs-to' - }); - } - - return this._internalModel._relationships.get(key).getRecord(); - }, - set: function set(key, value) { - if (value === undefined) { - value = null; - } - if (value && value.then) { - this._internalModel._relationships.get(key).setRecordPromise(value); - } else if (value) { - this._internalModel._relationships.get(key).setRecord(value._internalModel); - } else { - this._internalModel._relationships.get(key).setRecord(value); - } - - return this._internalModel._relationships.get(key).getRecord(); - } - }).meta(meta); - } - - /* - These observers observe all `belongsTo` relationships on the record. See - `relationships/ext` to see how these observers get their dependencies. - */ - var BelongsToMixin = _ember["default"].Mixin.create({ - notifyBelongsToChanged: function notifyBelongsToChanged(key) { - this.notifyPropertyChange(key); - } - }); - exports.BelongsToMixin = BelongsToMixin; -}); -define("ember-data/-private/system/relationships/ext", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/relationship-meta", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemRelationshipMeta, _emberDataPrivateSystemEmptyObject) { - "use strict"; - - var get = _ember["default"].get; - var Map = _ember["default"].Map; - var MapWithDefault = _ember["default"].MapWithDefault; - - var relationshipsDescriptor = _ember["default"].computed(function () { - if (_ember["default"].testing === true && relationshipsDescriptor._cacheable === true) { - relationshipsDescriptor._cacheable = false; - } - - var map = new MapWithDefault({ - defaultValue: function defaultValue() { - return []; - } - }); - - // Loop through each computed property on the class - this.eachComputedProperty(function (name, meta) { - // If the computed property is a relationship, add - // it to the map. - if (meta.isRelationship) { - meta.key = name; - var relationshipsForType = map.get((0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta)); - - relationshipsForType.push({ - name: name, - kind: meta.kind - }); - } - }); - - return map; - }).readOnly(); - - var relatedTypesDescriptor = _ember["default"].computed(function () { - var _this = this; - - if (_ember["default"].testing === true && relatedTypesDescriptor._cacheable === true) { - relatedTypesDescriptor._cacheable = false; - } - - var modelName; - var types = _ember["default"].A(); - - // Loop through each computed property on the class, - // and create an array of the unique types involved - // in relationships - this.eachComputedProperty(function (name, meta) { - if (meta.isRelationship) { - meta.key = name; - modelName = (0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta); - - (0, _emberDataPrivateDebug.assert)("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", modelName); - - if (!types.contains(modelName)) { - (0, _emberDataPrivateDebug.assert)("Trying to sideload " + name + " on " + _this.toString() + " but the type doesn't exist.", !!modelName); - types.push(modelName); - } - } - }); - - return types; - }).readOnly(); - - var relationshipsByNameDescriptor = _ember["default"].computed(function () { - if (_ember["default"].testing === true && relationshipsByNameDescriptor._cacheable === true) { - relationshipsByNameDescriptor._cacheable = false; - } - - var map = Map.create(); - - this.eachComputedProperty(function (name, meta) { - if (meta.isRelationship) { - meta.key = name; - var relationship = (0, _emberDataPrivateSystemRelationshipMeta.relationshipFromMeta)(meta); - relationship.type = (0, _emberDataPrivateSystemRelationshipMeta.typeForRelationshipMeta)(meta); - map.set(name, relationship); - } - }); - - return map; - }).readOnly(); - - /** - @module ember-data - */ - - /* - This file defines several extensions to the base `DS.Model` class that - add support for one-to-many relationships. - */ - - /** - @class Model - @namespace DS - */ - var DidDefinePropertyMixin = _ember["default"].Mixin.create({ - - /** - This Ember.js hook allows an object to be notified when a property - is defined. - In this case, we use it to be notified when an Ember Data user defines a - belongs-to relationship. In that case, we need to set up observers for - each one, allowing us to track relationship changes and automatically - reflect changes in the inverse has-many array. - This hook passes the class being set up, as well as the key and value - being defined. So, for example, when the user does this: - ```javascript - DS.Model.extend({ - parent: DS.belongsTo('user') - }); - ``` - This hook would be called with "parent" as the key and the computed - property returned by `DS.belongsTo` as the value. - @method didDefineProperty - @param {Object} proto - @param {String} key - @param {Ember.ComputedProperty} value - */ - didDefineProperty: function didDefineProperty(proto, key, value) { - // Check if the value being set is a computed property. - if (value instanceof _ember["default"].ComputedProperty) { - - // If it is, get the metadata for the relationship. This is - // populated by the `DS.belongsTo` helper when it is creating - // the computed property. - var meta = value.meta(); - - meta.parentType = proto.constructor; - } - } - }); - - exports.DidDefinePropertyMixin = DidDefinePropertyMixin; - - /* - These DS.Model extensions add class methods that provide relationship - introspection abilities about relationships. - - A note about the computed properties contained here: - - **These properties are effectively sealed once called for the first time.** - To avoid repeatedly doing expensive iteration over a model's fields, these - values are computed once and then cached for the remainder of the runtime of - your application. - - If your application needs to modify a class after its initial definition - (for example, using `reopen()` to add additional attributes), make sure you - do it before using your model with the store, which uses these properties - extensively. - */ - - var RelationshipsClassMethodsMixin = _ember["default"].Mixin.create({ - - /** - For a given relationship name, returns the model type of the relationship. - For example, if you define a model like this: - ```app/models/post.js - import DS from 'ember-data'; - export default DS.Model.extend({ - comments: DS.hasMany('comment') - }); - ``` - Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. - @method typeForRelationship - @static - @param {String} name the name of the relationship - @param {store} store an instance of DS.Store - @return {DS.Model} the type of the relationship, or undefined - */ - typeForRelationship: function typeForRelationship(name, store) { - var relationship = get(this, 'relationshipsByName').get(name); - return relationship && store.modelFor(relationship.type); - }, - - inverseMap: _ember["default"].computed(function () { - return new _emberDataPrivateSystemEmptyObject["default"](); - }), - - /** - Find the relationship which is the inverse of the one asked for. - For example, if you define models like this: - ```app/models/post.js - import DS from 'ember-data'; - export default DS.Model.extend({ - comments: DS.hasMany('message') - }); - ``` - ```app/models/message.js - import DS from 'ember-data'; - export default DS.Model.extend({ - owner: DS.belongsTo('post') - }); - ``` - App.Post.inverseFor('comments') -> { type: App.Message, name: 'owner', kind: 'belongsTo' } - App.Message.inverseFor('owner') -> { type: App.Post, name: 'comments', kind: 'hasMany' } - @method inverseFor - @static - @param {String} name the name of the relationship - @return {Object} the inverse relationship, or null - */ - inverseFor: function inverseFor(name, store) { - var inverseMap = get(this, 'inverseMap'); - if (inverseMap[name]) { - return inverseMap[name]; - } else { - var inverse = this._findInverseFor(name, store); - inverseMap[name] = inverse; - return inverse; - } - }, - - //Calculate the inverse, ignoring the cache - _findInverseFor: function _findInverseFor(name, store) { - - var inverseType = this.typeForRelationship(name, store); - if (!inverseType) { - return null; - } - - var propertyMeta = this.metaForProperty(name); - //If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })` - var options = propertyMeta.options; - if (options.inverse === null) { - return null; - } - - var inverseName, inverseKind, inverse; - - //If inverse is specified manually, return the inverse - if (options.inverse) { - inverseName = options.inverse; - inverse = _ember["default"].get(inverseType, 'relationshipsByName').get(inverseName); - - (0, _emberDataPrivateDebug.assert)("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.modelName + "' model. This is most likely due to a missing attribute on your model definition.", !_ember["default"].isNone(inverse)); - - inverseKind = inverse.kind; - } else { - //No inverse was specified manually, we need to use a heuristic to guess one - if (propertyMeta.type === propertyMeta.parentType.modelName) { - (0, _emberDataPrivateDebug.warn)("Detected a reflexive relationship by the name of '" + name + "' without an inverse option. Look at http://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.", false, { - id: 'ds.model.reflexive-relationship-without-inverse' - }); - } - - var possibleRelationships = findPossibleInverses(this, inverseType); - - if (possibleRelationships.length === 0) { - return null; - } - - var filteredRelationships = possibleRelationships.filter(function (possibleRelationship) { - var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options; - return name === optionsForRelationship.inverse; - }); - - (0, _emberDataPrivateDebug.assert)("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " + inverseType.toString() + " multiple times. Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", filteredRelationships.length < 2); - - if (filteredRelationships.length === 1) { - possibleRelationships = filteredRelationships; - } - - (0, _emberDataPrivateDebug.assert)("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1); - - inverseName = possibleRelationships[0].name; - inverseKind = possibleRelationships[0].kind; - } - - function findPossibleInverses(type, inverseType, relationshipsSoFar) { - var possibleRelationships = relationshipsSoFar || []; - - var relationshipMap = get(inverseType, 'relationships'); - if (!relationshipMap) { - return possibleRelationships; - } - - var relationships = relationshipMap.get(type.modelName); - - relationships = relationships.filter(function (relationship) { - var optionsForRelationship = inverseType.metaForProperty(relationship.name).options; - - if (!optionsForRelationship.inverse) { - return true; - } - - return name === optionsForRelationship.inverse; - }); - - if (relationships) { - possibleRelationships.push.apply(possibleRelationships, relationships); - } - - //Recurse to support polymorphism - if (type.superclass) { - findPossibleInverses(type.superclass, inverseType, possibleRelationships); - } - - return possibleRelationships; - } - - return { - type: inverseType, - name: inverseName, - kind: inverseKind - }; - }, - - /** - The model's relationships as a map, keyed on the type of the - relationship. The value of each entry is an array containing a descriptor - for each relationship with that type, describing the name of the relationship - as well as the type. - For example, given the following model definition: - ```app/models/blog.js - import DS from 'ember-data'; - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - posts: DS.hasMany('post') - }); - ``` - This computed property would return a map describing these - relationships, like this: - ```javascript - import Ember from 'ember'; - import Blog from 'app/models/blog'; - var relationships = Ember.get(Blog, 'relationships'); - relationships.get(App.User); - //=> [ { name: 'users', kind: 'hasMany' }, - // { name: 'owner', kind: 'belongsTo' } ] - relationships.get(App.Post); - //=> [ { name: 'posts', kind: 'hasMany' } ] - ``` - @property relationships - @static - @type Ember.Map - @readOnly - */ - - relationships: relationshipsDescriptor, - - /** - A hash containing lists of the model's relationships, grouped - by the relationship kind. For example, given a model with this - definition: - ```app/models/blog.js - import DS from 'ember-data'; - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - posts: DS.hasMany('post') - }); - ``` - This property would contain the following: - ```javascript - import Ember from 'ember'; - import Blog from 'app/models/blog'; - var relationshipNames = Ember.get(Blog, 'relationshipNames'); - relationshipNames.hasMany; - //=> ['users', 'posts'] - relationshipNames.belongsTo; - //=> ['owner'] - ``` - @property relationshipNames - @static - @type Object - @readOnly - */ - relationshipNames: _ember["default"].computed(function () { - var names = { - hasMany: [], - belongsTo: [] - }; - - this.eachComputedProperty(function (name, meta) { - if (meta.isRelationship) { - names[meta.kind].push(name); - } - }); - - return names; - }), - - /** - An array of types directly related to a model. Each type will be - included once, regardless of the number of relationships it has with - the model. - For example, given a model with this definition: - ```app/models/blog.js - import DS from 'ember-data'; - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - posts: DS.hasMany('post') - }); - ``` - This property would contain the following: - ```javascript - import Ember from 'ember'; - import Blog from 'app/models/blog'; - var relatedTypes = Ember.get(Blog, 'relatedTypes'); - //=> [ App.User, App.Post ] - ``` - @property relatedTypes - @static - @type Ember.Array - @readOnly - */ - relatedTypes: relatedTypesDescriptor, - - /** - A map whose keys are the relationships of a model and whose values are - relationship descriptors. - For example, given a model with this - definition: - ```app/models/blog.js - import DS from 'ember-data'; - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - posts: DS.hasMany('post') - }); - ``` - This property would contain the following: - ```javascript - import Ember from 'ember'; - import Blog from 'app/models/blog'; - var relationshipsByName = Ember.get(Blog, 'relationshipsByName'); - relationshipsByName.get('users'); - //=> { key: 'users', kind: 'hasMany', type: App.User } - relationshipsByName.get('owner'); - //=> { key: 'owner', kind: 'belongsTo', type: App.User } - ``` - @property relationshipsByName - @static - @type Ember.Map - @readOnly - */ - relationshipsByName: relationshipsByNameDescriptor, - - /** - A map whose keys are the fields of the model and whose values are strings - describing the kind of the field. A model's fields are the union of all of its - attributes and relationships. - For example: - ```app/models/blog.js - import DS from 'ember-data'; - export default DS.Model.extend({ - users: DS.hasMany('user'), - owner: DS.belongsTo('user'), - posts: DS.hasMany('post'), - title: DS.attr('string') - }); - ``` - ```js - import Ember from 'ember'; - import Blog from 'app/models/blog'; - var fields = Ember.get(Blog, 'fields'); - fields.forEach(function(kind, field) { - console.log(field, kind); - }); - // prints: - // users, hasMany - // owner, belongsTo - // posts, hasMany - // title, attribute - ``` - @property fields - @static - @type Ember.Map - @readOnly - */ - fields: _ember["default"].computed(function () { - var map = Map.create(); - - this.eachComputedProperty(function (name, meta) { - if (meta.isRelationship) { - map.set(name, meta.kind); - } else if (meta.isAttribute) { - map.set(name, 'attribute'); - } - }); - - return map; - }).readOnly(), - - /** - Given a callback, iterates over each of the relationships in the model, - invoking the callback with the name of each relationship and its relationship - descriptor. - @method eachRelationship - @static - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelationship: function eachRelationship(callback, binding) { - get(this, 'relationshipsByName').forEach(function (relationship, name) { - callback.call(binding, name, relationship); - }); - }, - - /** - Given a callback, iterates over each of the types related to a model, - invoking the callback with the related type's class. Each type will be - returned just once, regardless of how many different relationships it has - with a model. - @method eachRelatedType - @static - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelatedType: function eachRelatedType(callback, binding) { - var relationshipTypes = get(this, 'relatedTypes'); - - for (var i = 0; i < relationshipTypes.length; i++) { - var type = relationshipTypes[i]; - callback.call(binding, type); - } - }, - - determineRelationshipType: function determineRelationshipType(knownSide, store) { - var knownKey = knownSide.key; - var knownKind = knownSide.kind; - var inverse = this.inverseFor(knownKey, store); - var key = undefined, - otherKind = undefined; - - if (!inverse) { - return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone'; - } - - key = inverse.name; - otherKind = inverse.kind; - - if (otherKind === 'belongsTo') { - return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne'; - } else { - return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany'; - } - } - - }); - - exports.RelationshipsClassMethodsMixin = RelationshipsClassMethodsMixin; - - var RelationshipsInstanceMethodsMixin = _ember["default"].Mixin.create({ - /** - Given a callback, iterates over each of the relationships in the model, - invoking the callback with the name of each relationship and its relationship - descriptor. - The callback method you provide should have the following signature (all - parameters are optional): - ```javascript - function(name, descriptor); - ``` - - `name` the name of the current property in the iteration - - `descriptor` the meta object that describes this relationship - The relationship descriptor argument is an object with the following properties. - - **key** String the name of this relationship on the Model - - **kind** String "hasMany" or "belongsTo" - - **options** Object the original options hash passed when the relationship was declared - - **parentType** DS.Model the type of the Model that owns this relationship - - **type** DS.Model the type of the related Model - Note that in addition to a callback, you can also pass an optional target - object that will be set as `this` on the context. - Example - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - serialize: function(record, options) { - var json = {}; - record.eachRelationship(function(name, descriptor) { - if (descriptor.kind === 'hasMany') { - var serializedHasManyName = name.toUpperCase() + '_IDS'; - json[serializedHasManyName] = record.get(name).mapBy('id'); - } - }); - return json; - } - }); - ``` - @method eachRelationship - @param {Function} callback the callback to invoke - @param {any} binding the value to which the callback's `this` should be bound - */ - eachRelationship: function eachRelationship(callback, binding) { - this.constructor.eachRelationship(callback, binding); - }, - - relationshipFor: function relationshipFor(name) { - return get(this.constructor, 'relationshipsByName').get(name); - }, - - inverseFor: function inverseFor(key) { - return this.constructor.inverseFor(key, this.store); - } - - }); - exports.RelationshipsInstanceMethodsMixin = RelationshipsInstanceMethodsMixin; -}); -define("ember-data/-private/system/relationships/has-many", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/is-array-like"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemIsArrayLike) { - "use strict"; - - exports["default"] = hasMany; - - /** - @module ember-data - */ - - /** - `DS.hasMany` is used to define One-To-Many and Many-To-Many - relationships on a [DS.Model](/api/data/classes/DS.Model.html). - - `DS.hasMany` takes an optional hash as a second parameter, currently - supported options are: - - - `async`: A boolean value used to explicitly declare this to be an async relationship. - - `inverse`: A string used to identify the inverse property on a related model. - - #### One-To-Many - To declare a one-to-many relationship between two models, use - `DS.belongsTo` in combination with `DS.hasMany`, like this: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('comment') - }); - ``` - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - post: DS.belongsTo('post') - }); - ``` - - #### Many-To-Many - To declare a many-to-many relationship between two models, use - `DS.hasMany`: - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - tags: DS.hasMany('tag') - }); - ``` - - ```app/models/tag.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - posts: DS.hasMany('post') - }); - ``` - - You can avoid passing a string as the first parameter. In that case Ember Data - will infer the type from the singularized key name. - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - tags: DS.hasMany() - }); - ``` - - will lookup for a Tag type. - - #### Explicit Inverses - - Ember Data will do its best to discover which relationships map to - one another. In the one-to-many code above, for example, Ember Data - can figure out that changing the `comments` relationship should update - the `post` relationship on the inverse because post is the only - relationship to that model. - - However, sometimes you may have multiple `belongsTo`/`hasManys` for the - same type. You can specify which property on the related model is - the inverse using `DS.hasMany`'s `inverse` option: - - ```app/models/comment.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - onePost: DS.belongsTo('post'), - twoPost: DS.belongsTo('post'), - redPost: DS.belongsTo('post'), - bluePost: DS.belongsTo('post') - }); - ``` - - ```app/models/post.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - comments: DS.hasMany('comment', { - inverse: 'redPost' - }) - }); - ``` - - You can also specify an inverse on a `belongsTo`, which works how - you'd expect. - - @namespace - @method hasMany - @for DS - @param {String} type (optional) type of the relationship - @param {Object} options (optional) a hash of options - @return {Ember.computed} relationship - */ - function hasMany(type, options) { - if (typeof type === 'object') { - options = type; - type = undefined; - } - - (0, _emberDataPrivateDebug.assert)("The first argument to DS.hasMany must be a string representing a model type key, not an instance of " + _ember["default"].inspect(type) + ". E.g., to define a relation to the Comment model, use DS.hasMany('comment')", typeof type === 'string' || typeof type === 'undefined'); - - options = options || {}; - - if (typeof type === 'string') { - type = (0, _emberDataPrivateSystemNormalizeModelName["default"])(type); - } - - // Metadata about relationships is stored on the meta of - // the relationship. This is used for introspection and - // serialization. Note that `key` is populated lazily - // the first time the CP is called. - var meta = { - type: type, - isRelationship: true, - options: options, - kind: 'hasMany', - key: null - }; - - return _ember["default"].computed({ - get: function get(key) { - var relationship = this._internalModel._relationships.get(key); - return relationship.getRecords(); - }, - set: function set(key, records) { - (0, _emberDataPrivateDebug.assert)("You must pass an array of records to set a hasMany relationship", (0, _emberDataPrivateSystemIsArrayLike["default"])(records)); - (0, _emberDataPrivateDebug.assert)("All elements of a hasMany relationship must be instances of DS.Model, you passed " + _ember["default"].inspect(records), (function () { - return _ember["default"].A(records).every(function (record) { - return record.hasOwnProperty('_internalModel') === true; - }); - })()); - - var relationship = this._internalModel._relationships.get(key); - relationship.clear(); - relationship.addRecords(_ember["default"].A(records).mapBy('_internalModel')); - return relationship.getRecords(); - } - }).meta(meta); - } - - var HasManyMixin = _ember["default"].Mixin.create({ - notifyHasManyAdded: function notifyHasManyAdded(key) { - //We need to notifyPropertyChange in the adding case because we need to make sure - //we fetch the newly added record in case it is unloaded - //TODO(Igor): Consider whether we could do this only if the record state is unloaded - - //Goes away once hasMany is double promisified - this.notifyPropertyChange(key); - } - }); - exports.HasManyMixin = HasManyMixin; -}); -define("ember-data/-private/system/relationships/state/belongs-to", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/utils", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateUtils, _emberDataPrivateSystemRelationshipsStateRelationship) { - "use strict"; - - exports["default"] = BelongsToRelationship; - - function BelongsToRelationship(store, record, inverseKey, relationshipMeta) { - this._super$constructor(store, record, inverseKey, relationshipMeta); - this.record = record; - this.key = relationshipMeta.key; - this.inverseRecord = null; - this.canonicalState = null; - } - - BelongsToRelationship.prototype = Object.create(_emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype); - BelongsToRelationship.prototype.constructor = BelongsToRelationship; - BelongsToRelationship.prototype._super$constructor = _emberDataPrivateSystemRelationshipsStateRelationship["default"]; - - BelongsToRelationship.prototype.setRecord = function (newRecord) { - if (newRecord) { - this.addRecord(newRecord); - } else if (this.inverseRecord) { - this.removeRecord(this.inverseRecord); - } - this.setHasData(true); - this.setHasLoaded(true); - }; - - BelongsToRelationship.prototype.setCanonicalRecord = function (newRecord) { - if (newRecord) { - this.addCanonicalRecord(newRecord); - } else if (this.inverseRecord) { - this.removeCanonicalRecord(this.inverseRecord); - } - this.setHasData(true); - this.setHasLoaded(true); - }; - - BelongsToRelationship.prototype._super$addCanonicalRecord = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.addCanonicalRecord; - BelongsToRelationship.prototype.addCanonicalRecord = function (newRecord) { - if (this.canonicalMembers.has(newRecord)) { - return; - } - - if (this.canonicalState) { - this.removeCanonicalRecord(this.canonicalState); - } - - this.canonicalState = newRecord; - this._super$addCanonicalRecord(newRecord); - }; - - BelongsToRelationship.prototype._super$flushCanonical = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.flushCanonical; - BelongsToRelationship.prototype.flushCanonical = function () { - //temporary fix to not remove newly created records if server returned null. - //TODO remove once we have proper diffing - if (this.inverseRecord && this.inverseRecord.isNew() && !this.canonicalState) { - return; - } - this.inverseRecord = this.canonicalState; - this.record.notifyBelongsToChanged(this.key); - this._super$flushCanonical(); - }; - - BelongsToRelationship.prototype._super$addRecord = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.addRecord; - BelongsToRelationship.prototype.addRecord = function (newRecord) { - if (this.members.has(newRecord)) { - return; - } - - (0, _emberDataPrivateUtils.assertPolymorphicType)(this.record, this.relationshipMeta, newRecord); - - if (this.inverseRecord) { - this.removeRecord(this.inverseRecord); - } - - this.inverseRecord = newRecord; - this._super$addRecord(newRecord); - this.record.notifyBelongsToChanged(this.key); - }; - - BelongsToRelationship.prototype.setRecordPromise = function (newPromise) { - var content = newPromise.get && newPromise.get('content'); - (0, _emberDataPrivateDebug.assert)("You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call.", content !== undefined); - this.setRecord(content ? content._internalModel : content); - }; - - BelongsToRelationship.prototype._super$removeRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.removeRecordFromOwn; - BelongsToRelationship.prototype.removeRecordFromOwn = function (record) { - if (!this.members.has(record)) { - return; - } - this.inverseRecord = null; - this._super$removeRecordFromOwn(record); - this.record.notifyBelongsToChanged(this.key); - }; - - BelongsToRelationship.prototype._super$removeCanonicalRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.removeCanonicalRecordFromOwn; - BelongsToRelationship.prototype.removeCanonicalRecordFromOwn = function (record) { - if (!this.canonicalMembers.has(record)) { - return; - } - this.canonicalState = null; - this._super$removeCanonicalRecordFromOwn(record); - }; - - BelongsToRelationship.prototype.findRecord = function () { - if (this.inverseRecord) { - return this.store._findByInternalModel(this.inverseRecord); - } else { - return _ember["default"].RSVP.Promise.resolve(null); - } - }; - - BelongsToRelationship.prototype.fetchLink = function () { - var _this = this; - - return this.store.findBelongsTo(this.record, this.link, this.relationshipMeta).then(function (record) { - if (record) { - _this.addRecord(record); - } - return record; - }); - }; - - BelongsToRelationship.prototype.getRecord = function () { - var _this2 = this; - - //TODO(Igor) flushCanonical here once our syncing is not stupid - if (this.isAsync) { - var promise; - if (this.link) { - if (this.hasLoaded) { - promise = this.findRecord(); - } else { - promise = this.findLink().then(function () { - return _this2.findRecord(); - }); - } - } else { - promise = this.findRecord(); - } - - return _emberDataPrivateSystemPromiseProxies.PromiseObject.create({ - promise: promise, - content: this.inverseRecord ? this.inverseRecord.getRecord() : null - }); - } else { - if (this.inverseRecord === null) { - return null; - } - var toReturn = this.inverseRecord.getRecord(); - (0, _emberDataPrivateDebug.assert)("You looked up the '" + this.key + "' relationship on a '" + this.record.type.modelName + "' with id " + this.record.id + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)", toReturn === null || !toReturn.get('isEmpty')); - return toReturn; - } - }; - - BelongsToRelationship.prototype.reload = function () { - // TODO handle case when reload() is triggered multiple times - - if (this.link) { - return this.fetchLink(); - } - - // reload record, if it is already loaded - if (this.inverseRecord && this.inverseRecord.record) { - return this.inverseRecord.record.reload(); - } - - return this.findRecord(); - }; -}); -define("ember-data/-private/system/relationships/state/create", ["exports", "ember", "ember-data/-private/system/relationships/state/has-many", "ember-data/-private/system/relationships/state/belongs-to", "ember-data/-private/system/empty-object"], function (exports, _ember, _emberDataPrivateSystemRelationshipsStateHasMany, _emberDataPrivateSystemRelationshipsStateBelongsTo, _emberDataPrivateSystemEmptyObject) { - "use strict"; - - exports["default"] = Relationships; - - var get = _ember["default"].get; - - function createRelationshipFor(record, relationshipMeta, store) { - var inverseKey; - var inverse = record.type.inverseFor(relationshipMeta.key, store); - - if (inverse) { - inverseKey = inverse.name; - } - - if (relationshipMeta.kind === 'hasMany') { - return new _emberDataPrivateSystemRelationshipsStateHasMany["default"](store, record, inverseKey, relationshipMeta); - } else { - return new _emberDataPrivateSystemRelationshipsStateBelongsTo["default"](store, record, inverseKey, relationshipMeta); - } - } - function Relationships(record) { - this.record = record; - this.initializedRelationships = new _emberDataPrivateSystemEmptyObject["default"](); - } - - Relationships.prototype.has = function (key) { - return !!this.initializedRelationships[key]; - }; - - Relationships.prototype.get = function (key) { - var relationships = this.initializedRelationships; - var relationshipsByName = get(this.record.type, 'relationshipsByName'); - if (!relationships[key] && relationshipsByName.get(key)) { - relationships[key] = createRelationshipFor(this.record, relationshipsByName.get(key), this.record.store); - } - return relationships[key]; - }; -}); -define("ember-data/-private/system/relationships/state/has-many", ["exports", "ember-data/-private/debug", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/relationships/state/relationship", "ember-data/-private/system/ordered-set", "ember-data/-private/system/many-array", "ember-data/-private/utils"], function (exports, _emberDataPrivateDebug, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemRelationshipsStateRelationship, _emberDataPrivateSystemOrderedSet, _emberDataPrivateSystemManyArray, _emberDataPrivateUtils) { - "use strict"; - - exports["default"] = ManyRelationship; - - function ManyRelationship(store, record, inverseKey, relationshipMeta) { - this._super$constructor(store, record, inverseKey, relationshipMeta); - this.belongsToType = relationshipMeta.type; - this.canonicalState = []; - this.manyArray = _emberDataPrivateSystemManyArray["default"].create({ - canonicalState: this.canonicalState, - store: this.store, - relationship: this, - type: this.store.modelFor(this.belongsToType), - record: record - }); - this.isPolymorphic = relationshipMeta.options.polymorphic; - this.manyArray.isPolymorphic = this.isPolymorphic; - } - - ManyRelationship.prototype = Object.create(_emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype); - ManyRelationship.prototype.constructor = ManyRelationship; - ManyRelationship.prototype._super$constructor = _emberDataPrivateSystemRelationshipsStateRelationship["default"]; - - ManyRelationship.prototype.destroy = function () { - this.manyArray.destroy(); - }; - - ManyRelationship.prototype._super$updateMeta = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.updateMeta; - ManyRelationship.prototype.updateMeta = function (meta) { - this._super$updateMeta(meta); - this.manyArray.set('meta', meta); - }; - - ManyRelationship.prototype._super$addCanonicalRecord = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.addCanonicalRecord; - ManyRelationship.prototype.addCanonicalRecord = function (record, idx) { - if (this.canonicalMembers.has(record)) { - return; - } - if (idx !== undefined) { - this.canonicalState.splice(idx, 0, record); - } else { - this.canonicalState.push(record); - } - this._super$addCanonicalRecord(record, idx); - }; - - ManyRelationship.prototype._super$addRecord = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.addRecord; - ManyRelationship.prototype.addRecord = function (record, idx) { - if (this.members.has(record)) { - return; - } - this._super$addRecord(record, idx); - this.manyArray.internalAddRecords([record], idx); - }; - - ManyRelationship.prototype._super$removeCanonicalRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.removeCanonicalRecordFromOwn; - ManyRelationship.prototype.removeCanonicalRecordFromOwn = function (record, idx) { - var i = idx; - if (!this.canonicalMembers.has(record)) { - return; - } - if (i === undefined) { - i = this.canonicalState.indexOf(record); - } - if (i > -1) { - this.canonicalState.splice(i, 1); - } - this._super$removeCanonicalRecordFromOwn(record, idx); - }; - - ManyRelationship.prototype._super$flushCanonical = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.flushCanonical; - ManyRelationship.prototype.flushCanonical = function () { - this.manyArray.flushCanonical(); - this._super$flushCanonical(); - }; - - ManyRelationship.prototype._super$removeRecordFromOwn = _emberDataPrivateSystemRelationshipsStateRelationship["default"].prototype.removeRecordFromOwn; - ManyRelationship.prototype.removeRecordFromOwn = function (record, idx) { - if (!this.members.has(record)) { - return; - } - this._super$removeRecordFromOwn(record, idx); - if (idx !== undefined) { - //TODO(Igor) not used currently, fix - this.manyArray.currentState.removeAt(idx); - } else { - this.manyArray.internalRemoveRecords([record]); - } - }; - - ManyRelationship.prototype.notifyRecordRelationshipAdded = function (record, idx) { - (0, _emberDataPrivateUtils.assertPolymorphicType)(this.record, this.relationshipMeta, record); - - this.record.notifyHasManyAdded(this.key, record, idx); - }; - - ManyRelationship.prototype.reload = function () { - var self = this; - var manyArrayLoadedState = this.manyArray.get('isLoaded'); - - if (this._loadingPromise) { - if (this._loadingPromise.get('isPending')) { - return this._loadingPromise; - } - if (this._loadingPromise.get('isRejected')) { - this.manyArray.set('isLoaded', manyArrayLoadedState); - } - } - - if (this.link) { - return this.fetchLink(); - } else { - return this.store.scheduleFetchMany(this.manyArray.toArray()).then(function () { - //Goes away after the manyArray refactor - self.manyArray.set('isLoaded', true); - return self.manyArray; - }); - } - }; - - ManyRelationship.prototype.computeChanges = function (records) { - var members = this.canonicalMembers; - var recordsToRemove = []; - var length; - var record; - var i; - - records = setForArray(records); - - members.forEach(function (member) { - if (records.has(member)) { - return; - } - - recordsToRemove.push(member); - }); - - this.removeCanonicalRecords(recordsToRemove); - - // Using records.toArray() since currently using - // removeRecord can modify length, messing stuff up - // forEach since it directly looks at "length" each - // iteration - records = records.toArray(); - length = records.length; - for (i = 0; i < length; i++) { - record = records[i]; - this.removeCanonicalRecord(record); - this.addCanonicalRecord(record, i); - } - }; - - ManyRelationship.prototype.fetchLink = function () { - var _this = this; - - return this.store.findHasMany(this.record, this.link, this.relationshipMeta).then(function (records) { - if (records.hasOwnProperty('meta')) { - _this.updateMeta(records.meta); - } - _this.store._backburner.join(function () { - _this.updateRecordsFromAdapter(records); - _this.manyArray.set('isLoaded', true); - }); - return _this.manyArray; - }); - }; - - ManyRelationship.prototype.findRecords = function () { - var _this2 = this; - - var manyArray = this.manyArray.toArray(); - var internalModels = new Array(manyArray.length); - - for (var i = 0; i < manyArray.length; i++) { - internalModels[i] = manyArray[i]._internalModel; - } - - //TODO CLEANUP - return this.store.findMany(internalModels).then(function () { - if (!_this2.manyArray.get('isDestroyed')) { - //Goes away after the manyArray refactor - _this2.manyArray.set('isLoaded', true); - } - return _this2.manyArray; - }); - }; - ManyRelationship.prototype.notifyHasManyChanged = function () { - this.record.notifyHasManyAdded(this.key); - }; - - ManyRelationship.prototype.getRecords = function () { - var _this3 = this; - - //TODO(Igor) sync server here, once our syncing is not stupid - if (this.isAsync) { - var promise; - if (this.link) { - if (this.hasLoaded) { - promise = this.findRecords(); - } else { - promise = this.findLink().then(function () { - return _this3.findRecords(); - }); - } - } else { - promise = this.findRecords(); - } - this._loadingPromise = _emberDataPrivateSystemPromiseProxies.PromiseManyArray.create({ - content: this.manyArray, - promise: promise - }); - return this._loadingPromise; - } else { - (0, _emberDataPrivateDebug.assert)("You looked up the '" + this.key + "' relationship on a '" + this.record.type.modelName + "' with id " + this.record.id + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", this.manyArray.isEvery('isEmpty', false)); - - //TODO(Igor) WTF DO I DO HERE? - if (!this.manyArray.get('isDestroyed')) { - this.manyArray.set('isLoaded', true); - } - return this.manyArray; - } - }; - - function setForArray(array) { - var set = new _emberDataPrivateSystemOrderedSet["default"](); - - if (array) { - for (var i = 0, l = array.length; i < l; i++) { - set.add(array[i]); - } - } - - return set; - } -}); -define("ember-data/-private/system/relationships/state/relationship", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/ordered-set"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemOrderedSet) { - "use strict"; - - exports["default"] = Relationship; - - function Relationship(store, record, inverseKey, relationshipMeta) { - var async = relationshipMeta.options.async; - this.members = new _emberDataPrivateSystemOrderedSet["default"](); - this.canonicalMembers = new _emberDataPrivateSystemOrderedSet["default"](); - this.store = store; - this.key = relationshipMeta.key; - this.inverseKey = inverseKey; - this.record = record; - this.isAsync = typeof async === 'undefined' ? true : async; - this.relationshipMeta = relationshipMeta; - //This probably breaks for polymorphic relationship in complex scenarios, due to - //multiple possible modelNames - this.inverseKeyForImplicit = this.record.constructor.modelName + this.key; - this.linkPromise = null; - this.meta = null; - this.hasData = false; - this.hasLoaded = false; - } - - Relationship.prototype = { - constructor: Relationship, - - destroy: _ember["default"].K, - - updateMeta: function updateMeta(meta) { - this.meta = meta; - }, - - clear: function clear() { - var members = this.members.list; - var member; - - while (members.length > 0) { - member = members[0]; - this.removeRecord(member); - } - }, - - removeRecords: function removeRecords(records) { - var _this = this; - - records.forEach(function (record) { - return _this.removeRecord(record); - }); - }, - - addRecords: function addRecords(records, idx) { - var _this2 = this; - - records.forEach(function (record) { - _this2.addRecord(record, idx); - if (idx !== undefined) { - idx++; - } - }); - }, - - addCanonicalRecords: function addCanonicalRecords(records, idx) { - for (var i = 0; i < records.length; i++) { - if (idx !== undefined) { - this.addCanonicalRecord(records[i], i + idx); - } else { - this.addCanonicalRecord(records[i]); - } - } - }, - - addCanonicalRecord: function addCanonicalRecord(record, idx) { - if (!this.canonicalMembers.has(record)) { - this.canonicalMembers.add(record); - if (this.inverseKey) { - record._relationships.get(this.inverseKey).addCanonicalRecord(this.record); - } else { - if (!record._implicitRelationships[this.inverseKeyForImplicit]) { - record._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, record, this.key, { options: {} }); - } - record._implicitRelationships[this.inverseKeyForImplicit].addCanonicalRecord(this.record); - } - } - this.flushCanonicalLater(); - this.setHasData(true); - }, - - removeCanonicalRecords: function removeCanonicalRecords(records, idx) { - for (var i = 0; i < records.length; i++) { - if (idx !== undefined) { - this.removeCanonicalRecord(records[i], i + idx); - } else { - this.removeCanonicalRecord(records[i]); - } - } - }, - - removeCanonicalRecord: function removeCanonicalRecord(record, idx) { - if (this.canonicalMembers.has(record)) { - this.removeCanonicalRecordFromOwn(record); - if (this.inverseKey) { - this.removeCanonicalRecordFromInverse(record); - } else { - if (record._implicitRelationships[this.inverseKeyForImplicit]) { - record._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalRecord(this.record); - } - } - } - this.flushCanonicalLater(); - }, - - addRecord: function addRecord(record, idx) { - if (!this.members.has(record)) { - this.members.addWithIndex(record, idx); - this.notifyRecordRelationshipAdded(record, idx); - if (this.inverseKey) { - record._relationships.get(this.inverseKey).addRecord(this.record); - } else { - if (!record._implicitRelationships[this.inverseKeyForImplicit]) { - record._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, record, this.key, { options: {} }); - } - record._implicitRelationships[this.inverseKeyForImplicit].addRecord(this.record); - } - this.record.updateRecordArraysLater(); - } - this.setHasData(true); - }, - - removeRecord: function removeRecord(record) { - if (this.members.has(record)) { - this.removeRecordFromOwn(record); - if (this.inverseKey) { - this.removeRecordFromInverse(record); - } else { - if (record._implicitRelationships[this.inverseKeyForImplicit]) { - record._implicitRelationships[this.inverseKeyForImplicit].removeRecord(this.record); - } - } - } - }, - - removeRecordFromInverse: function removeRecordFromInverse(record) { - var inverseRelationship = record._relationships.get(this.inverseKey); - //Need to check for existence, as the record might unloading at the moment - if (inverseRelationship) { - inverseRelationship.removeRecordFromOwn(this.record); - } - }, - - removeRecordFromOwn: function removeRecordFromOwn(record) { - this.members["delete"](record); - this.notifyRecordRelationshipRemoved(record); - this.record.updateRecordArrays(); - }, - - removeCanonicalRecordFromInverse: function removeCanonicalRecordFromInverse(record) { - var inverseRelationship = record._relationships.get(this.inverseKey); - //Need to check for existence, as the record might unloading at the moment - if (inverseRelationship) { - inverseRelationship.removeCanonicalRecordFromOwn(this.record); - } - }, - - removeCanonicalRecordFromOwn: function removeCanonicalRecordFromOwn(record) { - this.canonicalMembers["delete"](record); - this.flushCanonicalLater(); - }, - - flushCanonical: function flushCanonical() { - this.willSync = false; - //a hack for not removing new records - //TODO remove once we have proper diffing - var newRecords = []; - for (var i = 0; i < this.members.list.length; i++) { - if (this.members.list[i].isNew()) { - newRecords.push(this.members.list[i]); - } - } - //TODO(Igor) make this less abysmally slow - this.members = this.canonicalMembers.copy(); - for (i = 0; i < newRecords.length; i++) { - this.members.add(newRecords[i]); - } - }, - - flushCanonicalLater: function flushCanonicalLater() { - var _this3 = this; - - if (this.willSync) { - return; - } - this.willSync = true; - this.store._backburner.join(function () { - return _this3.store._backburner.schedule('syncRelationships', _this3, _this3.flushCanonical); - }); - }, - - updateLink: function updateLink(link) { - (0, _emberDataPrivateDebug.warn)("You have pushed a record of type '" + this.record.type.modelName + "' with '" + this.key + "' as a link, but the association is not an async relationship.", this.isAsync, { - id: 'ds.store.push-link-for-sync-relationship' - }); - (0, _emberDataPrivateDebug.assert)("You have pushed a record of type '" + this.record.type.modelName + "' with '" + this.key + "' as a link, but the value of that link is not a string.", typeof link === 'string' || link === null); - if (link !== this.link) { - this.link = link; - this.linkPromise = null; - this.setHasLoaded(false); - this.record.notifyPropertyChange(this.key); - } - }, - - findLink: function findLink() { - if (this.linkPromise) { - return this.linkPromise; - } else { - var promise = this.fetchLink(); - this.linkPromise = promise; - return promise.then(function (result) { - return result; - }); - } - }, - - updateRecordsFromAdapter: function updateRecordsFromAdapter(records) { - //TODO(Igor) move this to a proper place - //TODO Once we have adapter support, we need to handle updated and canonical changes - this.computeChanges(records); - this.setHasData(true); - this.setHasLoaded(true); - }, - - notifyRecordRelationshipAdded: _ember["default"].K, - notifyRecordRelationshipRemoved: _ember["default"].K, - - /* - `hasData` for a relationship is a flag to indicate if we consider the - content of this relationship "known". Snapshots uses this to tell the - difference between unknown (`undefined`) or empty (`null`). The reason for - this is that we wouldn't want to serialize unknown relationships as `null` - as that might overwrite remote state. - All relationships for a newly created (`store.createRecord()`) are - considered known (`hasData === true`). - */ - setHasData: function setHasData(value) { - this.hasData = value; - }, - - /* - `hasLoaded` is a flag to indicate if we have gotten data from the adapter or - not when the relationship has a link. - This is used to be able to tell when to fetch the link and when to return - the local data in scenarios where the local state is considered known - (`hasData === true`). - Updating the link will automatically set `hasLoaded` to `false`. - */ - setHasLoaded: function setHasLoaded(value) { - this.hasLoaded = value; - } - }; -}); -define('ember-data/-private/system/snapshot-record-array', ['exports', 'ember-data/-private/features'], function (exports, _emberDataPrivateFeatures) { - 'use strict'; - - exports['default'] = SnapshotRecordArray; - - /** - @module ember-data - */ - - /** - @class SnapshotRecordArray - @namespace DS - @private - @constructor - @param {Array} snapshots An array of snapshots - @param {Object} meta - */ - function SnapshotRecordArray(recordArray, meta) { - var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; - - /** - An array of snapshots - @private - @property _snapshots - @type {Array} - */ - this._snapshots = null; - /** - An array of records - @private - @property _recordArray - @type {Array} - */ - this._recordArray = recordArray; - /** - Number of records in the array - @property length - @type {Number} - */ - this.length = recordArray.get('length'); - /** - The type of the underlying records for the snapshots in the array, as a DS.Model - @property type - @type {DS.Model} - */ - this.type = recordArray.get('type'); - /** - Meta object - @property meta - @type {Object} - */ - this.meta = meta; - /** - A hash of adapter options - @property adapterOptions - @type {Object} - */ - this.adapterOptions = options.adapterOptions; - - if ((0, _emberDataPrivateFeatures['default'])('ds-finder-include')) { - this.include = options.include; - } - } - - /** - Get snapshots of the underlying record array - @method snapshots - @return {Array} Array of snapshots - */ - SnapshotRecordArray.prototype.snapshots = function () { - if (this._snapshots) { - return this._snapshots; - } - var recordArray = this._recordArray; - this._snapshots = recordArray.invoke('createSnapshot'); - - return this._snapshots; - }; -}); -define('ember-data/-private/system/snapshot', ['exports', 'ember', 'ember-data/-private/system/empty-object', 'ember-data/-private/features'], function (exports, _ember, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures) { - 'use strict'; - - exports['default'] = Snapshot; - - /** - @module ember-data - */ - - var get = _ember['default'].get; - - /** - @class Snapshot - @namespace DS - @private - @constructor - @param {DS.Model} internalModel The model to create a snapshot from - */ - function Snapshot(internalModel) { - var _this = this; - - var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; - - this._attributes = new _emberDataPrivateSystemEmptyObject['default'](); - this._belongsToRelationships = new _emberDataPrivateSystemEmptyObject['default'](); - this._belongsToIds = new _emberDataPrivateSystemEmptyObject['default'](); - this._hasManyRelationships = new _emberDataPrivateSystemEmptyObject['default'](); - this._hasManyIds = new _emberDataPrivateSystemEmptyObject['default'](); - - var record = internalModel.getRecord(); - this.record = record; - record.eachAttribute(function (keyName) { - return _this._attributes[keyName] = get(record, keyName); - }); - - this.id = internalModel.id; - this._internalModel = internalModel; - this.type = internalModel.type; - this.modelName = internalModel.type.modelName; - - /** - A hash of adapter options - @property adapterOptions - @type {Object} - */ - this.adapterOptions = options.adapterOptions; - - if ((0, _emberDataPrivateFeatures['default'])('ds-finder-include')) { - this.include = options.include; - } - - this._changedAttributes = record.changedAttributes(); - } - - Snapshot.prototype = { - constructor: Snapshot, - - /** - The id of the snapshot's underlying record - Example - ```javascript - // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); - postSnapshot.id; // => '1' - ``` - @property id - @type {String} - */ - id: null, - - /** - The underlying record for this snapshot. Can be used to access methods and - properties defined on the record. - Example - ```javascript - var json = snapshot.record.toJSON(); - ``` - @property record - @type {DS.Model} - */ - record: null, - - /** - The type of the underlying record for this snapshot, as a DS.Model. - @property type - @type {DS.Model} - */ - type: null, - - /** - The name of the type of the underlying record for this snapshot, as a string. - @property modelName - @type {String} - */ - modelName: null, - - /** - Returns the value of an attribute. - Example - ```javascript - // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); - postSnapshot.attr('author'); // => 'Tomster' - postSnapshot.attr('title'); // => 'Ember.js rocks' - ``` - Note: Values are loaded eagerly and cached when the snapshot is created. - @method attr - @param {String} keyName - @return {Object} The attribute value or undefined - */ - attr: function attr(keyName) { - if (keyName in this._attributes) { - return this._attributes[keyName]; - } - throw new _ember['default'].Error("Model '" + _ember['default'].inspect(this.record) + "' has no attribute named '" + keyName + "' defined."); - }, - - /** - Returns all attributes and their corresponding values. - Example - ```javascript - // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); - postSnapshot.attributes(); // => { author: 'Tomster', title: 'Ember.js rocks' } - ``` - @method attributes - @return {Object} All attributes of the current snapshot - */ - attributes: function attributes() { - return _ember['default'].copy(this._attributes); - }, - - /** - Returns all changed attributes and their old and new values. - Example - ```javascript - // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); - postModel.set('title', 'Ember.js rocks!'); - postSnapshot.changedAttributes(); // => { title: ['Ember.js rocks', 'Ember.js rocks!'] } - ``` - @method changedAttributes - @return {Object} All changed attributes of the current snapshot - */ - changedAttributes: function changedAttributes() { - var changedAttributes = new _emberDataPrivateSystemEmptyObject['default'](); - var changedAttributeKeys = Object.keys(this._changedAttributes); - - for (var i = 0, _length = changedAttributeKeys.length; i < _length; i++) { - var key = changedAttributeKeys[i]; - changedAttributes[key] = _ember['default'].copy(this._changedAttributes[key]); - } - - return changedAttributes; - }, - - /** - Returns the current value of a belongsTo relationship. - `belongsTo` takes an optional hash of options as a second parameter, - currently supported options are: - - `id`: set to `true` if you only want the ID of the related record to be - returned. - Example - ```javascript - // store.push('post', { id: 1, title: 'Hello World' }); - // store.createRecord('comment', { body: 'Lorem ipsum', post: post }); - commentSnapshot.belongsTo('post'); // => DS.Snapshot - commentSnapshot.belongsTo('post', { id: true }); // => '1' - // store.push('comment', { id: 1, body: 'Lorem ipsum' }); - commentSnapshot.belongsTo('post'); // => undefined - ``` - Calling `belongsTo` will return a new Snapshot as long as there's any known - data for the relationship available, such as an ID. If the relationship is - known but unset, `belongsTo` will return `null`. If the contents of the - relationship is unknown `belongsTo` will return `undefined`. - Note: Relationships are loaded lazily and cached upon first access. - @method belongsTo - @param {String} keyName - @param {Object} [options] - @return {(DS.Snapshot|String|null|undefined)} A snapshot or ID of a known - relationship or null if the relationship is known but unset. undefined - will be returned if the contents of the relationship is unknown. - */ - belongsTo: function belongsTo(keyName, options) { - var id = options && options.id; - var relationship, inverseRecord, hasData; - var result; - - if (id && keyName in this._belongsToIds) { - return this._belongsToIds[keyName]; - } - - if (!id && keyName in this._belongsToRelationships) { - return this._belongsToRelationships[keyName]; - } - - relationship = this._internalModel._relationships.get(keyName); - if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) { - throw new _ember['default'].Error("Model '" + _ember['default'].inspect(this.record) + "' has no belongsTo relationship named '" + keyName + "' defined."); - } - - hasData = get(relationship, 'hasData'); - inverseRecord = get(relationship, 'inverseRecord'); - - if (hasData) { - if (inverseRecord && !inverseRecord.isDeleted()) { - if (id) { - result = get(inverseRecord, 'id'); - } else { - result = inverseRecord.createSnapshot(); - } - } else { - result = null; - } - } - - if (id) { - this._belongsToIds[keyName] = result; - } else { - this._belongsToRelationships[keyName] = result; - } - - return result; - }, - - /** - Returns the current value of a hasMany relationship. - `hasMany` takes an optional hash of options as a second parameter, - currently supported options are: - - `ids`: set to `true` if you only want the IDs of the related records to be - returned. - Example - ```javascript - // store.push('post', { id: 1, title: 'Hello World', comments: [2, 3] }); - postSnapshot.hasMany('comments'); // => [DS.Snapshot, DS.Snapshot] - postSnapshot.hasMany('comments', { ids: true }); // => ['2', '3'] - // store.push('post', { id: 1, title: 'Hello World' }); - postSnapshot.hasMany('comments'); // => undefined - ``` - Note: Relationships are loaded lazily and cached upon first access. - @method hasMany - @param {String} keyName - @param {Object} [options] - @return {(Array|undefined)} An array of snapshots or IDs of a known - relationship or an empty array if the relationship is known but unset. - undefined will be returned if the contents of the relationship is unknown. - */ - hasMany: function hasMany(keyName, options) { - var ids = options && options.ids; - var relationship, members, hasData; - var results; - - if (ids && keyName in this._hasManyIds) { - return this._hasManyIds[keyName]; - } - - if (!ids && keyName in this._hasManyRelationships) { - return this._hasManyRelationships[keyName]; - } - - relationship = this._internalModel._relationships.get(keyName); - if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) { - throw new _ember['default'].Error("Model '" + _ember['default'].inspect(this.record) + "' has no hasMany relationship named '" + keyName + "' defined."); - } - - hasData = get(relationship, 'hasData'); - members = get(relationship, 'members'); - - if (hasData) { - results = []; - members.forEach(function (member) { - if (!member.isDeleted()) { - if (ids) { - results.push(member.id); - } else { - results.push(member.createSnapshot()); - } - } - }); - } - - if (ids) { - this._hasManyIds[keyName] = results; - } else { - this._hasManyRelationships[keyName] = results; - } - - return results; - }, - - /** - Iterates through all the attributes of the model, calling the passed - function on each attribute. - Example - ```javascript - snapshot.eachAttribute(function(name, meta) { - // ... - }); - ``` - @method eachAttribute - @param {Function} callback the callback to execute - @param {Object} [binding] the value to which the callback's `this` should be bound - */ - eachAttribute: function eachAttribute(callback, binding) { - this.record.eachAttribute(callback, binding); - }, - - /** - Iterates through all the relationships of the model, calling the passed - function on each relationship. - Example - ```javascript - snapshot.eachRelationship(function(name, relationship) { - // ... - }); - ``` - @method eachRelationship - @param {Function} callback the callback to execute - @param {Object} [binding] the value to which the callback's `this` should be bound - */ - eachRelationship: function eachRelationship(callback, binding) { - this.record.eachRelationship(callback, binding); - }, - - /** - @method serialize - @param {Object} options - @return {Object} an object whose values are primitive JSON values only - */ - serialize: function serialize(options) { - return this.record.store.serializerFor(this.modelName).serialize(this, options); - } - }; -}); -define('ember-data/-private/system/store/common', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports._bind = _bind; - exports._guard = _guard; - exports._objectIsAlive = _objectIsAlive; - - var get = _ember['default'].get; - - function _bind(fn) { - var args = Array.prototype.slice.call(arguments, 1); - - return function () { - return fn.apply(undefined, args); - }; - } - - function _guard(promise, test) { - var guarded = promise['finally'](function () { - if (!test()) { - guarded._subscribers.length = 0; - } - }); - - return guarded; - } - - function _objectIsAlive(object) { - return !(get(object, "isDestroyed") || get(object, "isDestroying")); - } -}); -define('ember-data/-private/system/store/container-instance-cache', ['exports', 'ember', 'ember-data/-private/system/empty-object'], function (exports, _ember, _emberDataPrivateSystemEmptyObject) { - 'use strict'; - - exports['default'] = ContainerInstanceCache; - - /** - * The `ContainerInstanceCache` serves as a lazy cache for looking up - * instances of serializers and adapters. It has some additional logic for - * finding the 'fallback' adapter or serializer. - * - * The 'fallback' adapter or serializer is an adapter or serializer that is looked up - * when the preferred lookup fails. For example, say you try to look up `adapter:post`, - * but there is no entry (app/adapters/post.js in EmberCLI) for `adapter:post` in the registry. - * - * The `fallbacks` array passed will then be used; the first entry in the fallbacks array - * that exists in the container will then be cached for `adapter:post`. So, the next time you - * look up `adapter:post`, you'll get the `adapter:application` instance (or whatever the fallback - * was if `adapter:application` doesn't exist). - * - * @private - * @class ContainerInstanceCache - * - */ - function ContainerInstanceCache(owner) { - this._owner = owner; - this._cache = new _emberDataPrivateSystemEmptyObject['default'](); - } - - ContainerInstanceCache.prototype = new _emberDataPrivateSystemEmptyObject['default'](); - - _ember['default'].merge(ContainerInstanceCache.prototype, { - get: function get(type, preferredKey, fallbacks) { - var cache = this._cache; - var preferredLookupKey = type + ':' + preferredKey; - - if (!(preferredLookupKey in cache)) { - var instance = this.instanceFor(preferredLookupKey) || this._findInstance(type, fallbacks); - if (instance) { - cache[preferredLookupKey] = instance; - } - } - return cache[preferredLookupKey]; - }, - - _findInstance: function _findInstance(type, fallbacks) { - for (var i = 0, _length = fallbacks.length; i < _length; i++) { - var fallback = fallbacks[i]; - var lookupKey = type + ':' + fallback; - var instance = this.instanceFor(lookupKey); - - if (instance) { - return instance; - } - } - }, - - instanceFor: function instanceFor(key) { - var cache = this._cache; - if (!cache[key]) { - var instance = this._owner.lookup(key); - if (instance) { - cache[key] = instance; - } - } - return cache[key]; - }, - - destroy: function destroy() { - var cache = this._cache; - var cacheEntries = Object.keys(cache); - - for (var i = 0, _length2 = cacheEntries.length; i < _length2; i++) { - var cacheKey = cacheEntries[i]; - var cacheEntry = cache[cacheKey]; - if (cacheEntry) { - cacheEntry.destroy(); - } - } - this._owner = null; - }, - - constructor: ContainerInstanceCache, - - toString: function toString() { - return 'ContainerInstanceCache'; - } - }); -}); -define("ember-data/-private/system/store/finders", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/system/store/common", "ember-data/-private/system/store/serializer-response", "ember-data/-private/system/store/serializers"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateSystemStoreCommon, _emberDataPrivateSystemStoreSerializerResponse, _emberDataPrivateSystemStoreSerializers) { - "use strict"; - - exports._find = _find; - exports._findMany = _findMany; - exports._findHasMany = _findHasMany; - exports._findBelongsTo = _findBelongsTo; - exports._findAll = _findAll; - exports._query = _query; - exports._queryRecord = _queryRecord; - - var Promise = _ember["default"].RSVP.Promise; - - function payloadIsNotBlank(adapterPayload) { - if (_ember["default"].isArray(adapterPayload)) { - return true; - } else { - return Object.keys(adapterPayload || {}).length; - } - } - - function _find(adapter, store, typeClass, id, internalModel, options) { - var snapshot = internalModel.createSnapshot(options); - var promise = adapter.findRecord(store, typeClass, id, snapshot); - var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, internalModel.type.modelName); - var label = "DS: Handle Adapter#findRecord of " + typeClass + " with id: " + id; - - promise = Promise.resolve(promise, label); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); - - return promise.then(function (adapterPayload) { - (0, _emberDataPrivateDebug.assert)("You made a `findRecord` request for a " + typeClass.typeClassKey + " with id " + id + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); - return store._adapterRun(function () { - var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, id, 'findRecord'); - (0, _emberDataPrivateDebug.assert)('Ember Data expected the primary data returned from a `findRecord` response to be an object but instead it found an array.', !Array.isArray(payload.data)); - //TODO Optimize - var record = store.push(payload); - return record._internalModel; - }); - }, function (error) { - internalModel.notFound(); - if (internalModel.isEmpty()) { - internalModel.unloadRecord(); - } - - throw error; - }, "DS: Extract payload of '" + typeClass + "'"); - } - - function _findMany(adapter, store, typeClass, ids, internalModels) { - var snapshots = _ember["default"].A(internalModels).invoke('createSnapshot'); - var promise = adapter.findMany(store, typeClass, ids, snapshots); - var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, typeClass.modelName); - var label = "DS: Handle Adapter#findMany of " + typeClass; - - if (promise === undefined) { - throw new Error('adapter.findMany returned undefined, this was very likely a mistake'); - } - - promise = Promise.resolve(promise, label); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); - - return promise.then(function (adapterPayload) { - (0, _emberDataPrivateDebug.assert)("You made a `findMany` request for a " + typeClass.typeClassKey + " with ids " + ids + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); - return store._adapterRun(function () { - var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findMany'); - //TODO Optimize, no need to materialize here - var records = store.push(payload); - var internalModels = new Array(records.length); - - for (var i = 0; i < records.length; i++) { - internalModels[i] = records[i]._internalModel; - } - - return internalModels; - }); - }, null, "DS: Extract payload of " + typeClass); - } - - function _findHasMany(adapter, store, internalModel, link, relationship) { - var snapshot = internalModel.createSnapshot(); - var typeClass = store.modelFor(relationship.type); - var promise = adapter.findHasMany(store, snapshot, link, relationship); - var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, relationship.type); - var label = "DS: Handle Adapter#findHasMany of " + internalModel + " : " + relationship.type; - - promise = Promise.resolve(promise, label); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); - - return promise.then(function (adapterPayload) { - (0, _emberDataPrivateDebug.assert)("You made a `findHasMany` request for a " + internalModel.modelName + "'s `" + relationship.key + "` relationship, using link " + link + ", but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); - return store._adapterRun(function () { - var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findHasMany'); - //TODO Use a non record creating push - var records = store.push(payload); - var recordArray = records.map(function (record) { - return record._internalModel; - }); - recordArray.meta = payload.meta; - return recordArray; - }); - }, null, "DS: Extract payload of " + internalModel + " : hasMany " + relationship.type); - } - - function _findBelongsTo(adapter, store, internalModel, link, relationship) { - var snapshot = internalModel.createSnapshot(); - var typeClass = store.modelFor(relationship.type); - var promise = adapter.findBelongsTo(store, snapshot, link, relationship); - var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, relationship.type); - var label = "DS: Handle Adapter#findBelongsTo of " + internalModel + " : " + relationship.type; - - promise = Promise.resolve(promise, label); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); - - return promise.then(function (adapterPayload) { - return store._adapterRun(function () { - var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findBelongsTo'); - - if (!payload.data) { - return null; - } - - //TODO Optimize - var record = store.push(payload); - return record._internalModel; - }); - }, null, "DS: Extract payload of " + internalModel + " : " + relationship.type); - } - - function _findAll(adapter, store, typeClass, sinceToken, options) { - var modelName = typeClass.modelName; - var recordArray = store.peekAll(modelName); - var snapshotArray = recordArray.createSnapshot(options); - var promise = adapter.findAll(store, typeClass, sinceToken, snapshotArray); - var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); - var label = "DS: Handle Adapter#findAll of " + typeClass; - - promise = Promise.resolve(promise, label); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); - - return promise.then(function (adapterPayload) { - (0, _emberDataPrivateDebug.assert)("You made a `findAll` request for " + typeClass.typeClassKey + "records, but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); - store._adapterRun(function () { - var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'findAll'); - //TODO Optimize - store.push(payload); - }); - - store.didUpdateAll(typeClass); - return store.peekAll(modelName); - }, null, "DS: Extract payload of findAll " + typeClass); - } - - function _query(adapter, store, typeClass, query, recordArray) { - var modelName = typeClass.modelName; - var promise = adapter.query(store, typeClass, query, recordArray); - - var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); - var label = "DS: Handle Adapter#query of " + typeClass; - - promise = Promise.resolve(promise, label); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); - - return promise.then(function (adapterPayload) { - var records, payload; - store._adapterRun(function () { - payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'query'); - //TODO Optimize - records = store.push(payload); - }); - - (0, _emberDataPrivateDebug.assert)('The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use `store.queryRecord` to query for a single record.', _ember["default"].isArray(records)); - recordArray.loadRecords(records, payload); - return recordArray; - }, null, "DS: Extract payload of query " + typeClass); - } - - function _queryRecord(adapter, store, typeClass, query) { - var modelName = typeClass.modelName; - var promise = adapter.queryRecord(store, typeClass, query); - var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); - var label = "DS: Handle Adapter#queryRecord of " + typeClass; - - promise = Promise.resolve(promise, label); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); - - return promise.then(function (adapterPayload) { - (0, _emberDataPrivateDebug.assert)("You made a `queryRecord` request for " + typeClass.typeClassKey + "records, with query `" + query + "`, but the adapter's response did not have any data", payloadIsNotBlank(adapterPayload)); - var record; - store._adapterRun(function () { - var payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, null, 'queryRecord'); - _ember["default"].assert('`store.queryRecord` expected the adapter to return one record but the response from the adapter was empty.', payload.data); - //TODO Optimize - record = store.push(payload); - }); - - return record; - }, null, "DS: Extract payload of queryRecord " + typeClass); - } -}); -define('ember-data/-private/system/store/serializer-response', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { - 'use strict'; - - exports.validateDocumentStructure = validateDocumentStructure; - exports.normalizeResponseHelper = normalizeResponseHelper; - - /* - This is a helper method that validates a JSON API top-level document - - The format of a document is described here: - http://jsonapi.org/format/#document-top-level - - @method validateDocumentStructure - @param {Object} doc JSON API document - @return {array} An array of errors found in the document structure - */ - - function validateDocumentStructure(doc) { - var errors = []; - if (!doc || typeof doc !== 'object') { - errors.push('Top level of a JSON API document must be an object'); - } else { - if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) { - errors.push('One or more of the following keys must be present: "data", "errors", "meta".'); - } else { - if ('data' in doc && 'errors' in doc) { - errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document'); - } - } - if ('data' in doc) { - if (!(doc.data === null || _ember['default'].isArray(doc.data) || typeof doc.data === 'object')) { - errors.push('data must be null, an object, or an array'); - } - } - if ('meta' in doc) { - if (typeof doc.meta !== 'object') { - errors.push('meta must be an object'); - } - } - if ('errors' in doc) { - if (!_ember['default'].isArray(doc.errors)) { - errors.push('errors must be an array'); - } - } - if ('links' in doc) { - if (typeof doc.links !== 'object') { - errors.push('links must be an object'); - } - } - if ('jsonapi' in doc) { - if (typeof doc.jsonapi !== 'object') { - errors.push('jsonapi must be an object'); - } - } - if ('included' in doc) { - if (typeof doc.included !== 'object') { - errors.push('included must be an array'); - } - } - } - - return errors; - } - - /* - This is a helper method that always returns a JSON-API Document. - - @method normalizeResponseHelper - @param {DS.Serializer} serializer - @param {DS.Store} store - @param {subclass of DS.Model} modelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - - function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) { - var normalizedResponse = serializer.normalizeResponse(store, modelClass, payload, id, requestType); - var validationErrors = []; - (0, _emberDataPrivateDebug.runInDebug)(function () { - validationErrors = validateDocumentStructure(normalizedResponse); - }); - (0, _emberDataPrivateDebug.assert)('normalizeResponse must return a valid JSON API document:\n\t* ' + validationErrors.join('\n\t* '), _ember['default'].isEmpty(validationErrors)); - - return normalizedResponse; - } -}); -define("ember-data/-private/system/store/serializers", ["exports"], function (exports) { - "use strict"; - - exports.serializerForAdapter = serializerForAdapter; - - function serializerForAdapter(store, adapter, type) { - var serializer = adapter.serializer; - - if (serializer === undefined) { - serializer = store.serializerFor(type); - } - - if (serializer === null || serializer === undefined) { - serializer = { - extract: function extract(store, type, payload) { - return payload; - } - }; - } - - return serializer; - } -}); -define('ember-data/-private/system/store', ['exports', 'ember', 'ember-data/model', 'ember-data/-private/debug', 'ember-data/-private/system/normalize-link', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/adapters/errors', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/store/common', 'ember-data/-private/system/store/serializer-response', 'ember-data/-private/system/store/serializers', 'ember-data/-private/system/store/finders', 'ember-data/-private/utils', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/record-array-manager', 'ember-data/-private/system/store/container-instance-cache', 'ember-data/-private/system/model/internal-model', 'ember-data/-private/system/empty-object', 'ember-data/-private/features'], function (exports, _ember, _emberDataModel, _emberDataPrivateDebug, _emberDataPrivateSystemNormalizeLink, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateAdaptersErrors, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStoreCommon, _emberDataPrivateSystemStoreSerializerResponse, _emberDataPrivateSystemStoreSerializers, _emberDataPrivateSystemStoreFinders, _emberDataPrivateUtils, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateSystemStoreContainerInstanceCache, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemEmptyObject, _emberDataPrivateFeatures) { - /** - @module ember-data - */ - - 'use strict'; - - var badIdFormatAssertion = '`id` has to be non-empty string or number'; - - exports.badIdFormatAssertion = badIdFormatAssertion; - - var Backburner = _ember['default']._Backburner || _ember['default'].Backburner || _ember['default'].__loader.require('backburner')['default'] || _ember['default'].__loader.require('backburner')['Backburner']; - var Map = _ember['default'].Map; - var isArray = Array.isArray || _ember['default'].isArray; - - //Shim Backburner.join - if (!Backburner.prototype.join) { - var isString = function isString(suspect) { - return typeof suspect === 'string'; - }; - - Backburner.prototype.join = function () /*target, method, args */{ - var method, target; - - if (this.currentInstance) { - var length = arguments.length; - if (length === 1) { - method = arguments[0]; - target = null; - } else { - target = arguments[0]; - method = arguments[1]; - } - - if (isString(method)) { - method = target[method]; - } - - if (length === 1) { - return method(); - } else if (length === 2) { - return method.call(target); - } else { - var args = new Array(length - 2); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i + 2]; - } - return method.apply(target, args); - } - } else { - return this.run.apply(this, arguments); - } - }; - } - - //Get the materialized model from the internalModel/promise that returns - //an internal model and return it in a promiseObject. Useful for returning - //from find methods - function promiseRecord(internalModel, label) { - var toReturn = internalModel.then(function (model) { - return model.getRecord(); - }); - return (0, _emberDataPrivateSystemPromiseProxies.promiseObject)(toReturn, label); - } - - var get = _ember['default'].get; - var set = _ember['default'].set; - var once = _ember['default'].run.once; - var isNone = _ember['default'].isNone; - var Promise = _ember['default'].RSVP.Promise; - var copy = _ember['default'].copy; - var Store; - - var Service = _ember['default'].Service; - if (!Service) { - Service = _ember['default'].Object; - } - - // Implementors Note: - // - // The variables in this file are consistently named according to the following - // scheme: - // - // * +id+ means an identifier managed by an external source, provided inside - // the data provided by that source. These are always coerced to be strings - // before being used internally. - // * +clientId+ means a transient numerical identifier generated at runtime by - // the data store. It is important primarily because newly created objects may - // not yet have an externally generated id. - // * +internalModel+ means a record internalModel object, which holds metadata about a - // record, even if it has not yet been fully materialized. - // * +type+ means a DS.Model. - - /** - The store contains all of the data for records loaded from the server. - It is also responsible for creating instances of `DS.Model` that wrap - the individual data for a record, so that they can be bound to in your - Handlebars templates. - - Define your application's store like this: - - ```app/services/store.js - import DS from 'ember-data'; - - export default DS.Store.extend({ - }); - ``` - - Most Ember.js applications will only have a single `DS.Store` that is - automatically created by their `Ember.Application`. - - You can retrieve models from the store in several ways. To retrieve a record - for a specific id, use `DS.Store`'s `findRecord()` method: - - ```javascript - store.findRecord('person', 123).then(function (person) { - }); - ``` - - By default, the store will talk to your backend using a standard - REST mechanism. You can customize how the store talks to your - backend by specifying a custom adapter: - - ```app/adapters/application.js - import DS from 'ember-data'; - - export default DS.Adapter.extend({ - }); - ``` - - You can learn more about writing a custom adapter by reading the `DS.Adapter` - documentation. - - ### Store createRecord() vs. push() vs. pushPayload() - - The store provides multiple ways to create new record objects. They have - some subtle differences in their use which are detailed below: - - [createRecord](#method_createRecord) is used for creating new - records on the client side. This will return a new record in the - `created.uncommitted` state. In order to persist this record to the - backend you will need to call `record.save()`. - - [push](#method_push) is used to notify Ember Data's store of new or - updated records that exist in the backend. This will return a record - in the `loaded.saved` state. The primary use-case for `store#push` is - to notify Ember Data about record updates (full or partial) that happen - outside of the normal adapter methods (for example - [SSE](http://dev.w3.org/html5/eventsource/) or [Web - Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). - - [pushPayload](#method_pushPayload) is a convenience wrapper for - `store#push` that will deserialize payloads if the - Serializer implements a `pushPayload` method. - - Note: When creating a new record using any of the above methods - Ember Data will update `DS.RecordArray`s such as those returned by - `store#peekAll()`, `store#findAll()` or `store#filter()`. This means any - data bindings or computed properties that depend on the RecordArray - will automatically be synced to include the new or updated record - values. - - @class Store - @namespace DS - @extends Ember.Service - */ - exports.Store = Store = Service.extend({ - - /** - @method init - @private - */ - init: function init() { - this._super.apply(this, arguments); - this._backburner = new Backburner(['normalizeRelationships', 'syncRelationships', 'finished']); - // internal bookkeeping; not observable - this.typeMaps = {}; - this.recordArrayManager = _emberDataPrivateSystemRecordArrayManager['default'].create({ - store: this - }); - this._pendingSave = []; - this._instanceCache = new _emberDataPrivateSystemStoreContainerInstanceCache['default']((0, _emberDataPrivateUtils.getOwner)(this)); - //Used to keep track of all the find requests that need to be coalesced - this._pendingFetch = Map.create(); - }, - - /** - The adapter to use to communicate to a backend server or other persistence layer. - This can be specified as an instance, class, or string. - If you want to specify `app/adapters/custom.js` as a string, do: - ```js - adapter: 'custom' - ``` - @property adapter - @default DS.JSONAPIAdapter - @type {(DS.Adapter|String)} - */ - adapter: '-json-api', - - /** - Returns a JSON representation of the record using a custom - type-specific serializer, if one exists. - The available options are: - * `includeId`: `true` if the record's ID should be included in - the JSON representation - @method serialize - @private - @param {DS.Model} record the record to serialize - @param {Object} options an options hash - */ - serialize: function serialize(record, options) { - var snapshot = record._internalModel.createSnapshot(); - return snapshot.serialize(options); - }, - - /** - This property returns the adapter, after resolving a possible - string key. - If the supplied `adapter` was a class, or a String property - path resolved to a class, this property will instantiate the - class. - This property is cacheable, so the same instance of a specified - adapter class should be used for the lifetime of the store. - @property defaultAdapter - @private - @return DS.Adapter - */ - defaultAdapter: _ember['default'].computed('adapter', function () { - var adapter = get(this, 'adapter'); - - (0, _emberDataPrivateDebug.assert)('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name', typeof adapter === 'string'); - - adapter = this.retrieveManagedInstance('adapter', adapter); - - return adapter; - }), - - // ..................... - // . CREATE NEW RECORD . - // ..................... - - /** - Create a new record in the current store. The properties passed - to this method are set on the newly created record. - To create a new instance of a `Post`: - ```js - store.createRecord('post', { - title: "Rails is omakase" - }); - ``` - To create a new instance of a `Post` that has a relationship with a `User` record: - ```js - var user = this.store.peekRecord('user', 1); - store.createRecord('post', { - title: "Rails is omakase", - user: user - }); - ``` - @method createRecord - @param {String} modelName - @param {Object} inputProperties a hash of properties to set on the - newly created record. - @return {DS.Model} record - */ - createRecord: function createRecord(modelName, inputProperties) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - var typeClass = this.modelFor(modelName); - var properties = copy(inputProperties) || new _emberDataPrivateSystemEmptyObject['default'](); - - // If the passed properties do not include a primary key, - // give the adapter an opportunity to generate one. Typically, - // client-side ID generators will use something like uuid.js - // to avoid conflicts. - - if (isNone(properties.id)) { - properties.id = this._generateId(modelName, properties); - } - - // Coerce ID to a string - properties.id = (0, _emberDataPrivateSystemCoerceId['default'])(properties.id); - - var internalModel = this.buildInternalModel(typeClass, properties.id); - var record = internalModel.getRecord(); - - // Move the record out of its initial `empty` state into - // the `loaded` state. - internalModel.loadedData(); - - // Set the properties specified on the record. - record.setProperties(properties); - - internalModel.eachRelationship(function (key, descriptor) { - internalModel._relationships.get(key).setHasData(true); - }); - - return record; - }, - - /** - If possible, this method asks the adapter to generate an ID for - a newly created record. - @method _generateId - @private - @param {String} modelName - @param {Object} properties from the new record - @return {String} if the adapter can generate one, an ID - */ - _generateId: function _generateId(modelName, properties) { - var adapter = this.adapterFor(modelName); - - if (adapter && adapter.generateIdForRecord) { - return adapter.generateIdForRecord(this, modelName, properties); - } - - return null; - }, - - // ................. - // . DELETE RECORD . - // ................. - - /** - For symmetry, a record can be deleted via the store. - Example - ```javascript - var post = store.createRecord('post', { - title: "Rails is omakase" - }); - store.deleteRecord(post); - ``` - @method deleteRecord - @param {DS.Model} record - */ - deleteRecord: function deleteRecord(record) { - record.deleteRecord(); - }, - - /** - For symmetry, a record can be unloaded via the store. Only - non-dirty records can be unloaded. - Example - ```javascript - store.findRecord('post', 1).then(function(post) { - store.unloadRecord(post); - }); - ``` - @method unloadRecord - @param {DS.Model} record - */ - unloadRecord: function unloadRecord(record) { - record.unloadRecord(); - }, - - // ................ - // . FIND RECORDS . - // ................ - - /** - @method find - @param {String} modelName - @param {String|Integer} id - @param {Object} options - @return {Promise} promise - @private - */ - find: function find(modelName, id, options) { - // The default `model` hook in Ember.Route calls `find(modelName, id)`, - // that's why we have to keep this method around even though `findRecord` is - // the public way to get a record by modelName and id. - - if (arguments.length === 1) { - (0, _emberDataPrivateDebug.assert)('Using store.find(type) has been removed. Use store.findAll(type) to retrieve all records for a given type.'); - } - - if (_ember['default'].typeOf(id) === 'object') { - (0, _emberDataPrivateDebug.assert)('Calling store.find() with a query object is no longer supported. Use store.query() instead.'); - } - - if (options) { - (0, _emberDataPrivateDebug.assert)('Calling store.find(type, id, { preload: preload }) is no longer supported. Use store.findRecord(type, id, { preload: preload }) instead.'); - } - - (0, _emberDataPrivateDebug.assert)("You need to pass the model name and id to the store's find method", arguments.length === 2); - (0, _emberDataPrivateDebug.assert)("You cannot pass `" + _ember['default'].inspect(id) + "` as id to the store's find method", _ember['default'].typeOf(id) === 'string' || _ember['default'].typeOf(id) === 'number'); - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - - return this.findRecord(modelName, id); - }, - - /** - This method returns a record for a given type and id combination. - The `findRecord` method will always return a **promise** that will be - resolved with the record. If the record was already in the store, - the promise will be resolved immediately. Otherwise, the store - will ask the adapter's `find` method to find the necessary data. - The `findRecord` method will always resolve its promise with the same - object for a given type and `id`. - Example - ```app/routes/post.js - import Ember from 'ember'; - export default Ember.Route.extend({ - model: function(params) { - return this.store.findRecord('post', params.post_id); - } - }); - ``` - If you would like to force the record to reload, instead of - loading it from the cache when present you can set `reload: true` - in the options object for `findRecord`. - ```app/routes/post/edit.js - import Ember from 'ember'; - export default Ember.Route.extend({ - model: function(params) { - return this.store.findRecord('post', params.post_id, { reload: true }); - } - }); - ``` - @method findRecord - @param {String} modelName - @param {(String|Integer)} id - @param {Object} options - @return {Promise} promise - */ - findRecord: function findRecord(modelName, id, options) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - (0, _emberDataPrivateDebug.assert)(badIdFormatAssertion, typeof id === 'string' && id.length > 0 || typeof id === 'number' && !isNaN(id)); - - var internalModel = this._internalModelForId(modelName, id); - options = options || {}; - - if (!this.hasRecordForId(modelName, id)) { - return this._findByInternalModel(internalModel, options); - } - - var fetchedInternalModel = this._findRecord(internalModel, options); - - return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); - }, - - _findRecord: function _findRecord(internalModel, options) { - // Refetch if the reload option is passed - if (options.reload) { - return this.scheduleFetch(internalModel, options); - } - - // Refetch the record if the adapter thinks the record is stale - var snapshot = internalModel.createSnapshot(options); - var typeClass = internalModel.type; - var adapter = this.adapterFor(typeClass.modelName); - if (adapter.shouldReloadRecord(this, snapshot)) { - return this.scheduleFetch(internalModel, options); - } - - // Trigger the background refetch if all the previous checks fail - if (adapter.shouldBackgroundReloadRecord(this, snapshot)) { - this.scheduleFetch(internalModel, options); - } - - // Return the cached record - return Promise.resolve(internalModel); - }, - - _findByInternalModel: function _findByInternalModel(internalModel, options) { - options = options || {}; - - if (options.preload) { - internalModel._preloadData(options.preload); - } - - var fetchedInternalModel = this._findEmptyInternalModel(internalModel, options); - - return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); - }, - - _findEmptyInternalModel: function _findEmptyInternalModel(internalModel, options) { - if (internalModel.isEmpty()) { - return this.scheduleFetch(internalModel, options); - } - - //TODO double check about reloading - if (internalModel.isLoading()) { - return internalModel._loadingPromise; - } - - return Promise.resolve(internalModel); - }, - - /** - This method makes a series of requests to the adapter's `find` method - and returns a promise that resolves once they are all loaded. - @private - @method findByIds - @param {String} modelName - @param {Array} ids - @return {Promise} promise - */ - findByIds: function findByIds(modelName, ids) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - var promises = new Array(ids.length); - - for (var i = 0; i < ids.length; i++) { - promises[i] = this.findRecord(modelName, ids[i]); - } - - return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(_ember['default'].RSVP.all(promises).then(_ember['default'].A, null, "DS: Store#findByIds of " + modelName + " complete")); - }, - - /** - This method is called by `findRecord` if it discovers that a particular - type/id pair hasn't been loaded yet to kick off a request to the - adapter. - @method fetchRecord - @private - @param {InternalModel} internalModel model - @return {Promise} promise - */ - // TODO rename this to have an underscore - fetchRecord: function fetchRecord(internalModel, options) { - var typeClass = internalModel.type; - var id = internalModel.id; - var adapter = this.adapterFor(typeClass.modelName); - - (0, _emberDataPrivateDebug.assert)("You tried to find a record but you have no adapter (for " + typeClass + ")", adapter); - (0, _emberDataPrivateDebug.assert)("You tried to find a record but your adapter (for " + typeClass + ") does not implement 'findRecord'", typeof adapter.findRecord === 'function' || typeof adapter.find === 'function'); - - var promise = (0, _emberDataPrivateSystemStoreFinders._find)(adapter, this, typeClass, id, internalModel, options); - return promise; - }, - - scheduleFetchMany: function scheduleFetchMany(records) { - var internalModels = new Array(records.length); - var fetches = new Array(records.length); - for (var i = 0; i < records.length; i++) { - internalModels[i] = records[i]._internalModel; - } - - for (var i = 0; i < internalModels.length; i++) { - fetches[i] = this.scheduleFetch(internalModels[i]); - } - - return _ember['default'].RSVP.Promise.all(fetches); - }, - - scheduleFetch: function scheduleFetch(internalModel, options) { - var typeClass = internalModel.type; - - if (internalModel._loadingPromise) { - return internalModel._loadingPromise; - } - - var resolver = _ember['default'].RSVP.defer('Fetching ' + typeClass + 'with id: ' + internalModel.id); - var pendingFetchItem = { - record: internalModel, - resolver: resolver, - options: options - }; - var promise = resolver.promise; - - internalModel.loadingData(promise); - - if (!this._pendingFetch.get(typeClass)) { - this._pendingFetch.set(typeClass, [pendingFetchItem]); - } else { - this._pendingFetch.get(typeClass).push(pendingFetchItem); - } - _ember['default'].run.scheduleOnce('afterRender', this, this.flushAllPendingFetches); - - return promise; - }, - - flushAllPendingFetches: function flushAllPendingFetches() { - if (this.isDestroyed || this.isDestroying) { - return; - } - - this._pendingFetch.forEach(this._flushPendingFetchForType, this); - this._pendingFetch = Map.create(); - }, - - _flushPendingFetchForType: function _flushPendingFetchForType(pendingFetchItems, typeClass) { - var store = this; - var adapter = store.adapterFor(typeClass.modelName); - var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; - var records = _ember['default'].A(pendingFetchItems).mapBy('record'); - - function _fetchRecord(recordResolverPair) { - recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record, recordResolverPair.options)); // TODO adapter options - } - - function resolveFoundRecords(records) { - records.forEach(function (record) { - var pair = _ember['default'].A(pendingFetchItems).findBy('record', record); - if (pair) { - var resolver = pair.resolver; - resolver.resolve(record); - } - }); - return records; - } - - function makeMissingRecordsRejector(requestedRecords) { - return function rejectMissingRecords(resolvedRecords) { - resolvedRecords = _ember['default'].A(resolvedRecords); - var missingRecords = requestedRecords.reject(function (record) { - return resolvedRecords.contains(record); - }); - if (missingRecords.length) { - (0, _emberDataPrivateDebug.warn)('Ember Data expected to find records with the following ids in the adapter response but they were missing: ' + _ember['default'].inspect(_ember['default'].A(missingRecords).mapBy('id')), false, { - id: 'ds.store.missing-records-from-adapter' - }); - } - rejectRecords(missingRecords); - }; - } - - function makeRecordsRejector(records) { - return function (error) { - rejectRecords(records, error); - }; - } - - function rejectRecords(records, error) { - records.forEach(function (record) { - var pair = _ember['default'].A(pendingFetchItems).findBy('record', record); - if (pair) { - var resolver = pair.resolver; - resolver.reject(error); - } - }); - } - - if (pendingFetchItems.length === 1) { - _fetchRecord(pendingFetchItems[0]); - } else if (shouldCoalesce) { - - // TODO: Improve records => snapshots => records => snapshots - // - // We want to provide records to all store methods and snapshots to all - // adapter methods. To make sure we're doing that we're providing an array - // of snapshots to adapter.groupRecordsForFindMany(), which in turn will - // return grouped snapshots instead of grouped records. - // - // But since the _findMany() finder is a store method we need to get the - // records from the grouped snapshots even though the _findMany() finder - // will once again convert the records to snapshots for adapter.findMany() - - var snapshots = _ember['default'].A(records).invoke('createSnapshot'); - var groups = adapter.groupRecordsForFindMany(this, snapshots); - groups.forEach(function (groupOfSnapshots) { - var groupOfRecords = _ember['default'].A(groupOfSnapshots).mapBy('_internalModel'); - var requestedRecords = _ember['default'].A(groupOfRecords); - var ids = requestedRecords.mapBy('id'); - if (ids.length > 1) { - (0, _emberDataPrivateSystemStoreFinders._findMany)(adapter, store, typeClass, ids, requestedRecords).then(resolveFoundRecords).then(makeMissingRecordsRejector(requestedRecords)).then(null, makeRecordsRejector(requestedRecords)); - } else if (ids.length === 1) { - var pair = _ember['default'].A(pendingFetchItems).findBy('record', groupOfRecords[0]); - _fetchRecord(pair); - } else { - (0, _emberDataPrivateDebug.assert)("You cannot return an empty array from adapter's method groupRecordsForFindMany", false); - } - }); - } else { - pendingFetchItems.forEach(_fetchRecord); - } - }, - - /** - Get a record by a given type and ID without triggering a fetch. - This method will synchronously return the record if it is available in the store, - otherwise it will return `null`. A record is available if it has been fetched earlier, or - pushed manually into the store. - _Note: This is an synchronous method and does not return a promise._ - ```js - var post = store.peekRecord('post', 1); - post.get('id'); // 1 - ``` - @method peekRecord - @param {String} modelName - @param {String|Integer} id - @return {DS.Model|null} record - */ - peekRecord: function peekRecord(modelName, id) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - if (this.hasRecordForId(modelName, id)) { - return this._internalModelForId(modelName, id).getRecord(); - } else { - return null; - } - }, - - /** - This method is called by the record's `reload` method. - This method calls the adapter's `find` method, which returns a promise. When - **that** promise resolves, `reloadRecord` will resolve the promise returned - by the record's `reload`. - @method reloadRecord - @private - @param {DS.Model} internalModel - @return {Promise} promise - */ - reloadRecord: function reloadRecord(internalModel) { - var modelName = internalModel.type.modelName; - var adapter = this.adapterFor(modelName); - var id = internalModel.id; - - (0, _emberDataPrivateDebug.assert)("You cannot reload a record without an ID", id); - (0, _emberDataPrivateDebug.assert)("You tried to reload a record but you have no adapter (for " + modelName + ")", adapter); - (0, _emberDataPrivateDebug.assert)("You tried to reload a record but your adapter does not implement `findRecord`", typeof adapter.findRecord === 'function' || typeof adapter.find === 'function'); - - return this.scheduleFetch(internalModel); - }, - - /** - Returns true if a record for a given type and ID is already loaded. - @method hasRecordForId - @param {(String|DS.Model)} modelName - @param {(String|Integer)} inputId - @return {Boolean} - */ - hasRecordForId: function hasRecordForId(modelName, inputId) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - var typeClass = this.modelFor(modelName); - var id = (0, _emberDataPrivateSystemCoerceId['default'])(inputId); - var internalModel = this.typeMapFor(typeClass).idToRecord[id]; - return !!internalModel && internalModel.isLoaded(); - }, - - /** - Returns id record for a given type and ID. If one isn't already loaded, - it builds a new record and leaves it in the `empty` state. - @method recordForId - @private - @param {String} modelName - @param {(String|Integer)} id - @return {DS.Model} record - */ - recordForId: function recordForId(modelName, id) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - return this._internalModelForId(modelName, id).getRecord(); - }, - - _internalModelForId: function _internalModelForId(typeName, inputId) { - var typeClass = this.modelFor(typeName); - var id = (0, _emberDataPrivateSystemCoerceId['default'])(inputId); - var idToRecord = this.typeMapFor(typeClass).idToRecord; - var record = idToRecord[id]; - - if (!record || !idToRecord[id]) { - record = this.buildInternalModel(typeClass, id); - } - - return record; - }, - - /** - @method findMany - @private - @param {Array} internalModels - @return {Promise} promise - */ - findMany: function findMany(internalModels) { - var finds = new Array(internalModels.length); - - for (var i = 0; i < internalModels.length; i++) { - finds[i] = this._findByInternalModel(internalModels[i]); - } - - return Promise.all(finds); - }, - - /** - If a relationship was originally populated by the adapter as a link - (as opposed to a list of IDs), this method is called when the - relationship is fetched. - The link (which is usually a URL) is passed through unchanged, so the - adapter can make whatever request it wants. - The usual use-case is for the server to register a URL as a link, and - then use that URL in the future to make a request for the relationship. - @method findHasMany - @private - @param {DS.Model} owner - @param {any} link - @param {(Relationship)} relationship - @return {Promise} promise - */ - findHasMany: function findHasMany(owner, link, relationship) { - var adapter = this.adapterFor(owner.type.modelName); - - (0, _emberDataPrivateDebug.assert)("You tried to load a hasMany relationship but you have no adapter (for " + owner.type + ")", adapter); - (0, _emberDataPrivateDebug.assert)("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", typeof adapter.findHasMany === 'function'); - - return (0, _emberDataPrivateSystemStoreFinders._findHasMany)(adapter, this, owner, link, relationship); - }, - - /** - @method findBelongsTo - @private - @param {DS.Model} owner - @param {any} link - @param {Relationship} relationship - @return {Promise} promise - */ - findBelongsTo: function findBelongsTo(owner, link, relationship) { - var adapter = this.adapterFor(owner.type.modelName); - - (0, _emberDataPrivateDebug.assert)("You tried to load a belongsTo relationship but you have no adapter (for " + owner.type + ")", adapter); - (0, _emberDataPrivateDebug.assert)("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", typeof adapter.findBelongsTo === 'function'); - - return (0, _emberDataPrivateSystemStoreFinders._findBelongsTo)(adapter, this, owner, link, relationship); - }, - - /** - This method delegates a query to the adapter. This is the one place where - adapter-level semantics are exposed to the application. - Exposing queries this way seems preferable to creating an abstract query - language for all server-side queries, and then require all adapters to - implement them. - --- - If you do something like this: - ```javascript - store.query('person', { page: 1 }); - ``` - The call made to the server, using a Rails backend, will look something like this: - ``` - Started GET "/api/v1/person?page=1" - Processing by Api::V1::PersonsController#index as HTML - Parameters: { "page"=>"1" } - ``` - --- - If you do something like this: - ```javascript - store.query('person', { ids: [1, 2, 3] }); - ``` - The call to the server, using a Rails backend, will look something like this: - ``` - Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3" - Processing by Api::V1::PersonsController#index as HTML - Parameters: { "ids" => ["1", "2", "3"] } - ``` - This method returns a promise, which is resolved with a `RecordArray` - once the server returns. - @method query - @param {String} modelName - @param {any} query an opaque query to be used by the adapter - @return {Promise} promise - */ - query: function query(modelName, _query2) { - return this._query(modelName, _query2); - }, - - _query: function _query(modelName, query, array) { - (0, _emberDataPrivateDebug.assert)("You need to pass a type to the store's query method", modelName); - (0, _emberDataPrivateDebug.assert)("You need to pass a query hash to the store's query method", query); - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - var typeClass = this.modelFor(modelName); - array = array || this.recordArrayManager.createAdapterPopulatedRecordArray(typeClass, query); - - var adapter = this.adapterFor(modelName); - - (0, _emberDataPrivateDebug.assert)("You tried to load a query but you have no adapter (for " + typeClass + ")", adapter); - (0, _emberDataPrivateDebug.assert)("You tried to load a query but your adapter does not implement `query`", typeof adapter.query === 'function'); - - return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._query)(adapter, this, typeClass, query, array)); - }, - - /** - This method delegates a query to the adapter. This is the one place where - adapter-level semantics are exposed to the application. - Exposing queries this way seems preferable to creating an abstract query - language for all server-side queries, and then require all adapters to - implement them. - This method returns a promise, which is resolved with a `RecordObject` - once the server returns. - @method queryRecord - @param {String} modelName - @param {any} query an opaque query to be used by the adapter - @return {Promise} promise - */ - queryRecord: function queryRecord(modelName, query) { - (0, _emberDataPrivateDebug.assert)("You need to pass a type to the store's queryRecord method", modelName); - (0, _emberDataPrivateDebug.assert)("You need to pass a query hash to the store's queryRecord method", query); - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - - var typeClass = this.modelFor(modelName); - var adapter = this.adapterFor(modelName); - - (0, _emberDataPrivateDebug.assert)("You tried to make a query but you have no adapter (for " + typeClass + ")", adapter); - (0, _emberDataPrivateDebug.assert)("You tried to make a query but your adapter does not implement `queryRecord`", typeof adapter.queryRecord === 'function'); - - return (0, _emberDataPrivateSystemPromiseProxies.promiseObject)((0, _emberDataPrivateSystemStoreFinders._queryRecord)(adapter, this, typeClass, query)); - }, - - /** - `findAll` ask the adapter's `findAll` method to find the records - for the given type, and return a promise that will be resolved - once the server returns the values. The promise will resolve into - all records of this type present in the store, even if the server - only returns a subset of them. - ```app/routes/authors.js - import Ember from 'ember'; - export default Ember.Route.extend({ - model: function(params) { - return this.store.findAll('author'); - } - }); - ``` - @method findAll - @param {String} modelName - @param {Object} options - @return {DS.AdapterPopulatedRecordArray} - */ - findAll: function findAll(modelName, options) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - var typeClass = this.modelFor(modelName); - - return this._fetchAll(typeClass, this.peekAll(modelName), options); - }, - - /** - @method _fetchAll - @private - @param {DS.Model} typeClass - @param {DS.RecordArray} array - @return {Promise} promise - */ - _fetchAll: function _fetchAll(typeClass, array, options) { - options = options || {}; - var adapter = this.adapterFor(typeClass.modelName); - var sinceToken = this.typeMapFor(typeClass).metadata.since; - - set(array, 'isUpdating', true); - - (0, _emberDataPrivateDebug.assert)("You tried to load all records but you have no adapter (for " + typeClass + ")", adapter); - (0, _emberDataPrivateDebug.assert)("You tried to load all records but your adapter does not implement `findAll`", typeof adapter.findAll === 'function'); - if (options.reload) { - return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options)); - } - var snapshotArray = array.createSnapshot(options); - if (adapter.shouldReloadAll(this, snapshotArray)) { - return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)((0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options)); - } - if (adapter.shouldBackgroundReloadAll(this, snapshotArray)) { - (0, _emberDataPrivateSystemStoreFinders._findAll)(adapter, this, typeClass, sinceToken, options); - } - return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(Promise.resolve(array)); - }, - - /** - @method didUpdateAll - @param {DS.Model} typeClass - @private - */ - didUpdateAll: function didUpdateAll(typeClass) { - var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); - set(liveRecordArray, 'isUpdating', false); - }, - - /** - This method returns a filtered array that contains all of the - known records for a given type in the store. - Note that because it's just a filter, the result will contain any - locally created records of the type, however, it will not make a - request to the backend to retrieve additional records. If you - would like to request all the records from the backend please use - [store.findAll](#method_findAll). - Also note that multiple calls to `peekAll` for a given type will always - return the same `RecordArray`. - Example - ```javascript - var localPosts = store.peekAll('post'); - ``` - @method peekAll - @param {String} modelName - @return {DS.RecordArray} - */ - peekAll: function peekAll(modelName) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - var typeClass = this.modelFor(modelName); - - var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); - this.recordArrayManager.populateLiveRecordArray(liveRecordArray, typeClass); - - return liveRecordArray; - }, - - /** - This method unloads all records in the store. - Optionally you can pass a type which unload all records for a given type. - ```javascript - store.unloadAll(); - store.unloadAll('post'); - ``` - @method unloadAll - @param {String=} modelName - */ - unloadAll: function unloadAll(modelName) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), !modelName || typeof modelName === 'string'); - if (arguments.length === 0) { - var typeMaps = this.typeMaps; - var keys = Object.keys(typeMaps); - var types = new Array(keys.length); - - for (var i = 0; i < keys.length; i++) { - types[i] = typeMaps[keys[i]]['type'].modelName; - } - - types.forEach(this.unloadAll, this); - } else { - var typeClass = this.modelFor(modelName); - var typeMap = this.typeMapFor(typeClass); - var records = typeMap.records.slice(); - var record = undefined; - - for (var i = 0; i < records.length; i++) { - record = records[i]; - record.unloadRecord(); - record.destroy(); // maybe within unloadRecord - } - - typeMap.metadata = new _emberDataPrivateSystemEmptyObject['default'](); - } - }, - - /** - Takes a type and filter function, and returns a live RecordArray that - remains up to date as new records are loaded into the store or created - locally. - The filter function takes a materialized record, and returns true - if the record should be included in the filter and false if it should - not. - Example - ```javascript - store.filter('post', function(post) { - return post.get('unread'); - }); - ``` - The filter function is called once on all records for the type when - it is created, and then once on each newly loaded or created record. - If any of a record's properties change, or if it changes state, the - filter function will be invoked again to determine whether it should - still be in the array. - Optionally you can pass a query, which is the equivalent of calling - [find](#method_find) with that same query, to fetch additional records - from the server. The results returned by the server could then appear - in the filter if they match the filter function. - The query itself is not used to filter records, it's only sent to your - server for you to be able to do server-side filtering. The filter - function will be applied on the returned results regardless. - Example - ```javascript - store.filter('post', { unread: true }, function(post) { - return post.get('unread'); - }).then(function(unreadPosts) { - unreadPosts.get('length'); // 5 - var unreadPost = unreadPosts.objectAt(0); - unreadPost.set('unread', false); - unreadPosts.get('length'); // 4 - }); - ``` - @method filter - @param {String} modelName - @param {Object} query optional query - @param {Function} filter - @return {DS.PromiseArray} - */ - filter: function filter(modelName, query, _filter) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - - if (!_ember['default'].ENV.ENABLE_DS_FILTER) { - (0, _emberDataPrivateDebug.assert)('The filter API has been moved to a plugin. To enable store.filter using an environment flag, or to use an alternative, you can visit the ember-data-filter addon page. https://github.com/ember-data/ember-data-filter', false); - } - - var promise; - var length = arguments.length; - var array; - var hasQuery = length === 3; - - // allow an optional server query - if (hasQuery) { - promise = this.query(modelName, query); - } else if (arguments.length === 2) { - _filter = query; - } - - modelName = this.modelFor(modelName); - - if (hasQuery) { - array = this.recordArrayManager.createFilteredRecordArray(modelName, _filter, query); - } else { - array = this.recordArrayManager.createFilteredRecordArray(modelName, _filter); - } - - promise = promise || Promise.resolve(array); - - return (0, _emberDataPrivateSystemPromiseProxies.promiseArray)(promise.then(function () { - return array; - }, null, 'DS: Store#filter of ' + modelName)); - }, - - /** - This method returns if a certain record is already loaded - in the store. Use this function to know beforehand if a findRecord() - will result in a request or that it will be a cache hit. - Example - ```javascript - store.recordIsLoaded('post', 1); // false - store.findRecord('post', 1).then(function() { - store.recordIsLoaded('post', 1); // true - }); - ``` - @method recordIsLoaded - @param {String} modelName - @param {string} id - @return {boolean} - */ - recordIsLoaded: function recordIsLoaded(modelName, id) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - return this.hasRecordForId(modelName, id); - }, - - // ............ - // . UPDATING . - // ............ - - /** - If the adapter updates attributes the record will notify - the store to update its membership in any filters. - To avoid thrashing, this method is invoked only once per - run loop per record. - @method dataWasUpdated - @private - @param {Class} type - @param {InternalModel} internalModel - */ - dataWasUpdated: function dataWasUpdated(type, internalModel) { - this.recordArrayManager.recordDidChange(internalModel); - }, - - // .............. - // . PERSISTING . - // .............. - - /** - This method is called by `record.save`, and gets passed a - resolver for the promise that `record.save` returns. - It schedules saving to happen at the end of the run loop. - @method scheduleSave - @private - @param {InternalModel} internalModel - @param {Resolver} resolver - @param {Object} options - */ - scheduleSave: function scheduleSave(internalModel, resolver, options) { - var snapshot = internalModel.createSnapshot(options); - internalModel.flushChangedAttributes(); - internalModel.adapterWillCommit(); - this._pendingSave.push({ - snapshot: snapshot, - resolver: resolver - }); - once(this, 'flushPendingSave'); - }, - - /** - This method is called at the end of the run loop, and - flushes any records passed into `scheduleSave` - @method flushPendingSave - @private - */ - flushPendingSave: function flushPendingSave() { - var _this = this; - - var pending = this._pendingSave.slice(); - this._pendingSave = []; - - pending.forEach(function (pendingItem) { - var snapshot = pendingItem.snapshot; - var resolver = pendingItem.resolver; - var record = snapshot._internalModel; - var adapter = _this.adapterFor(record.type.modelName); - var operation; - - if (get(record, 'currentState.stateName') === 'root.deleted.saved') { - return resolver.resolve(); - } else if (record.isNew()) { - operation = 'createRecord'; - } else if (record.isDeleted()) { - operation = 'deleteRecord'; - } else { - operation = 'updateRecord'; - } - - resolver.resolve(_commit(adapter, _this, operation, snapshot)); - }); - }, - - /** - This method is called once the promise returned by an - adapter's `createRecord`, `updateRecord` or `deleteRecord` - is resolved. - If the data provides a server-generated ID, it will - update the record and the store's indexes. - @method didSaveRecord - @private - @param {InternalModel} internalModel the in-flight internal model - @param {Object} data optional data (see above) - */ - didSaveRecord: function didSaveRecord(internalModel, dataArg) { - var data; - if (dataArg) { - data = dataArg.data; - } - if (data) { - // normalize relationship IDs into records - this._backburner.schedule('normalizeRelationships', this, '_setupRelationships', internalModel, data); - this.updateId(internalModel, data); - } - - //We first make sure the primary data has been updated - //TODO try to move notification to the user to the end of the runloop - internalModel.adapterDidCommit(data); - }, - - /** - This method is called once the promise returned by an - adapter's `createRecord`, `updateRecord` or `deleteRecord` - is rejected with a `DS.InvalidError`. - @method recordWasInvalid - @private - @param {InternalModel} internalModel - @param {Object} errors - */ - recordWasInvalid: function recordWasInvalid(internalModel, errors) { - internalModel.adapterDidInvalidate(errors); - }, - - /** - This method is called once the promise returned by an - adapter's `createRecord`, `updateRecord` or `deleteRecord` - is rejected (with anything other than a `DS.InvalidError`). - @method recordWasError - @private - @param {InternalModel} internalModel - @param {Error} error - */ - recordWasError: function recordWasError(internalModel, error) { - internalModel.adapterDidError(error); - }, - - /** - When an adapter's `createRecord`, `updateRecord` or `deleteRecord` - resolves with data, this method extracts the ID from the supplied - data. - @method updateId - @private - @param {InternalModel} internalModel - @param {Object} data - */ - updateId: function updateId(internalModel, data) { - var oldId = internalModel.id; - var id = (0, _emberDataPrivateSystemCoerceId['default'])(data.id); - - (0, _emberDataPrivateDebug.assert)("An adapter cannot assign a new id to a record that already has an id. " + internalModel + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); - - this.typeMapFor(internalModel.type).idToRecord[id] = internalModel; - - internalModel.setId(id); - }, - - /** - Returns a map of IDs to client IDs for a given type. - @method typeMapFor - @private - @param {DS.Model} typeClass - @return {Object} typeMap - */ - typeMapFor: function typeMapFor(typeClass) { - var typeMaps = get(this, 'typeMaps'); - var guid = _ember['default'].guidFor(typeClass); - var typeMap = typeMaps[guid]; - - if (typeMap) { - return typeMap; - } - - typeMap = { - idToRecord: new _emberDataPrivateSystemEmptyObject['default'](), - records: [], - metadata: new _emberDataPrivateSystemEmptyObject['default'](), - type: typeClass - }; - - typeMaps[guid] = typeMap; - - return typeMap; - }, - - // ................ - // . LOADING DATA . - // ................ - - /** - This internal method is used by `push`. - @method _load - @private - @param {(String|DS.Model)} type - @param {Object} data - */ - _load: function _load(data) { - var internalModel = this._internalModelForId(data.type, data.id); - - internalModel.setupData(data); - - this.recordArrayManager.recordDidChange(internalModel); - - return internalModel; - }, - - /* - In case someone defined a relationship to a mixin, for example: - ``` - var Comment = DS.Model.extend({ - owner: belongsTo('commentable'. { polymorphic: true}) - }); - var Commentable = Ember.Mixin.create({ - comments: hasMany('comment') - }); - ``` - we want to look up a Commentable class which has all the necessary - relationship metadata. Thus, we look up the mixin and create a mock - DS.Model, so we can access the relationship CPs of the mixin (`comments`) - in this case - */ - - _modelForMixin: function _modelForMixin(modelName) { - var normalizedModelName = (0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName); - // container.registry = 2.1 - // container._registry = 1.11 - 2.0 - // container = < 1.11 - var owner = (0, _emberDataPrivateUtils.getOwner)(this); - - var mixin = owner._lookupFactory('mixin:' + normalizedModelName); - if (mixin) { - //Cache the class as a model - owner.register('model:' + normalizedModelName, _emberDataModel['default'].extend(mixin)); - } - var factory = this.modelFactoryFor(normalizedModelName); - if (factory) { - factory.__isMixin = true; - factory.__mixin = mixin; - } - - return factory; - }, - - /** - Returns a model class for a particular key. Used by - methods that take a type key (like `find`, `createRecord`, - etc.) - @method modelFor - @param {String} modelName - @return {DS.Model} - */ - modelFor: function modelFor(modelName) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - - var factory = this.modelFactoryFor(modelName); - if (!factory) { - //Support looking up mixins as base types for polymorphic relationships - factory = this._modelForMixin(modelName); - } - if (!factory) { - throw new _ember['default'].Error("No model was found for '" + modelName + "'"); - } - factory.modelName = factory.modelName || (0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName); - - return factory; - }, - - modelFactoryFor: function modelFactoryFor(modelName) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - var normalizedKey = (0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName); - - var owner = (0, _emberDataPrivateUtils.getOwner)(this); - - return owner._lookupFactory('model:' + normalizedKey); - }, - - /** - Push some data for a given type into the store. - This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments: - - record's `type` should always be in singular, dasherized form - - members (properties) should be camelCased - [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level): - ```js - store.push({ - data: { - // primary data for single record of type `Person` - id: '1', - type: 'person', - attributes: { - firstName: 'Daniel', - lastName: 'Kmak' - } - } - }); - ``` - [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7) - `data` property can also hold an array (of records): - ```js - store.push({ - data: [ - // an array of records - { - id: '1', - type: 'person', - attributes: { - firstName: 'Daniel', - lastName: 'Kmak' - } - }, - { - id: '2', - type: 'person', - attributes: { - firstName: 'Tom', - lastName: 'Dale' - } - } - ] - }); - ``` - [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355) - There are some typical properties for `JSONAPI` payload: - * `id` - mandatory, unique record's key - * `type` - mandatory string which matches `model`'s dasherized name in singular form - * `attributes` - object which holds data for record attributes - `DS.attr`'s declared in model - * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`): - - [`links`](http://jsonapi.org/format/#document-links) - - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data - - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship - For this model: - ```app/models/person.js - import DS from 'ember-data'; - export default DS.Model.extend({ - firstName: DS.attr('string'), - lastName: DS.attr('string'), - children: DS.hasMany('person') - }); - ``` - To represent the children as IDs: - ```js - { - data: { - id: '1', - type: 'person', - attributes: { - firstName: 'Tom', - lastName: 'Dale' - }, - relationships: { - children: { - data: [ - { - id: '2', - type: 'person' - }, - { - id: '3', - type: 'person' - }, - { - id: '4', - type: 'person' - } - ] - } - } - } - } - ``` - [Demo.](http://ember-twiddle.com/343e1735e034091f5bde) - To represent the children relationship as a URL: - ```js - { - data: { - id: '1', - type: 'person', - attributes: { - firstName: 'Tom', - lastName: 'Dale' - }, - relationships: { - children: { - links: { - related: '/people/1/children' - } - } - } - } - } - ``` - If you're streaming data or implementing an adapter, make sure - that you have converted the incoming data into this form. The - store's [normalize](#method_normalize) method is a convenience - helper for converting a json payload into the form Ember Data - expects. - ```js - store.push(store.normalize('person', data)); - ``` - This method can be used both to push in brand new - records, as well as to update existing records. - @method push - @param {Object} data - @return {DS.Model|Array} the record(s) that was created or - updated. - */ - push: function push(data) { - var included = data.included; - var i, length; - if (included) { - for (i = 0, length = included.length; i < length; i++) { - this._pushInternalModel(included[i]); - } - } - - if (isArray(data.data)) { - length = data.data.length; - var internalModels = new Array(length); - for (i = 0; i < length; i++) { - internalModels[i] = this._pushInternalModel(data.data[i]).getRecord(); - } - return internalModels; - } - - if (data.data === null) { - return null; - } - - (0, _emberDataPrivateDebug.assert)('Expected an object in the \'data\' property in a call to \'push\' for ' + data.type + ', but was ' + _ember['default'].typeOf(data.data), _ember['default'].typeOf(data.data) === 'object'); - - var internalModel = this._pushInternalModel(data.data); - - return internalModel.getRecord(); - }, - - _hasModelFor: function _hasModelFor(type) { - return (0, _emberDataPrivateUtils.getOwner)(this)._lookupFactory('model:' + type); - }, - - _pushInternalModel: function _pushInternalModel(data) { - var _this2 = this; - - var modelName = data.type; - (0, _emberDataPrivateDebug.assert)('You must include an \'id\' for ' + modelName + ' in an object passed to \'push\'', data.id != null && data.id !== ''); - (0, _emberDataPrivateDebug.assert)('You tried to push data with a type \'' + modelName + '\' but no model could be found with that name.', this._hasModelFor(modelName)); - - var type = this.modelFor(modelName); - - // If Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload - // contains unknown keys, log a warning. - - if (_ember['default'].ENV.DS_WARN_ON_UNKNOWN_KEYS) { - (0, _emberDataPrivateDebug.warn)("The payload for '" + type.modelName + "' contains these unknown keys: " + _ember['default'].inspect(Object.keys(data).forEach(function (key) { - return !(key === 'id' || key === 'links' || get(type, 'fields').has(key) || key.match(/Type$/)); - })) + ". Make sure they've been defined in your model.", Object.keys(data).filter(function (key) { - return !(key === 'id' || key === 'links' || get(type, 'fields').has(key) || key.match(/Type$/)); - }).length === 0, { id: 'ds.store.unknown-keys-in-payload' }); - } - - // Actually load the record into the store. - var internalModel = this._load(data); - - this._backburner.join(function () { - _this2._backburner.schedule('normalizeRelationships', _this2, '_setupRelationships', internalModel, data); - }); - - return internalModel; - }, - - _setupRelationships: function _setupRelationships(record, data) { - // This will convert relationships specified as IDs into DS.Model instances - // (possibly unloaded) and also create the data structures used to track - // relationships. - setupRelationships(this, record, data); - }, - - /** - Push some raw data into the store. - This method can be used both to push in brand new - records, as well as to update existing records. You - can push in more than one type of object at once. - All objects should be in the format expected by the - serializer. - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.ActiveModelSerializer; - ``` - ```js - var pushData = { - posts: [ - { id: 1, post_title: "Great post", comment_ids: [2] } - ], - comments: [ - { id: 2, comment_body: "Insightful comment" } - ] - } - store.pushPayload(pushData); - ``` - By default, the data will be deserialized using a default - serializer (the application serializer if it exists). - Alternatively, `pushPayload` will accept a model type which - will determine which serializer will process the payload. - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.ActiveModelSerializer; - ``` - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.JSONSerializer; - ``` - ```js - store.pushPayload('comment', pushData); // Will use the application serializer - store.pushPayload('post', pushData); // Will use the post serializer - ``` - @method pushPayload - @param {String} modelName Optionally, a model type used to determine which serializer will be used - @param {Object} inputPayload - */ - pushPayload: function pushPayload(modelName, inputPayload) { - var _this3 = this; - - var serializer; - var payload; - if (!inputPayload) { - payload = modelName; - serializer = defaultSerializer(this); - (0, _emberDataPrivateDebug.assert)("You cannot use `store#pushPayload` without a modelName unless your default serializer defines `pushPayload`", typeof serializer.pushPayload === 'function'); - } else { - payload = inputPayload; - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - serializer = this.serializerFor(modelName); - } - this._adapterRun(function () { - return serializer.pushPayload(_this3, payload); - }); - }, - - /** - `normalize` converts a json payload into the normalized form that - [push](#method_push) expects. - Example - ```js - socket.on('message', function(message) { - var modelName = message.model; - var data = message.data; - store.push(modelName, store.normalize(modelName, data)); - }); - ``` - @method normalize - @param {String} modelName The name of the model type for this payload - @param {Object} payload - @return {Object} The normalized payload - */ - normalize: function normalize(modelName, payload) { - (0, _emberDataPrivateDebug.assert)('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - var serializer = this.serializerFor(modelName); - var model = this.modelFor(modelName); - return serializer.normalize(model, payload); - }, - - /** - Build a brand new record for a given type, ID, and - initial data. - @method buildRecord - @private - @param {DS.Model} type - @param {String} id - @param {Object} data - @return {InternalModel} internal model - */ - buildInternalModel: function buildInternalModel(type, id, data) { - var typeMap = this.typeMapFor(type); - var idToRecord = typeMap.idToRecord; - - (0, _emberDataPrivateDebug.assert)('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]); - (0, _emberDataPrivateDebug.assert)('\'' + _ember['default'].inspect(type) + '\' does not appear to be an ember-data model', typeof type._create === 'function'); - - // lookupFactory should really return an object that creates - // instances with the injections applied - var internalModel = new _emberDataPrivateSystemModelInternalModel['default'](type, id, this, null, data); - - // if we're creating an item, this process will be done - // later, once the object has been persisted. - if (id) { - idToRecord[id] = internalModel; - } - - typeMap.records.push(internalModel); - - return internalModel; - }, - - //Called by the state machine to notify the store that the record is ready to be interacted with - recordWasLoaded: function recordWasLoaded(record) { - this.recordArrayManager.recordWasLoaded(record); - }, - - // ............... - // . DESTRUCTION . - // ............... - - /** - When a record is destroyed, this un-indexes it and - removes it from any record arrays so it can be GCed. - @method _dematerializeRecord - @private - @param {InternalModel} internalModel - */ - _dematerializeRecord: function _dematerializeRecord(internalModel) { - var type = internalModel.type; - var typeMap = this.typeMapFor(type); - var id = internalModel.id; - - internalModel.updateRecordArrays(); - - if (id) { - delete typeMap.idToRecord[id]; - } - - var loc = typeMap.records.indexOf(internalModel); - typeMap.records.splice(loc, 1); - }, - - // ...................... - // . PER-TYPE ADAPTERS - // ...................... - - /** - Returns an instance of the adapter for a given type. For - example, `adapterFor('person')` will return an instance of - `App.PersonAdapter`. - If no `App.PersonAdapter` is found, this method will look - for an `App.ApplicationAdapter` (the default adapter for - your entire application). - If no `App.ApplicationAdapter` is found, it will return - the value of the `defaultAdapter`. - @method adapterFor - @public - @param {String} modelName - @return DS.Adapter - */ - adapterFor: function adapterFor(modelName) { - - (0, _emberDataPrivateDebug.assert)('Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - - return this.lookupAdapter(modelName); - }, - - _adapterRun: function _adapterRun(fn) { - return this._backburner.run(fn); - }, - - // .............................. - // . RECORD CHANGE NOTIFICATION . - // .............................. - - /** - Returns an instance of the serializer for a given type. For - example, `serializerFor('person')` will return an instance of - `App.PersonSerializer`. - If no `App.PersonSerializer` is found, this method will look - for an `App.ApplicationSerializer` (the default serializer for - your entire application). - if no `App.ApplicationSerializer` is found, it will attempt - to get the `defaultSerializer` from the `PersonAdapter` - (`adapterFor('person')`). - If a serializer cannot be found on the adapter, it will fall back - to an instance of `DS.JSONSerializer`. - @method serializerFor - @public - @param {String} modelName the record to serialize - @return {DS.Serializer} - */ - serializerFor: function serializerFor(modelName) { - - (0, _emberDataPrivateDebug.assert)('Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ' + _ember['default'].inspect(modelName), typeof modelName === 'string'); - - var fallbacks = ['application', this.adapterFor(modelName).get('defaultSerializer'), '-default']; - - var serializer = this.lookupSerializer(modelName, fallbacks); - return serializer; - }, - - /** - Retrieve a particular instance from the - container cache. If not found, creates it and - placing it in the cache. - Enabled a store to manage local instances of - adapters and serializers. - @method retrieveManagedInstance - @private - @param {String} modelName the object modelName - @param {String} name the object name - @param {Array} fallbacks the fallback objects to lookup if the lookup for modelName or 'application' fails - @return {Ember.Object} - */ - retrieveManagedInstance: function retrieveManagedInstance(type, modelName, fallbacks) { - var normalizedModelName = (0, _emberDataPrivateSystemNormalizeModelName['default'])(modelName); - - var instance = this._instanceCache.get(type, normalizedModelName, fallbacks); - set(instance, 'store', this); - return instance; - }, - - lookupAdapter: function lookupAdapter(name) { - return this.retrieveManagedInstance('adapter', name, this.get('_adapterFallbacks')); - }, - - _adapterFallbacks: _ember['default'].computed('adapter', function () { - var adapter = this.get('adapter'); - return ['application', adapter, '-json-api']; - }), - - lookupSerializer: function lookupSerializer(name, fallbacks) { - return this.retrieveManagedInstance('serializer', name, fallbacks); - }, - - willDestroy: function willDestroy() { - this._super.apply(this, arguments); - this.recordArrayManager.destroy(); - - this.unloadAll(); - } - - }); - - if ((0, _emberDataPrivateFeatures['default'])("ds-references")) { - - Store.reopen({ - /** - Get the reference for the specified record. - Example - ```javascript - var userRef = store.getReference('user', 1); - // check if the user is loaded - var isLoaded = userRef.value() !== null; - // get the record of the reference (null if not yet available) - var user = userRef.value(); - // get the identifier of the reference - if (userRef.remoteType() === "id") { - var id = userRef.id(); - } - // load user (via store.find) - userRef.load().then(...) - // or trigger a reload - userRef.reload().then(...) - // provide data for reference - userRef.push({ id: 1, username: "@user" }).then(function(user) { - userRef.value() === user; - }); - ``` - @method getReference - @param {String} type - @param {String|Integer} id - @return {RecordReference} - */ - getReference: function getReference(type, id) { - return this._internalModelForId(type, id).recordReference; - } - }); - } - - function deserializeRecordId(store, key, relationship, id) { - if (isNone(id)) { - return; - } - - (0, _emberDataPrivateDebug.assert)('A ' + relationship.parentType + ' record was pushed into the store with the value of ' + key + ' being ' + _ember['default'].inspect(id) + ', but ' + key + ' is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.', !isArray(id)); - - //TODO:Better asserts - return store._internalModelForId(id.type, id.id); - } - - function deserializeRecordIds(store, key, relationship, ids) { - if (isNone(ids)) { - return; - } - - (0, _emberDataPrivateDebug.assert)('A ' + relationship.parentType + ' record was pushed into the store with the value of ' + key + ' being \'' + _ember['default'].inspect(ids) + '\', but ' + key + ' is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.', isArray(ids)); - var _ids = new Array(ids.length); - - for (var i = 0; i < ids.length; i++) { - _ids[i] = deserializeRecordId(store, key, relationship, ids[i]); - } - - return _ids; - } - - // Delegation to the adapter and promise management - - function defaultSerializer(store) { - return store.serializerFor('application'); - } - - function _commit(adapter, store, operation, snapshot) { - var internalModel = snapshot._internalModel; - var modelName = snapshot.modelName; - var typeClass = store.modelFor(modelName); - var promise = adapter[operation](store, typeClass, snapshot); - var serializer = (0, _emberDataPrivateSystemStoreSerializers.serializerForAdapter)(store, adapter, modelName); - var label = 'DS: Extract and notify about ' + operation + ' completion of ' + internalModel; - - (0, _emberDataPrivateDebug.assert)('Your adapter\'s \'' + operation + '\' method must return a value, but it returned \'undefined\'', promise !== undefined); - - promise = Promise.resolve(promise, label); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, store)); - promise = (0, _emberDataPrivateSystemStoreCommon._guard)(promise, (0, _emberDataPrivateSystemStoreCommon._bind)(_emberDataPrivateSystemStoreCommon._objectIsAlive, internalModel)); - - return promise.then(function (adapterPayload) { - store._adapterRun(function () { - var payload, data; - if (adapterPayload) { - payload = (0, _emberDataPrivateSystemStoreSerializerResponse.normalizeResponseHelper)(serializer, store, typeClass, adapterPayload, snapshot.id, operation); - if (payload.included) { - store.push({ data: payload.included }); - } - data = payload.data; - } - store.didSaveRecord(internalModel, { data: data }); - }); - - return internalModel; - }, function (error) { - if (error instanceof _emberDataPrivateAdaptersErrors.InvalidError) { - var errors = serializer.extractErrors(store, typeClass, error, snapshot.id); - store.recordWasInvalid(internalModel, errors); - } else { - store.recordWasError(internalModel, error); - } - - throw error; - }, label); - } - - function setupRelationships(store, record, data) { - if (!data.relationships) { - return; - } - - record.type.eachRelationship(function (key, descriptor) { - var kind = descriptor.kind; - - if (!data.relationships[key]) { - return; - } - - var relationship; - - if (data.relationships[key].links && data.relationships[key].links.related) { - var relatedLink = (0, _emberDataPrivateSystemNormalizeLink['default'])(data.relationships[key].links.related); - if (relatedLink && relatedLink.href) { - relationship = record._relationships.get(key); - relationship.updateLink(relatedLink.href); - } - } - - if (data.relationships[key].meta) { - relationship = record._relationships.get(key); - relationship.updateMeta(data.relationships[key].meta); - } - - // If the data contains a relationship that is specified as an ID (or IDs), - // normalizeRelationship will convert them into DS.Model instances - // (possibly unloaded) before we push the payload into the store. - normalizeRelationship(store, key, descriptor, data.relationships[key]); - - var value = data.relationships[key].data; - - if (value !== undefined) { - if (kind === 'belongsTo') { - relationship = record._relationships.get(key); - relationship.setCanonicalRecord(value); - } else if (kind === 'hasMany') { - relationship = record._relationships.get(key); - relationship.updateRecordsFromAdapter(value); - } - } - }); - } - - function normalizeRelationship(store, key, relationship, jsonPayload) { - var data = jsonPayload.data; - if (data) { - var kind = relationship.kind; - if (kind === 'belongsTo') { - jsonPayload.data = deserializeRecordId(store, key, relationship, data); - } else if (kind === 'hasMany') { - jsonPayload.data = deserializeRecordIds(store, key, relationship, data); - } - } - } - - exports.Store = Store; - exports['default'] = Store; -}); -define("ember-data/-private/transforms/boolean", ["exports", "ember-data/transform"], function (exports, _emberDataTransform) { - "use strict"; - - /** - The `DS.BooleanTransform` class is used to serialize and deserialize - boolean attributes on Ember Data record objects. This transform is - used when `boolean` is passed as the type parameter to the - [DS.attr](../../data#method_attr) function. - - Usage - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - isAdmin: DS.attr('boolean'), - name: DS.attr('string'), - email: DS.attr('string') - }); - ``` - - @class BooleanTransform - @extends DS.Transform - @namespace DS - */ - exports["default"] = _emberDataTransform["default"].extend({ - deserialize: function deserialize(serialized) { - var type = typeof serialized; - - if (type === "boolean") { - return serialized; - } else if (type === "string") { - return serialized.match(/^true$|^t$|^1$/i) !== null; - } else if (type === "number") { - return serialized === 1; - } else { - return false; - } - }, - - serialize: function serialize(deserialized) { - return Boolean(deserialized); - } - }); -}); -define("ember-data/-private/transforms/date", ["exports", "ember", "ember-data/-private/ext/date", "ember-data/transform"], function (exports, _ember, _emberDataPrivateExtDate, _emberDataTransform) { - "use strict"; - - exports["default"] = _emberDataTransform["default"].extend({ - deserialize: function deserialize(serialized) { - var type = typeof serialized; - - if (type === "string") { - return new Date(_ember["default"].Date.parse(serialized)); - } else if (type === "number") { - return new Date(serialized); - } else if (serialized === null || serialized === undefined) { - // if the value is null return null - // if the value is not present in the data return undefined - return serialized; - } else { - return null; - } - }, - - serialize: function serialize(date) { - if (date instanceof Date) { - return date.toISOString(); - } else { - return null; - } - } - }); -}); - -/** - The `DS.DateTransform` class is used to serialize and deserialize - date attributes on Ember Data record objects. This transform is used - when `date` is passed as the type parameter to the - [DS.attr](../../data#method_attr) function. - - ```app/models/score.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - value: DS.attr('number'), - player: DS.belongsTo('player'), - date: DS.attr('date') - }); - ``` - - @class DateTransform - @extends DS.Transform - @namespace DS - */ -define("ember-data/-private/transforms/number", ["exports", "ember", "ember-data/transform"], function (exports, _ember, _emberDataTransform) { - "use strict"; - - var empty = _ember["default"].isEmpty; - - function isNumber(value) { - return value === value && value !== Infinity && value !== -Infinity; - } - - /** - The `DS.NumberTransform` class is used to serialize and deserialize - numeric attributes on Ember Data record objects. This transform is - used when `number` is passed as the type parameter to the - [DS.attr](../../data#method_attr) function. - - Usage - - ```app/models/score.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - value: DS.attr('number'), - player: DS.belongsTo('player'), - date: DS.attr('date') - }); - ``` - - @class NumberTransform - @extends DS.Transform - @namespace DS - */ - exports["default"] = _emberDataTransform["default"].extend({ - deserialize: function deserialize(serialized) { - var transformed; - - if (empty(serialized)) { - return null; - } else { - transformed = Number(serialized); - - return isNumber(transformed) ? transformed : null; - } - }, - - serialize: function serialize(deserialized) { - var transformed; - - if (empty(deserialized)) { - return null; - } else { - transformed = Number(deserialized); - - return isNumber(transformed) ? transformed : null; - } - } - }); -}); -define("ember-data/-private/transforms/string", ["exports", "ember", "ember-data/transform"], function (exports, _ember, _emberDataTransform) { - "use strict"; - - var none = _ember["default"].isNone; - - /** - The `DS.StringTransform` class is used to serialize and deserialize - string attributes on Ember Data record objects. This transform is - used when `string` is passed as the type parameter to the - [DS.attr](../../data#method_attr) function. - - Usage - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - isAdmin: DS.attr('boolean'), - name: DS.attr('string'), - email: DS.attr('string') - }); - ``` - - @class StringTransform - @extends DS.Transform - @namespace DS - */ - exports["default"] = _emberDataTransform["default"].extend({ - deserialize: function deserialize(serialized) { - return none(serialized) ? null : String(serialized); - }, - serialize: function serialize(deserialized) { - return none(deserialized) ? null : String(deserialized); - } - }); -}); -define("ember-data/-private/transforms", ["exports", "ember-data/transform", "ember-data/-private/transforms/number", "ember-data/-private/transforms/date", "ember-data/-private/transforms/string", "ember-data/-private/transforms/boolean"], function (exports, _emberDataTransform, _emberDataPrivateTransformsNumber, _emberDataPrivateTransformsDate, _emberDataPrivateTransformsString, _emberDataPrivateTransformsBoolean) { - "use strict"; - - exports.Transform = _emberDataTransform["default"]; - exports.NumberTransform = _emberDataPrivateTransformsNumber["default"]; - exports.DateTransform = _emberDataPrivateTransformsDate["default"]; - exports.StringTransform = _emberDataPrivateTransformsString["default"]; - exports.BooleanTransform = _emberDataPrivateTransformsBoolean["default"]; -}); -define('ember-data/-private/utils/parse-response-headers', ['exports', 'ember-data/-private/system/empty-object'], function (exports, _emberDataPrivateSystemEmptyObject) { - 'use strict'; - - exports['default'] = parseResponseHeaders; - - function _toArray(arr) { - return Array.isArray(arr) ? arr : Array.from(arr); - } - - var CLRF = '\r\n'; - function parseResponseHeaders(headersString) { - var headers = new _emberDataPrivateSystemEmptyObject['default'](); - - if (!headersString) { - return headers; - } - - var headerPairs = headersString.split(CLRF); - - headerPairs.forEach(function (header) { - var _header$split = header.split(':'); - - var _header$split2 = _toArray(_header$split); - - var field = _header$split2[0]; - - var value = _header$split2.slice(1); - - field = field.trim(); - value = value.join(':').trim(); - - if (value) { - headers[field] = value; - } - }); - - return headers; - } -}); -define('ember-data/-private/utils', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { - 'use strict'; - - var get = _ember['default'].get; - - /** - Assert that `addedRecord` has a valid type so it can be added to the - relationship of the `record`. - - The assert basically checks if the `addedRecord` can be added to the - relationship (specified via `relationshipMeta`) of the `record`. - - This utility should only be used internally, as both record parameters must - be an InternalModel and the `relationshipMeta` needs to be the meta - information about the relationship, retrieved via - `record.relationshipFor(key)`. - - @method assertPolymorphicType - @param {InternalModel} record - @param {RelationshipMeta} relationshipMeta retrieved via - `record.relationshipFor(key)` - @param {InternalModel} addedRecord record which - should be added/set for the relationship - */ - var assertPolymorphicType = function assertPolymorphicType(record, relationshipMeta, addedRecord) { - var addedType = addedRecord.type.modelName; - var recordType = record.type.modelName; - var key = relationshipMeta.key; - var typeClass = record.store.modelFor(relationshipMeta.type); - - var assertionMessage = 'You cannot add a record of type \'' + addedType + '\' to the \'' + recordType + '.' + key + '\' relationship (only \'' + typeClass.modelName + '\' allowed)'; - - (0, _emberDataPrivateDebug.assert)(assertionMessage, checkPolymorphic(typeClass, addedRecord)); - }; - - function checkPolymorphic(typeClass, addedRecord) { - if (typeClass.__isMixin) { - //TODO Need to do this in order to support mixins, should convert to public api - //once it exists in Ember - return typeClass.__mixin.detect(addedRecord.type.PrototypeMixin); - } - if (_ember['default'].MODEL_FACTORY_INJECTIONS) { - typeClass = typeClass.superclass; - } - return typeClass.detect(addedRecord.type); - } - - /** - Check if the passed model has a `type` attribute or a relationship named `type`. - - @method modelHasAttributeOrRelationshipNamedType - @param modelClass - */ - function modelHasAttributeOrRelationshipNamedType(modelClass) { - return get(modelClass, 'attributes').has('type') || get(modelClass, 'relationshipsByName').has('type'); - } - - /* - ember-container-inject-owner is a new feature in Ember 2.3 that finally provides a public - API for looking items up. This function serves as a super simple polyfill to avoid - triggering deprecations. - */ - function getOwner(context) { - var owner; - - if (_ember['default'].getOwner) { - owner = _ember['default'].getOwner(context); - } - - if (!owner && context.container) { - owner = context.container; - } - - if (owner && owner.lookupFactory && !owner._lookupFactory) { - // `owner` is a container, we are just making this work - owner._lookupFactory = owner.lookupFactory; - owner.register = function () { - var registry = owner.registry || owner._registry || owner; - - return registry.register.apply(registry, arguments); - }; - } - - return owner; - } - - exports.assertPolymorphicType = assertPolymorphicType; - exports.modelHasAttributeOrRelationshipNamedType = modelHasAttributeOrRelationshipNamedType; - exports.getOwner = getOwner; -}); -define('ember-data/adapter', ['exports', 'ember'], function (exports, _ember) { - /** - @module ember-data - */ - - 'use strict'; - - var get = _ember['default'].get; - - /** - An adapter is an object that receives requests from a store and - translates them into the appropriate action to take against your - persistence layer. The persistence layer is usually an HTTP API, but - may be anything, such as the browser's local storage. Typically the - adapter is not invoked directly instead its functionality is accessed - through the `store`. - - ### Creating an Adapter - - Create a new subclass of `DS.Adapter` in the `app/adapters` folder: - - ```app/adapters/application.js - import DS from 'ember-data'; - - export default DS.Adapter.extend({ - // ...your code here - }); - ``` - - Model-specific adapters can be created by putting your adapter - class in an `app/adapters/` + `model-name` + `.js` file of the application. - - ```app/adapters/post.js - import DS from 'ember-data'; - - export default DS.Adapter.extend({ - // ...Post-specific adapter code goes here - }); - ``` - - `DS.Adapter` is an abstract base class that you should override in your - application to customize it for your backend. The minimum set of methods - that you should implement is: - - * `findRecord()` - * `createRecord()` - * `updateRecord()` - * `deleteRecord()` - * `findAll()` - * `query()` - - To improve the network performance of your application, you can optimize - your adapter by overriding these lower-level methods: - - * `findMany()` - - - For an example implementation, see `DS.RESTAdapter`, the - included REST adapter. - - @class Adapter - @namespace DS - @extends Ember.Object - */ - - exports['default'] = _ember['default'].Object.extend({ - - /** - If you would like your adapter to use a custom serializer you can - set the `defaultSerializer` property to be the name of the custom - serializer. - Note the `defaultSerializer` serializer has a lower priority than - a model specific serializer (i.e. `PostSerializer`) or the - `application` serializer. - ```app/adapters/django.js - import DS from 'ember-data'; - export default DS.Adapter.extend({ - defaultSerializer: 'django' - }); - ``` - @property defaultSerializer - @type {String} - */ - defaultSerializer: '-default', - - /** - The `findRecord()` method is invoked when the store is asked for a record that - has not previously been loaded. In response to `findRecord()` being called, you - should query your persistence layer for a record with the given ID. Once - found, you can asynchronously call the store's `push()` method to push - the record into the store. - Here is an example `findRecord` implementation: - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.Adapter.extend({ - findRecord: function(store, type, id, snapshot) { - var url = [type.modelName, id].join('/'); - return new Ember.RSVP.Promise(function(resolve, reject) { - Ember.$.getJSON(url).then(function(data) { - Ember.run(null, resolve, data); - }, function(jqXHR) { - jqXHR.then = null; // tame jQuery's ill mannered promises - Ember.run(null, reject, jqXHR); - }); - }); - } - }); - ``` - @method findRecord - @param {DS.Store} store - @param {DS.Model} type - @param {String} id - @param {DS.Snapshot} snapshot - @return {Promise} promise - */ - findRecord: null, - - /** - The `findAll()` method is used to retrieve all records for a given type. - Example - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.Adapter.extend({ - findAll: function(store, type, sinceToken) { - var url = type; - var query = { since: sinceToken }; - return new Ember.RSVP.Promise(function(resolve, reject) { - Ember.$.getJSON(url, query).then(function(data) { - Ember.run(null, resolve, data); - }, function(jqXHR) { - jqXHR.then = null; // tame jQuery's ill mannered promises - Ember.run(null, reject, jqXHR); - }); - }); - } - }); - ``` - @method findAll - @param {DS.Store} store - @param {DS.Model} type - @param {String} sinceToken - @param {DS.SnapshotRecordArray} snapshotRecordArray - @return {Promise} promise - */ - findAll: null, - - /** - This method is called when you call `query` on the store. - Example - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.Adapter.extend({ - query: function(store, type, query) { - var url = type; - return new Ember.RSVP.Promise(function(resolve, reject) { - Ember.$.getJSON(url, query).then(function(data) { - Ember.run(null, resolve, data); - }, function(jqXHR) { - jqXHR.then = null; // tame jQuery's ill mannered promises - Ember.run(null, reject, jqXHR); - }); - }); - } - }); - ``` - @method query - @param {DS.Store} store - @param {DS.Model} type - @param {Object} query - @param {DS.AdapterPopulatedRecordArray} recordArray - @return {Promise} promise - */ - query: null, - - /** - The `queryRecord()` method is invoked when the store is asked for a single - record through a query object. - In response to `queryRecord()` being called, you should always fetch fresh - data. Once found, you can asynchronously call the store's `push()` method - to push the record into the store. - Here is an example `queryRecord` implementation: - Example - ```app/adapters/application.js - import DS from 'ember-data'; - import Ember from 'ember'; - export default DS.Adapter.extend(DS.BuildURLMixin, { - queryRecord: function(store, type, query) { - var urlForQueryRecord = this.buildURL(type.modelName, null, null, 'queryRecord', query); - return new Ember.RSVP.Promise(function(resolve, reject) { - Ember.$.getJSON(urlForQueryRecord, query).then(function(data) { - Ember.run(null, resolve, data); - }, function(jqXHR) { - jqXHR.then = null; // tame jQuery's ill mannered promises - Ember.run(null, reject, jqXHR); - }); - }); - } - }); - ``` - @method queryRecord - @param {DS.Store} store - @param {subclass of DS.Model} type - @param {Object} query - @return {Promise} promise - */ - queryRecord: null, - - /** - If the globally unique IDs for your records should be generated on the client, - implement the `generateIdForRecord()` method. This method will be invoked - each time you create a new record, and the value returned from it will be - assigned to the record's `primaryKey`. - Most traditional REST-like HTTP APIs will not use this method. Instead, the ID - of the record will be set by the server, and your adapter will update the store - with the new ID when it calls `didCreateRecord()`. Only implement this method if - you intend to generate record IDs on the client-side. - The `generateIdForRecord()` method will be invoked with the requesting store as - the first parameter and the newly created record as the second parameter: - ```javascript - generateIdForRecord: function(store, inputProperties) { - var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); - return uuid; - } - ``` - @method generateIdForRecord - @param {DS.Store} store - @param {DS.Model} type the DS.Model class of the record - @param {Object} inputProperties a hash of properties to set on the - newly created record. - @return {(String|Number)} id - */ - generateIdForRecord: null, - - /** - Proxies to the serializer's `serialize` method. - Example - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.Adapter.extend({ - createRecord: function(store, type, snapshot) { - var data = this.serialize(snapshot, { includeId: true }); - var url = type; - // ... - } - }); - ``` - @method serialize - @param {DS.Snapshot} snapshot - @param {Object} options - @return {Object} serialized snapshot - */ - serialize: function serialize(snapshot, options) { - return get(snapshot.record, 'store').serializerFor(snapshot.modelName).serialize(snapshot, options); - }, - - /** - Implement this method in a subclass to handle the creation of - new records. - Serializes the record and sends it to the server. - Example - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.Adapter.extend({ - createRecord: function(store, type, snapshot) { - var data = this.serialize(snapshot, { includeId: true }); - var url = type; - return new Ember.RSVP.Promise(function(resolve, reject) { - Ember.$.ajax({ - type: 'POST', - url: url, - dataType: 'json', - data: data - }).then(function(data) { - Ember.run(null, resolve, data); - }, function(jqXHR) { - jqXHR.then = null; // tame jQuery's ill mannered promises - Ember.run(null, reject, jqXHR); - }); - }); - } - }); - ``` - @method createRecord - @param {DS.Store} store - @param {DS.Model} type the DS.Model class of the record - @param {DS.Snapshot} snapshot - @return {Promise} promise - */ - createRecord: null, - - /** - Implement this method in a subclass to handle the updating of - a record. - Serializes the record update and sends it to the server. - The updateRecord method is expected to return a promise that will - resolve with the serialized record. This allows the backend to - inform the Ember Data store the current state of this record after - the update. If it is not possible to return a serialized record - the updateRecord promise can also resolve with `undefined` and the - Ember Data store will assume all of the updates were successfully - applied on the backend. - Example - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.Adapter.extend({ - updateRecord: function(store, type, snapshot) { - var data = this.serialize(snapshot, { includeId: true }); - var id = snapshot.id; - var url = [type, id].join('/'); - return new Ember.RSVP.Promise(function(resolve, reject) { - Ember.$.ajax({ - type: 'PUT', - url: url, - dataType: 'json', - data: data - }).then(function(data) { - Ember.run(null, resolve, data); - }, function(jqXHR) { - jqXHR.then = null; // tame jQuery's ill mannered promises - Ember.run(null, reject, jqXHR); - }); - }); - } - }); - ``` - @method updateRecord - @param {DS.Store} store - @param {DS.Model} type the DS.Model class of the record - @param {DS.Snapshot} snapshot - @return {Promise} promise - */ - updateRecord: null, - - /** - Implement this method in a subclass to handle the deletion of - a record. - Sends a delete request for the record to the server. - Example - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.Adapter.extend({ - deleteRecord: function(store, type, snapshot) { - var data = this.serialize(snapshot, { includeId: true }); - var id = snapshot.id; - var url = [type, id].join('/'); - return new Ember.RSVP.Promise(function(resolve, reject) { - Ember.$.ajax({ - type: 'DELETE', - url: url, - dataType: 'json', - data: data - }).then(function(data) { - Ember.run(null, resolve, data); - }, function(jqXHR) { - jqXHR.then = null; // tame jQuery's ill mannered promises - Ember.run(null, reject, jqXHR); - }); - }); - } - }); - ``` - @method deleteRecord - @param {DS.Store} store - @param {DS.Model} type the DS.Model class of the record - @param {DS.Snapshot} snapshot - @return {Promise} promise - */ - deleteRecord: null, - - /** - By default the store will try to coalesce all `fetchRecord` calls within the same runloop - into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. - You can opt out of this behaviour by either not implementing the findMany hook or by setting - coalesceFindRequests to false. - @property coalesceFindRequests - @type {boolean} - */ - coalesceFindRequests: true, - - /** - Find multiple records at once if coalesceFindRequests is true. - @method findMany - @param {DS.Store} store - @param {DS.Model} type the DS.Model class of the records - @param {Array} ids - @param {Array} snapshots - @return {Promise} promise - */ - findMany: null, - - /** - Organize records into groups, each of which is to be passed to separate - calls to `findMany`. - For example, if your api has nested URLs that depend on the parent, you will - want to group records by their parent. - The default implementation returns the records as a single group. - @method groupRecordsForFindMany - @param {DS.Store} store - @param {Array} snapshots - @return {Array} an array of arrays of records, each of which is to be - loaded separately by `findMany`. - */ - groupRecordsForFindMany: function groupRecordsForFindMany(store, snapshots) { - return [snapshots]; - }, - - /** - This method is used by the store to determine if the store should - reload a record from the adapter when a record is requested by - `store.findRecord`. - If this method returns true, the store will re-fetch a record from - the adapter. If this method returns false, the store will resolve - immediately using the cached record. - @method shouldReloadRecord - @param {DS.Store} store - @param {DS.Snapshot} snapshot - @return {Boolean} - */ - shouldReloadRecord: function shouldReloadRecord(store, snapshot) { - return false; - }, - - /** - This method is used by the store to determine if the store should - reload all records from the adapter when records are requested by - `store.findAll`. - If this method returns true, the store will re-fetch all records from - the adapter. If this method returns false, the store will resolve - immediately using the cached record. - @method shouldReloadAll - @param {DS.Store} store - @param {DS.SnapshotRecordArray} snapshotRecordArray - @return {Boolean} - */ - shouldReloadAll: function shouldReloadAll(store, snapshotRecordArray) { - return !snapshotRecordArray.length; - }, - - /** - This method is used by the store to determine if the store should - reload a record after the `store.findRecord` method resolves a - cached record. - This method is *only* checked by the store when the store is - returning a cached record. - If this method returns true the store will re-fetch a record from - the adapter. - @method shouldBackgroundReloadRecord - @param {DS.Store} store - @param {DS.Snapshot} snapshot - @return {Boolean} - */ - shouldBackgroundReloadRecord: function shouldBackgroundReloadRecord(store, snapshot) { - return true; - }, - - /** - This method is used by the store to determine if the store should - reload a record array after the `store.findAll` method resolves - with a cached record array. - This method is *only* checked by the store when the store is - returning a cached record array. - If this method returns true the store will re-fetch all records - from the adapter. - @method shouldBackgroundReloadAll - @param {DS.Store} store - @param {DS.SnapshotRecordArray} snapshotRecordArray - @return {Boolean} - */ - shouldBackgroundReloadAll: function shouldBackgroundReloadAll(store, snapshotRecordArray) { - return true; - } - }); -}); -define('ember-data/adapters/json-api', ['exports', 'ember', 'ember-data/adapters/rest'], function (exports, _ember, _emberDataAdaptersRest) { - /** - @module ember-data - */ - - 'use strict'; - - /** - @class JSONAPIAdapter - @constructor - @namespace DS - @extends DS.RESTAdapter - */ - exports['default'] = _emberDataAdaptersRest['default'].extend({ - defaultSerializer: '-json-api', - - /** - @method ajaxOptions - @private - @param {String} url - @param {String} type The request type GET, POST, PUT, DELETE etc. - @param {Object} options - @return {Object} - */ - ajaxOptions: function ajaxOptions(url, type, options) { - var hash = this._super.apply(this, arguments); - - if (hash.contentType) { - hash.contentType = 'application/vnd.api+json'; - } - - var beforeSend = hash.beforeSend; - hash.beforeSend = function (xhr) { - xhr.setRequestHeader('Accept', 'application/vnd.api+json'); - if (beforeSend) { - beforeSend(xhr); - } - }; - - return hash; - }, - - /** - By default the JSONAPIAdapter will send each find request coming from a `store.find` - or from accessing a relationship separately to the server. If your server supports passing - ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests - within a single runloop. - For example, if you have an initial payload of: - ```javascript - { - post: { - id: 1, - comments: [1, 2] - } - } - ``` - By default calling `post.get('comments')` will trigger the following requests(assuming the - comments haven't been loaded before): - ``` - GET /comments/1 - GET /comments/2 - ``` - If you set coalesceFindRequests to `true` it will instead trigger the following request: - ``` - GET /comments?filter[id]=1,2 - ``` - Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` - relationships accessed within the same runloop. If you set `coalesceFindRequests: true` - ```javascript - store.findRecord('comment', 1); - store.findRecord('comment', 2); - ``` - will also send a request to: `GET /comments?filter[id]=1,2` - Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app - `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. - @property coalesceFindRequests - @type {boolean} - */ - coalesceFindRequests: false, - - /** - @method findMany - @param {DS.Store} store - @param {DS.Model} type - @param {Array} ids - @param {Array} snapshots - @return {Promise} promise - */ - findMany: function findMany(store, type, ids, snapshots) { - var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); - return this.ajax(url, 'GET', { data: { filter: { id: ids.join(',') } } }); - }, - - /** - @method pathForType - @param {String} modelName - @return {String} path - **/ - pathForType: function pathForType(modelName) { - var dasherized = _ember['default'].String.dasherize(modelName); - return _ember['default'].String.pluralize(dasherized); - }, - - // TODO: Remove this once we have a better way to override HTTP verbs. - /** - @method updateRecord - @param {DS.Store} store - @param {DS.Model} type - @param {DS.Snapshot} snapshot - @return {Promise} promise - */ - updateRecord: function updateRecord(store, type, snapshot) { - var data = {}; - var serializer = store.serializerFor(type.modelName); - - serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); - - var id = snapshot.id; - var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); - - return this.ajax(url, 'PATCH', { data: data }); - } - }); -}); -define('ember-data/adapters/rest', ['exports', 'ember', 'ember-data/adapter', 'ember-data/-private/adapters/errors', 'ember-data/-private/adapters/build-url-mixin', 'ember-data/-private/features', 'ember-data/-private/utils/parse-response-headers'], function (exports, _ember, _emberDataAdapter, _emberDataPrivateAdaptersErrors, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateFeatures, _emberDataPrivateUtilsParseResponseHeaders) { - /** - @module ember-data - */ - - 'use strict'; - - var MapWithDefault = _ember['default'].MapWithDefault; - var get = _ember['default'].get; - - /** - The REST adapter allows your store to communicate with an HTTP server by - transmitting JSON via XHR. Most Ember.js apps that consume a JSON API - should use the REST adapter. - - This adapter is designed around the idea that the JSON exchanged with - the server should be conventional. - - ## JSON Structure - - The REST adapter expects the JSON returned from your server to follow - these conventions. - - ### Object Root - - The JSON payload should be an object that contains the record inside a - root property. For example, in response to a `GET` request for - `/posts/1`, the JSON should look like this: - - ```js - { - "post": { - "id": 1, - "title": "I'm Running to Reform the W3C's Tag", - "author": "Yehuda Katz" - } - } - ``` - - Similarly, in response to a `GET` request for `/posts`, the JSON should - look like this: - - ```js - { - "posts": [ - { - "id": 1, - "title": "I'm Running to Reform the W3C's Tag", - "author": "Yehuda Katz" - }, - { - "id": 2, - "title": "Rails is omakase", - "author": "D2H" - } - ] - } - ``` - - Note that the object root can be pluralized for both a single-object response - and an array response: the REST adapter is not strict on this. Further, if the - HTTP server responds to a `GET` request to `/posts/1` (e.g. the response to a - `findRecord` query) with more than one object in the array, Ember Data will - only display the object with the matching ID. - - ### Conventional Names - - Attribute names in your JSON payload should be the camelCased versions of - the attributes in your Ember.js models. - - For example, if you have a `Person` model: - - ```app/models/person.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - firstName: DS.attr('string'), - lastName: DS.attr('string'), - occupation: DS.attr('string') - }); - ``` - - The JSON returned should look like this: - - ```js - { - "person": { - "id": 5, - "firstName": "Barack", - "lastName": "Obama", - "occupation": "President" - } - } - ``` - - ## Customization - - ### Endpoint path customization - - Endpoint paths can be prefixed with a `namespace` by setting the namespace - property on the adapter: - - ```app/adapters/application.js - import DS from 'ember-data'; - - export default DS.RESTAdapter.extend({ - namespace: 'api/1' - }); - ``` - Requests for the `Person` model would now target `/api/1/people/1`. - - ### Host customization - - An adapter can target other hosts by setting the `host` property. - - ```app/adapters/application.js - import DS from 'ember-data'; - - export default DS.RESTAdapter.extend({ - host: 'https://api.example.com' - }); - ``` - - ### Headers customization - - Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary - headers can be set as key/value pairs on the `RESTAdapter`'s `headers` - object and Ember Data will send them along with each ajax request. - - - ```app/adapters/application.js - import DS from 'ember-data'; - - export default DS.RESTAdapter.extend({ - headers: { - "API_KEY": "secret key", - "ANOTHER_HEADER": "Some header value" - } - }); - ``` - - `headers` can also be used as a computed property to support dynamic - headers. In the example below, the `session` object has been - injected into an adapter by Ember's container. - - ```app/adapters/application.js - import DS from 'ember-data'; - - export default DS.RESTAdapter.extend({ - headers: Ember.computed('session.authToken', function() { - return { - "API_KEY": this.get("session.authToken"), - "ANOTHER_HEADER": "Some header value" - }; - }) - }); - ``` - - In some cases, your dynamic headers may require data from some - object outside of Ember's observer system (for example - `document.cookie`). You can use the - [volatile](/api/classes/Ember.ComputedProperty.html#method_volatile) - function to set the property into a non-cached mode causing the headers to - be recomputed with every request. - - ```app/adapters/application.js - import DS from 'ember-data'; - - export default DS.RESTAdapter.extend({ - headers: Ember.computed(function() { - return { - "API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"), - "ANOTHER_HEADER": "Some header value" - }; - }).volatile() - }); - ``` - - @class RESTAdapter - @constructor - @namespace DS - @extends DS.Adapter - @uses DS.BuildURLMixin - */ - exports['default'] = _emberDataAdapter['default'].extend(_emberDataPrivateAdaptersBuildUrlMixin['default'], { - defaultSerializer: '-rest', - - /** - By default, the RESTAdapter will send the query params sorted alphabetically to the - server. - For example: - ```js - store.query('posts', { sort: 'price', category: 'pets' }); - ``` - will generate a requests like this `/posts?category=pets&sort=price`, even if the - parameters were specified in a different order. - That way the generated URL will be deterministic and that simplifies caching mechanisms - in the backend. - Setting `sortQueryParams` to a falsey value will respect the original order. - In case you want to sort the query parameters with a different criteria, set - `sortQueryParams` to your custom sort function. - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.RESTAdapter.extend({ - sortQueryParams: function(params) { - var sortedKeys = Object.keys(params).sort().reverse(); - var len = sortedKeys.length, newParams = {}; - for (var i = 0; i < len; i++) { - newParams[sortedKeys[i]] = params[sortedKeys[i]]; - } - return newParams; - } - }); - ``` - @method sortQueryParams - @param {Object} obj - @return {Object} - */ - sortQueryParams: function sortQueryParams(obj) { - var keys = Object.keys(obj); - var len = keys.length; - if (len < 2) { - return obj; - } - var newQueryParams = {}; - var sortedKeys = keys.sort(); - - for (var i = 0; i < len; i++) { - newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]]; - } - return newQueryParams; - }, - - /** - By default the RESTAdapter will send each find request coming from a `store.find` - or from accessing a relationship separately to the server. If your server supports passing - ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests - within a single runloop. - For example, if you have an initial payload of: - ```javascript - { - post: { - id: 1, - comments: [1, 2] - } - } - ``` - By default calling `post.get('comments')` will trigger the following requests(assuming the - comments haven't been loaded before): - ``` - GET /comments/1 - GET /comments/2 - ``` - If you set coalesceFindRequests to `true` it will instead trigger the following request: - ``` - GET /comments?ids[]=1&ids[]=2 - ``` - Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` - relationships accessed within the same runloop. If you set `coalesceFindRequests: true` - ```javascript - store.findRecord('comment', 1); - store.findRecord('comment', 2); - ``` - will also send a request to: `GET /comments?ids[]=1&ids[]=2` - Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app - `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. - @property coalesceFindRequests - @type {boolean} - */ - coalesceFindRequests: false, - - /** - Endpoint paths can be prefixed with a `namespace` by setting the namespace - property on the adapter: - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.RESTAdapter.extend({ - namespace: 'api/1' - }); - ``` - Requests for the `Post` model would now target `/api/1/post/`. - @property namespace - @type {String} - */ - - /** - An adapter can target other hosts by setting the `host` property. - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.RESTAdapter.extend({ - host: 'https://api.example.com' - }); - ``` - Requests for the `Post` model would now target `https://api.example.com/post/`. - @property host - @type {String} - */ - - /** - Some APIs require HTTP headers, e.g. to provide an API - key. Arbitrary headers can be set as key/value pairs on the - `RESTAdapter`'s `headers` object and Ember Data will send them - along with each ajax request. For dynamic headers see [headers - customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). - ```app/adapters/application.js - import DS from 'ember-data'; - export default DS.RESTAdapter.extend({ - headers: { - "API_KEY": "secret key", - "ANOTHER_HEADER": "Some header value" - } - }); - ``` - @property headers - @type {Object} - */ - - /** - Called by the store in order to fetch the JSON for a given - type and ID. - The `findRecord` method makes an Ajax request to a URL computed by - `buildURL`, and returns a promise for the resulting payload. - This method performs an HTTP `GET` request with the id provided as part of the query string. - @method findRecord - @param {DS.Store} store - @param {DS.Model} type - @param {String} id - @param {DS.Snapshot} snapshot - @return {Promise} promise - */ - findRecord: function findRecord(store, type, id, snapshot) { - var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); - var query = this.buildQuery(snapshot); - - return this.ajax(url, 'GET', { data: query }); - }, - - /** - Called by the store in order to fetch a JSON array for all - of the records for a given type. - The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a - promise for the resulting payload. - @method findAll - @param {DS.Store} store - @param {DS.Model} type - @param {String} sinceToken - @param {DS.SnapshotRecordArray} snapshotRecordArray - @return {Promise} promise - */ - findAll: function findAll(store, type, sinceToken, snapshotRecordArray) { - var url = this.buildURL(type.modelName, null, null, 'findAll'); - var query = this.buildQuery(snapshotRecordArray); - - if (sinceToken) { - query.since = sinceToken; - } - - return this.ajax(url, 'GET', { data: query }); - }, - - /** - Called by the store in order to fetch a JSON array for - the records that match a particular query. - The `query` method makes an Ajax (HTTP GET) request to a URL - computed by `buildURL`, and returns a promise for the resulting - payload. - The `query` argument is a simple JavaScript object that will be passed directly - to the server as parameters. - @method query - @param {DS.Store} store - @param {DS.Model} type - @param {Object} query - @return {Promise} promise - */ - query: function query(store, type, _query) { - var url = this.buildURL(type.modelName, null, null, 'query', _query); - - if (this.sortQueryParams) { - _query = this.sortQueryParams(_query); - } - - return this.ajax(url, 'GET', { data: _query }); - }, - - /** - Called by the store in order to fetch a JSON object for - the record that matches a particular query. - The `queryRecord` method makes an Ajax (HTTP GET) request to a URL - computed by `buildURL`, and returns a promise for the resulting - payload. - The `query` argument is a simple JavaScript object that will be passed directly - to the server as parameters. - @method queryRecord - @param {DS.Store} store - @param {DS.Model} type - @param {Object} query - @return {Promise} promise - */ - queryRecord: function queryRecord(store, type, query) { - var url = this.buildURL(type.modelName, null, null, 'queryRecord', query); - - if (this.sortQueryParams) { - query = this.sortQueryParams(query); - } - - return this.ajax(url, 'GET', { data: query }); - }, - - /** - Called by the store in order to fetch several records together if `coalesceFindRequests` is true - For example, if the original payload looks like: - ```js - { - "id": 1, - "title": "Rails is omakase", - "comments": [ 1, 2, 3 ] - } - ``` - The IDs will be passed as a URL-encoded Array of IDs, in this form: - ``` - ids[]=1&ids[]=2&ids[]=3 - ``` - Many servers, such as Rails and PHP, will automatically convert this URL-encoded array - into an Array for you on the server-side. If you want to encode the - IDs, differently, just override this (one-line) method. - The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a - promise for the resulting payload. - @method findMany - @param {DS.Store} store - @param {DS.Model} type - @param {Array} ids - @param {Array} snapshots - @return {Promise} promise - */ - findMany: function findMany(store, type, ids, snapshots) { - var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); - return this.ajax(url, 'GET', { data: { ids: ids } }); - }, - - /** - Called by the store in order to fetch a JSON array for - the unloaded records in a has-many relationship that were originally - specified as a URL (inside of `links`). - For example, if your original payload looks like this: - ```js - { - "post": { - "id": 1, - "title": "Rails is omakase", - "links": { "comments": "/posts/1/comments" } - } - } - ``` - This method will be called with the parent record and `/posts/1/comments`. - The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. - The format of your `links` value will influence the final request URL via the `urlPrefix` method: - * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. - * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. - * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. - @method findHasMany - @param {DS.Store} store - @param {DS.Snapshot} snapshot - @param {String} url - @return {Promise} promise - */ - findHasMany: function findHasMany(store, snapshot, url, relationship) { - var id = snapshot.id; - var type = snapshot.modelName; - - url = this.urlPrefix(url, this.buildURL(type, id, null, 'findHasMany')); - - return this.ajax(url, 'GET'); - }, - - /** - Called by the store in order to fetch a JSON array for - the unloaded records in a belongs-to relationship that were originally - specified as a URL (inside of `links`). - For example, if your original payload looks like this: - ```js - { - "person": { - "id": 1, - "name": "Tom Dale", - "links": { "group": "/people/1/group" } - } - } - ``` - This method will be called with the parent record and `/people/1/group`. - The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. - The format of your `links` value will influence the final request URL via the `urlPrefix` method: - * Links beginning with `//`, `http://`, `https://`, will be used as is, with no further manipulation. - * Links beginning with a single `/` will have the current adapter's `host` value prepended to it. - * Links with no beginning `/` will have a parentURL prepended to it, via the current adapter's `buildURL`. - @method findBelongsTo - @param {DS.Store} store - @param {DS.Snapshot} snapshot - @param {String} url - @return {Promise} promise - */ - findBelongsTo: function findBelongsTo(store, snapshot, url, relationship) { - var id = snapshot.id; - var type = snapshot.modelName; - - url = this.urlPrefix(url, this.buildURL(type, id, null, 'findBelongsTo')); - return this.ajax(url, 'GET'); - }, - - /** - Called by the store when a newly created record is - saved via the `save` method on a model record instance. - The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request - to a URL computed by `buildURL`. - See `serialize` for information on how to customize the serialized form - of a record. - @method createRecord - @param {DS.Store} store - @param {DS.Model} type - @param {DS.Snapshot} snapshot - @return {Promise} promise - */ - createRecord: function createRecord(store, type, snapshot) { - var data = {}; - var serializer = store.serializerFor(type.modelName); - var url = this.buildURL(type.modelName, null, snapshot, 'createRecord'); - - serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); - - return this.ajax(url, "POST", { data: data }); - }, - - /** - Called by the store when an existing record is saved - via the `save` method on a model record instance. - The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request - to a URL computed by `buildURL`. - See `serialize` for information on how to customize the serialized form - of a record. - @method updateRecord - @param {DS.Store} store - @param {DS.Model} type - @param {DS.Snapshot} snapshot - @return {Promise} promise - */ - updateRecord: function updateRecord(store, type, snapshot) { - var data = {}; - var serializer = store.serializerFor(type.modelName); - - serializer.serializeIntoHash(data, type, snapshot); - - var id = snapshot.id; - var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); - - return this.ajax(url, "PUT", { data: data }); - }, - - /** - Called by the store when a record is deleted. - The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. - @method deleteRecord - @param {DS.Store} store - @param {DS.Model} type - @param {DS.Snapshot} snapshot - @return {Promise} promise - */ - deleteRecord: function deleteRecord(store, type, snapshot) { - var id = snapshot.id; - - return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE"); - }, - - _stripIDFromURL: function _stripIDFromURL(store, snapshot) { - var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot); - - var expandedURL = url.split('/'); - //Case when the url is of the format ...something/:id - var lastSegment = expandedURL[expandedURL.length - 1]; - var id = snapshot.id; - if (lastSegment === id) { - expandedURL[expandedURL.length - 1] = ""; - } else if (endsWith(lastSegment, '?id=' + id)) { - //Case when the url is of the format ...something?id=:id - expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); - } - - return expandedURL.join('/'); - }, - - // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers - maxURLLength: 2048, - - /** - Organize records into groups, each of which is to be passed to separate - calls to `findMany`. - This implementation groups together records that have the same base URL but - differing ids. For example `/comments/1` and `/comments/2` will be grouped together - because we know findMany can coalesce them together as `/comments?ids[]=1&ids[]=2` - It also supports urls where ids are passed as a query param, such as `/comments?id=1` - but not those where there is more than 1 query param such as `/comments?id=2&name=David` - Currently only the query param of `id` is supported. If you need to support others, please - override this or the `_stripIDFromURL` method. - It does not group records that have differing base urls, such as for example: `/posts/1/comments/2` - and `/posts/2/comments/3` - @method groupRecordsForFindMany - @param {DS.Store} store - @param {Array} snapshots - @return {Array} an array of arrays of records, each of which is to be - loaded separately by `findMany`. - */ - groupRecordsForFindMany: function groupRecordsForFindMany(store, snapshots) { - var groups = MapWithDefault.create({ defaultValue: function defaultValue() { - return []; - } }); - var adapter = this; - var maxURLLength = this.maxURLLength; - - snapshots.forEach(function (snapshot) { - var baseUrl = adapter._stripIDFromURL(store, snapshot); - groups.get(baseUrl).push(snapshot); - }); - - function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) { - var baseUrl = adapter._stripIDFromURL(store, group[0]); - var idsSize = 0; - var splitGroups = [[]]; - - group.forEach(function (snapshot) { - var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength; - if (baseUrl.length + idsSize + additionalLength >= maxURLLength) { - idsSize = 0; - splitGroups.push([]); - } - - idsSize += additionalLength; - - var lastGroupIndex = splitGroups.length - 1; - splitGroups[lastGroupIndex].push(snapshot); - }); - - return splitGroups; - } - - var groupsArray = []; - groups.forEach(function (group, key) { - var paramNameLength = '&ids%5B%5D='.length; - var splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength); - - splitGroups.forEach(function (splitGroup) { - return groupsArray.push(splitGroup); - }); - }); - - return groupsArray; - }, - - /** - Takes an ajax response, and returns the json payload or an error. - By default this hook just returns the json payload passed to it. - You might want to override it in two cases: - 1. Your API might return useful results in the response headers. - Response headers are passed in as the second argument. - 2. Your API might return errors as successful responses with status code - 200 and an Errors text or object. You can return a `DS.InvalidError` or a - `DS.AdapterError` (or a sub class) from this hook and it will automatically - reject the promise and put your record into the invalid or error state. - Returning a `DS.InvalidError` from this method will cause the - record to transition into the `invalid` state and make the - `errors` object available on the record. When returning an - `DS.InvalidError` the store will attempt to normalize the error data - returned from the server using the serializer's `extractErrors` - method. - @method handleResponse - @param {Number} status - @param {Object} headers - @param {Object} payload - @param {Object} requestData - the original request information - @return {Object | DS.AdapterError} response - */ - handleResponse: function handleResponse(status, headers, payload, requestData) { - if (this.isSuccess(status, headers, payload)) { - return payload; - } else if (this.isInvalid(status, headers, payload)) { - return new _emberDataPrivateAdaptersErrors.InvalidError(payload.errors); - } - - var errors = this.normalizeErrorResponse(status, headers, payload); - var detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData); - - return new _emberDataPrivateAdaptersErrors.AdapterError(errors, detailedMessage); - }, - - /** - Default `handleResponse` implementation uses this hook to decide if the - response is a success. - @method isSuccess - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Boolean} - */ - isSuccess: function isSuccess(status, headers, payload) { - return status >= 200 && status < 300 || status === 304; - }, - - /** - Default `handleResponse` implementation uses this hook to decide if the - response is a an invalid error. - @method isInvalid - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Boolean} - */ - isInvalid: function isInvalid(status, headers, payload) { - return status === 422; - }, - - /** - Takes a URL, an HTTP method and a hash of data, and makes an - HTTP request. - When the server responds with a payload, Ember Data will call into `extractSingle` - or `extractArray` (depending on whether the original query was for one record or - many records). - By default, `ajax` method has the following behavior: - * It sets the response `dataType` to `"json"` - * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be - `application/json; charset=utf-8` - * If the HTTP method is not `"GET"`, it stringifies the data passed in. The - data is the serialized record in the case of a save. - * Registers success and failure handlers. - @method ajax - @private - @param {String} url - @param {String} type The request type GET, POST, PUT, DELETE etc. - @param {Object} options - @return {Promise} promise - */ - ajax: function ajax(url, type, options) { - var adapter = this; - - var requestData = { - url: url, - method: type - }; - - return new _ember['default'].RSVP.Promise(function (resolve, reject) { - var hash = adapter.ajaxOptions(url, type, options); - - hash.success = function (payload, textStatus, jqXHR) { - - var response = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders['default'])(jqXHR.getAllResponseHeaders()), payload, requestData); - - if (response && response.isAdapterError) { - _ember['default'].run.join(null, reject, response); - } else { - _ember['default'].run.join(null, resolve, response); - } - }; - - hash.error = function (jqXHR, textStatus, errorThrown) { - var error = undefined; - - if (errorThrown instanceof Error) { - error = errorThrown; - } else if (textStatus === 'timeout') { - error = new _emberDataPrivateAdaptersErrors.TimeoutError(); - } else if (textStatus === 'abort') { - error = new _emberDataPrivateAdaptersErrors.AbortError(); - } else { - error = adapter.handleResponse(jqXHR.status, (0, _emberDataPrivateUtilsParseResponseHeaders['default'])(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || errorThrown, requestData); - } - - _ember['default'].run.join(null, reject, error); - }; - - adapter._ajaxRequest(hash); - }, 'DS: RESTAdapter#ajax ' + type + ' to ' + url); - }, - - /** - @method _ajaxRequest - @private - @param {Object} options jQuery ajax options to be used for the ajax request - */ - _ajaxRequest: function _ajaxRequest(options) { - _ember['default'].$.ajax(options); - }, - - /** - @method ajaxOptions - @private - @param {String} url - @param {String} type The request type GET, POST, PUT, DELETE etc. - @param {Object} options - @return {Object} - */ - ajaxOptions: function ajaxOptions(url, type, options) { - var hash = options || {}; - hash.url = url; - hash.type = type; - hash.dataType = 'json'; - hash.context = this; - - if (hash.data && type !== 'GET') { - hash.contentType = 'application/json; charset=utf-8'; - hash.data = JSON.stringify(hash.data); - } - - var headers = get(this, 'headers'); - if (headers !== undefined) { - hash.beforeSend = function (xhr) { - Object.keys(headers).forEach(function (key) { - return xhr.setRequestHeader(key, headers[key]); - }); - }; - } - - return hash; - }, - - /** - @method parseErrorResponse - @private - @param {String} responseText - @return {Object} - */ - parseErrorResponse: function parseErrorResponse(responseText) { - var json = responseText; - - try { - json = _ember['default'].$.parseJSON(responseText); - } catch (e) {} - - return json; - }, - - /** - @method normalizeErrorResponse - @private - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Object} errors payload - */ - normalizeErrorResponse: function normalizeErrorResponse(status, headers, payload) { - if (payload && typeof payload === 'object' && payload.errors) { - return payload.errors; - } else { - return [{ - status: '' + status, - title: "The backend responded with an error", - detail: '' + payload - }]; - } - }, - - /** - Generates a detailed ("friendly") error message, with plenty - of information for debugging (good luck!) - @method generatedDetailedMessage - @private - @param {Number} status - @param {Object} headers - @param {Object} payload - @return {Object} request information - */ - generatedDetailedMessage: function generatedDetailedMessage(status, headers, payload, requestData) { - var shortenedPayload; - var payloadContentType = headers["Content-Type"] || "Empty Content-Type"; - - if (payloadContentType === "text/html" && payload.length > 250) { - shortenedPayload = "[Omitted Lengthy HTML]"; - } else { - shortenedPayload = payload; - } - - var requestDescription = requestData.method + ' ' + requestData.url; - var payloadDescription = 'Payload (' + payloadContentType + ')'; - - return ['Ember Data Request ' + requestDescription + ' returned a ' + status, payloadDescription, shortenedPayload].join('\n'); - }, - - buildQuery: function buildQuery(snapshot) { - var include = snapshot.include; - - var query = {}; - - if ((0, _emberDataPrivateFeatures['default'])('ds-finder-include')) { - if (include) { - query.include = include; - } - } - - return query; - } - }); - - //From http://stackoverflow.com/questions/280634/endswith-in-javascript - function endsWith(string, suffix) { - if (typeof String.prototype.endsWith !== 'function') { - return string.indexOf(suffix, string.length - suffix.length) !== -1; - } else { - return string.endsWith(suffix); - } - } -}); -define("ember-data/attr", ["exports", "ember", "ember-data/-private/debug"], function (exports, _ember, _emberDataPrivateDebug) { - "use strict"; - - exports["default"] = attr; - - /** - @module ember-data - */ - - function getDefaultValue(record, options, key) { - if (typeof options.defaultValue === "function") { - return options.defaultValue.apply(null, arguments); - } else { - var defaultValue = options.defaultValue; - (0, _emberDataPrivateDebug.deprecate)("Non primitive defaultValues are deprecated because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.", typeof defaultValue !== 'object' || defaultValue === null, { - id: 'ds.defaultValue.complex-object', - until: '3.0.0' - }); - return defaultValue; - } - } - - function hasValue(record, key) { - return key in record._attributes || key in record._inFlightAttributes || key in record._data; - } - - function getValue(record, key) { - if (key in record._attributes) { - return record._attributes[key]; - } else if (key in record._inFlightAttributes) { - return record._inFlightAttributes[key]; - } else { - return record._data[key]; - } - } - - /** - `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). - By default, attributes are passed through as-is, however you can specify an - optional type to have the value automatically transformed. - Ember Data ships with four basic transform types: `string`, `number`, - `boolean` and `date`. You can define your own transforms by subclassing - [DS.Transform](/api/data/classes/DS.Transform.html). - - Note that you cannot use `attr` to define an attribute of `id`. - - `DS.attr` takes an optional hash as a second parameter, currently - supported options are: - - - `defaultValue`: Pass a string or a function to be called to set the attribute - to a default value if none is supplied. - - Example - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - username: DS.attr('string'), - email: DS.attr('string'), - verified: DS.attr('boolean', { defaultValue: false }) - }); - ``` - - Default value can also be a function. This is useful it you want to return - a new object for each attribute. - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - username: attr('string'), - email: attr('string'), - settings: attr({defaultValue: function() { - return {}; - }}) - }); - ``` - - @namespace - @method attr - @for DS - @param {String} type the attribute type - @param {Object} options a hash of options - @return {Attribute} - */ - function attr(type, options) { - if (typeof type === 'object') { - options = type; - type = undefined; - } else { - options = options || {}; - } - - var meta = { - type: type, - isAttribute: true, - options: options - }; - - return _ember["default"].computed({ - get: function get(key) { - var internalModel = this._internalModel; - if (hasValue(internalModel, key)) { - return getValue(internalModel, key); - } else { - return getDefaultValue(this, options, key); - } - }, - set: function set(key, value) { - var internalModel = this._internalModel; - var oldValue = getValue(internalModel, key); - - if (value !== oldValue) { - // Add the new value to the changed attributes hash; it will get deleted by - // the 'didSetProperty' handler if it is no different from the original value - internalModel._attributes[key] = value; - - this._internalModel.send('didSetProperty', { - name: key, - oldValue: oldValue, - originalValue: internalModel._data[key], - value: value - }); - } - - return value; - } - }).meta(meta); - } -}); -define("ember-data/index", ["exports", "ember", "ember-data/-private/debug", "ember-data/-private/core", "ember-data/-private/system/normalize-model-name", "ember-data/-private/system/model/internal-model", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/store", "ember-data/-private/system/model", "ember-data/model", "ember-data/-private/system/snapshot", "ember-data/adapter", "ember-data/serializer", "ember-data/-private/system/debug", "ember-data/-private/adapters/errors", "ember-data/-private/system/record-arrays", "ember-data/-private/system/many-array", "ember-data/-private/system/record-array-manager", "ember-data/-private/adapters", "ember-data/-private/adapters/build-url-mixin", "ember-data/-private/serializers", "ember-inflector", "ember-data/serializers/embedded-records-mixin", "ember-data/-private/transforms", "ember-data/relationships", "ember-data/setup-container", "ember-data/-private/instance-initializers/initialize-store-service", "ember-data/-private/system/container-proxy", "ember-data/-private/system/relationships/state/relationship"], function (exports, _ember, _emberDataPrivateDebug, _emberDataPrivateCore, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateSystemModelInternalModel, _emberDataPrivateSystemPromiseProxies, _emberDataPrivateSystemStore, _emberDataPrivateSystemModel, _emberDataModel, _emberDataPrivateSystemSnapshot, _emberDataAdapter, _emberDataSerializer, _emberDataPrivateSystemDebug, _emberDataPrivateAdaptersErrors, _emberDataPrivateSystemRecordArrays, _emberDataPrivateSystemManyArray, _emberDataPrivateSystemRecordArrayManager, _emberDataPrivateAdapters, _emberDataPrivateAdaptersBuildUrlMixin, _emberDataPrivateSerializers, _emberInflector, _emberDataSerializersEmbeddedRecordsMixin, _emberDataPrivateTransforms, _emberDataRelationships, _emberDataSetupContainer, _emberDataPrivateInstanceInitializersInitializeStoreService, _emberDataPrivateSystemContainerProxy, _emberDataPrivateSystemRelationshipsStateRelationship) { - "use strict"; - - if (_ember["default"].VERSION.match(/^1\.([0-9]|1[0-2])\./)) { - throw new _ember["default"].Error("Ember Data requires at least Ember 1.13.0, but you have " + _ember["default"].VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data."); - } - - if (_ember["default"].VERSION.match(/^1\.13\./)) { - (0, _emberDataPrivateDebug.warn)("Use of Ember Data 2+ with Ember 1.13 is unsupported. Please upgrade your version of Ember to 2.0 or higher.", false, { - id: 'ds.version.ember-1-13' - }); - }_emberDataPrivateCore["default"].Store = _emberDataPrivateSystemStore.Store; - _emberDataPrivateCore["default"].PromiseArray = _emberDataPrivateSystemPromiseProxies.PromiseArray; - _emberDataPrivateCore["default"].PromiseObject = _emberDataPrivateSystemPromiseProxies.PromiseObject; - - _emberDataPrivateCore["default"].PromiseManyArray = _emberDataPrivateSystemPromiseProxies.PromiseManyArray; - - _emberDataPrivateCore["default"].Model = _emberDataModel["default"]; - _emberDataPrivateCore["default"].RootState = _emberDataPrivateSystemModel.RootState; - _emberDataPrivateCore["default"].attr = _emberDataPrivateSystemModel.attr; - _emberDataPrivateCore["default"].Errors = _emberDataPrivateSystemModel.Errors; - - _emberDataPrivateCore["default"].InternalModel = _emberDataPrivateSystemModelInternalModel["default"]; - _emberDataPrivateCore["default"].Snapshot = _emberDataPrivateSystemSnapshot["default"]; - - _emberDataPrivateCore["default"].Adapter = _emberDataAdapter["default"]; - - _emberDataPrivateCore["default"].AdapterError = _emberDataPrivateAdaptersErrors.AdapterError; - _emberDataPrivateCore["default"].InvalidError = _emberDataPrivateAdaptersErrors.InvalidError; - _emberDataPrivateCore["default"].TimeoutError = _emberDataPrivateAdaptersErrors.TimeoutError; - _emberDataPrivateCore["default"].AbortError = _emberDataPrivateAdaptersErrors.AbortError; - - _emberDataPrivateCore["default"].errorsHashToArray = _emberDataPrivateAdaptersErrors.errorsHashToArray; - _emberDataPrivateCore["default"].errorsArrayToHash = _emberDataPrivateAdaptersErrors.errorsArrayToHash; - - _emberDataPrivateCore["default"].Serializer = _emberDataSerializer["default"]; - - _emberDataPrivateCore["default"].DebugAdapter = _emberDataPrivateSystemDebug["default"]; - - _emberDataPrivateCore["default"].RecordArray = _emberDataPrivateSystemRecordArrays.RecordArray; - _emberDataPrivateCore["default"].FilteredRecordArray = _emberDataPrivateSystemRecordArrays.FilteredRecordArray; - _emberDataPrivateCore["default"].AdapterPopulatedRecordArray = _emberDataPrivateSystemRecordArrays.AdapterPopulatedRecordArray; - _emberDataPrivateCore["default"].ManyArray = _emberDataPrivateSystemManyArray["default"]; - - _emberDataPrivateCore["default"].RecordArrayManager = _emberDataPrivateSystemRecordArrayManager["default"]; - - _emberDataPrivateCore["default"].RESTAdapter = _emberDataPrivateAdapters.RESTAdapter; - _emberDataPrivateCore["default"].BuildURLMixin = _emberDataPrivateAdaptersBuildUrlMixin["default"]; - - _emberDataPrivateCore["default"].RESTSerializer = _emberDataPrivateSerializers.RESTSerializer; - _emberDataPrivateCore["default"].JSONSerializer = _emberDataPrivateSerializers.JSONSerializer; - - _emberDataPrivateCore["default"].JSONAPIAdapter = _emberDataPrivateAdapters.JSONAPIAdapter; - _emberDataPrivateCore["default"].JSONAPISerializer = _emberDataPrivateSerializers.JSONAPISerializer; - - _emberDataPrivateCore["default"].Transform = _emberDataPrivateTransforms.Transform; - _emberDataPrivateCore["default"].DateTransform = _emberDataPrivateTransforms.DateTransform; - _emberDataPrivateCore["default"].StringTransform = _emberDataPrivateTransforms.StringTransform; - _emberDataPrivateCore["default"].NumberTransform = _emberDataPrivateTransforms.NumberTransform; - _emberDataPrivateCore["default"].BooleanTransform = _emberDataPrivateTransforms.BooleanTransform; - - _emberDataPrivateCore["default"].EmbeddedRecordsMixin = _emberDataSerializersEmbeddedRecordsMixin["default"]; - - _emberDataPrivateCore["default"].belongsTo = _emberDataRelationships.belongsTo; - _emberDataPrivateCore["default"].hasMany = _emberDataRelationships.hasMany; - - _emberDataPrivateCore["default"].Relationship = _emberDataPrivateSystemRelationshipsStateRelationship["default"]; - - _emberDataPrivateCore["default"].ContainerProxy = _emberDataPrivateSystemContainerProxy["default"]; - - _emberDataPrivateCore["default"]._setupContainer = _emberDataSetupContainer["default"]; - _emberDataPrivateCore["default"]._initializeStoreService = _emberDataPrivateInstanceInitializersInitializeStoreService["default"]; - - Object.defineProperty(_emberDataPrivateCore["default"], 'normalizeModelName', { - enumerable: true, - writable: false, - configurable: false, - value: _emberDataPrivateSystemNormalizeModelName["default"] - }); - - _ember["default"].lookup.DS = _emberDataPrivateCore["default"]; - - exports["default"] = _emberDataPrivateCore["default"]; -}); - -/** - Ember Data - @module ember-data - @main ember-data -*/ -define("ember-data/model", ["exports", "ember-data/-private/system/model"], function (exports, _emberDataPrivateSystemModel) { - "use strict"; - - exports["default"] = _emberDataPrivateSystemModel["default"]; -}); -define("ember-data/relationships", ["exports", "ember-data/-private/system/relationships/belongs-to", "ember-data/-private/system/relationships/has-many"], function (exports, _emberDataPrivateSystemRelationshipsBelongsTo, _emberDataPrivateSystemRelationshipsHasMany) { - /** - @module ember-data - */ - - "use strict"; - - exports.belongsTo = _emberDataPrivateSystemRelationshipsBelongsTo["default"]; - exports.hasMany = _emberDataPrivateSystemRelationshipsHasMany["default"]; -}); -define('ember-data/serializer', ['exports', 'ember'], function (exports, _ember) { - /** - @module ember-data - */ - - 'use strict'; - - /** - `DS.Serializer` is an abstract base class that you should override in your - application to customize it for your backend. The minimum set of methods - that you should implement is: - - * `normalizeResponse()` - * `serialize()` - - And you can optionally override the following methods: - - * `normalize()` - - For an example implementation, see - [DS.JSONSerializer](DS.JSONSerializer.html), the included JSON serializer. - - @class Serializer - @namespace DS - @extends Ember.Object - */ - - exports['default'] = _ember['default'].Object.extend({ - - /** - The `store` property is the application's `store` that contains all records. - It's injected as a service. - It can be used to push records from a non flat data structure server - response. - @property store - @type {DS.Store} - @public - */ - - /** - The `normalizeResponse` method is used to normalize a payload from the - server to a JSON-API Document. - http://jsonapi.org/format/#document-structure - @method normalizeResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeResponse: null, - - /** - The `serialize` method is used when a record is saved in order to convert - the record into the form that your external data source expects. - `serialize` takes an optional `options` hash with a single option: - - `includeId`: If this is `true`, `serialize` should include the ID - in the serialized object it builds. - @method serialize - @param {DS.Model} record - @param {Object} [options] - @return {Object} - */ - serialize: null, - - /** - The `normalize` method is used to convert a payload received from your - external data source into the normalized form `store.push()` expects. You - should override this method, munge the hash and return the normalized - payload. - @method normalize - @param {DS.Model} typeClass - @param {Object} hash - @return {Object} - */ - normalize: function normalize(typeClass, hash) { - return hash; - } - - }); -}); -define('ember-data/serializers/embedded-records-mixin', ['exports', 'ember', 'ember-data/-private/debug'], function (exports, _ember, _emberDataPrivateDebug) { - 'use strict'; - - function _toConsumableArray(arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; - } else { - return Array.from(arr); - } - } - - var get = _ember['default'].get; - var set = _ember['default'].set; - var camelize = _ember['default'].String.camelize; - - /** - ## Using Embedded Records - - `DS.EmbeddedRecordsMixin` supports serializing embedded records. - - To set up embedded records, include the mixin when extending a serializer, - then define and configure embedded (model) relationships. - - Below is an example of a per-type serializer (`post` type). - - ```app/serializers/post.js - import DS from 'ember-data'; - - export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { - attrs: { - author: { embedded: 'always' }, - comments: { serialize: 'ids' } - } - }); - ``` - Note that this use of `{ embedded: 'always' }` is unrelated to - the `{ embedded: 'always' }` that is defined as an option on `DS.attr` as part of - defining a model while working with the `ActiveModelSerializer`. Nevertheless, - using `{ embedded: 'always' }` as an option to `DS.attr` is not a valid way to setup - embedded records. - - The `attrs` option for a resource `{ embedded: 'always' }` is shorthand for: - - ```js - { - serialize: 'records', - deserialize: 'records' - } - ``` - - ### Configuring Attrs - - A resource's `attrs` option may be set to use `ids`, `records` or false for the - `serialize` and `deserialize` settings. - - The `attrs` property can be set on the `ApplicationSerializer` or a per-type - serializer. - - In the case where embedded JSON is expected while extracting a payload (reading) - the setting is `deserialize: 'records'`, there is no need to use `ids` when - extracting as that is the default behavior without this mixin if you are using - the vanilla `EmbeddedRecordsMixin`. Likewise, to embed JSON in the payload while - serializing `serialize: 'records'` is the setting to use. There is an option of - not embedding JSON in the serialized payload by using `serialize: 'ids'`. If you - do not want the relationship sent at all, you can use `serialize: false`. - - - ### EmbeddedRecordsMixin defaults - If you do not overwrite `attrs` for a specific relationship, the `EmbeddedRecordsMixin` - will behave in the following way: - - BelongsTo: `{ serialize: 'id', deserialize: 'id' }` - HasMany: `{ serialize: false, deserialize: 'ids' }` - - ### Model Relationships - - Embedded records must have a model defined to be extracted and serialized. Note that - when defining any relationships on your model such as `belongsTo` and `hasMany`, you - should not both specify `async: true` and also indicate through the serializer's - `attrs` attribute that the related model should be embedded for deserialization. - If a model is declared embedded for deserialization (`embedded: 'always'` or `deserialize: 'records'`), - then do not use `async: true`. - - To successfully extract and serialize embedded records the model relationships - must be setup correcty. See the - [defining relationships](/guides/models/defining-models/#toc_defining-relationships) - section of the **Defining Models** guide page. - - Records without an `id` property are not considered embedded records, model - instances must have an `id` property to be used with Ember Data. - - ### Example JSON payloads, Models and Serializers - - **When customizing a serializer it is important to grok what the customizations - are. Please read the docs for the methods this mixin provides, in case you need - to modify it to fit your specific needs.** - - For example review the docs for each method of this mixin: - * [normalize](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_normalize) - * [serializeBelongsTo](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeBelongsTo) - * [serializeHasMany](/api/data/classes/DS.EmbeddedRecordsMixin.html#method_serializeHasMany) - - @class EmbeddedRecordsMixin - @namespace DS - */ - exports['default'] = _ember['default'].Mixin.create({ - - /** - Normalize the record and recursively normalize/extract all the embedded records - while pushing them into the store as they are encountered - A payload with an attr configured for embedded records needs to be extracted: - ```js - { - "post": { - "id": "1" - "title": "Rails is omakase", - "comments": [{ - "id": "1", - "body": "Rails is unagi" - }, { - "id": "2", - "body": "Omakase O_o" - }] - } - } - ``` - @method normalize - @param {DS.Model} typeClass - @param {Object} hash to be normalized - @param {String} prop the hash has been referenced by - @return {Object} the normalized hash - **/ - normalize: function normalize(typeClass, hash, prop) { - var normalizedHash = this._super(typeClass, hash, prop); - return this._extractEmbeddedRecords(this, this.store, typeClass, normalizedHash); - }, - - keyForRelationship: function keyForRelationship(key, typeClass, method) { - if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) { - return this.keyForAttribute(key, method); - } else { - return this._super(key, typeClass, method) || key; - } - }, - - /** - Serialize `belongsTo` relationship when it is configured as an embedded object. - This example of an author model belongs to a post model: - ```js - Post = DS.Model.extend({ - title: DS.attr('string'), - body: DS.attr('string'), - author: DS.belongsTo('author') - }); - Author = DS.Model.extend({ - name: DS.attr('string'), - post: DS.belongsTo('post') - }); - ``` - Use a custom (type) serializer for the post model to configure embedded author - ```app/serializers/post.js - import DS from 'ember-data; - export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { - attrs: { - author: { embedded: 'always' } - } - }) - ``` - A payload with an attribute configured for embedded records can serialize - the records together under the root attribute's payload: - ```js - { - "post": { - "id": "1" - "title": "Rails is omakase", - "author": { - "id": "2" - "name": "dhh" - } - } - } - ``` - @method serializeBelongsTo - @param {DS.Snapshot} snapshot - @param {Object} json - @param {Object} relationship - */ - serializeBelongsTo: function serializeBelongsTo(snapshot, json, relationship) { - var attr = relationship.key; - if (this.noSerializeOptionSpecified(attr)) { - this._super(snapshot, json, relationship); - return; - } - var includeIds = this.hasSerializeIdsOption(attr); - var includeRecords = this.hasSerializeRecordsOption(attr); - var embeddedSnapshot = snapshot.belongsTo(attr); - var key; - if (includeIds) { - key = this.keyForRelationship(attr, relationship.kind, 'serialize'); - if (!embeddedSnapshot) { - json[key] = null; - } else { - json[key] = embeddedSnapshot.id; - - if (relationship.options.polymorphic) { - this.serializePolymorphicType(snapshot, json, relationship); - } - } - } else if (includeRecords) { - this._serializeEmbeddedBelongsTo(snapshot, json, relationship); - } - }, - - _serializeEmbeddedBelongsTo: function _serializeEmbeddedBelongsTo(snapshot, json, relationship) { - var embeddedSnapshot = snapshot.belongsTo(relationship.key); - var serializedKey = this._getMappedKey(relationship.key, snapshot.type); - if (serializedKey === relationship.key && this.keyForRelationship) { - serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); - } - - if (!embeddedSnapshot) { - json[serializedKey] = null; - } else { - json[serializedKey] = embeddedSnapshot.record.serialize({ includeId: true }); - this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[serializedKey]); - - if (relationship.options.polymorphic) { - this.serializePolymorphicType(snapshot, json, relationship); - } - } - }, - - /** - Serialize `hasMany` relationship when it is configured as embedded objects. - This example of a post model has many comments: - ```js - Post = DS.Model.extend({ - title: DS.attr('string'), - body: DS.attr('string'), - comments: DS.hasMany('comment') - }); - Comment = DS.Model.extend({ - body: DS.attr('string'), - post: DS.belongsTo('post') - }); - ``` - Use a custom (type) serializer for the post model to configure embedded comments - ```app/serializers/post.js - import DS from 'ember-data; - export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { - attrs: { - comments: { embedded: 'always' } - } - }) - ``` - A payload with an attribute configured for embedded records can serialize - the records together under the root attribute's payload: - ```js - { - "post": { - "id": "1" - "title": "Rails is omakase", - "body": "I want this for my ORM, I want that for my template language..." - "comments": [{ - "id": "1", - "body": "Rails is unagi" - }, { - "id": "2", - "body": "Omakase O_o" - }] - } - } - ``` - The attrs options object can use more specific instruction for extracting and - serializing. When serializing, an option to embed `ids` or `records` can be set. - When extracting the only option is `records`. - So `{ embedded: 'always' }` is shorthand for: - `{ serialize: 'records', deserialize: 'records' }` - To embed the `ids` for a related object (using a hasMany relationship): - ```app/serializers/post.js - import DS from 'ember-data; - export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { - attrs: { - comments: { serialize: 'ids', deserialize: 'records' } - } - }) - ``` - ```js - { - "post": { - "id": "1" - "title": "Rails is omakase", - "body": "I want this for my ORM, I want that for my template language..." - "comments": ["1", "2"] - } - } - ``` - @method serializeHasMany - @param {DS.Snapshot} snapshot - @param {Object} json - @param {Object} relationship - */ - serializeHasMany: function serializeHasMany(snapshot, json, relationship) { - var attr = relationship.key; - if (this.noSerializeOptionSpecified(attr)) { - this._super(snapshot, json, relationship); - return; - } - var includeIds = this.hasSerializeIdsOption(attr); - var includeRecords = this.hasSerializeRecordsOption(attr); - if (includeIds) { - var serializedKey = this.keyForRelationship(attr, relationship.kind, 'serialize'); - json[serializedKey] = snapshot.hasMany(attr, { ids: true }); - } else if (includeRecords) { - this._serializeEmbeddedHasMany(snapshot, json, relationship); - } - }, - - _serializeEmbeddedHasMany: function _serializeEmbeddedHasMany(snapshot, json, relationship) { - var serializedKey = this._getMappedKey(relationship.key, snapshot.type); - if (serializedKey === relationship.key && this.keyForRelationship) { - serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); - } - - (0, _emberDataPrivateDebug.warn)('The embedded relationship \'' + serializedKey + '\' is undefined for \'' + snapshot.modelName + '\' with id \'' + snapshot.id + '\'. Please include it in your original payload.', _ember['default'].typeOf(snapshot.hasMany(relationship.key)) !== 'undefined', { id: 'ds.serializer.embedded-relationship-undefined' }); - - json[serializedKey] = this._generateSerializedHasMany(snapshot, relationship); - }, - - /* - Returns an array of embedded records serialized to JSON - */ - _generateSerializedHasMany: function _generateSerializedHasMany(snapshot, relationship) { - var hasMany = snapshot.hasMany(relationship.key); - var manyArray = _ember['default'].A(hasMany); - var ret = new Array(manyArray.length); - - for (var i = 0; i < manyArray.length; i++) { - var embeddedSnapshot = manyArray[i]; - var embeddedJson = embeddedSnapshot.record.serialize({ includeId: true }); - this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson); - ret[i] = embeddedJson; - } - - return ret; - }, - - /** - When serializing an embedded record, modify the property (in the json payload) - that refers to the parent record (foreign key for relationship). - Serializing a `belongsTo` relationship removes the property that refers to the - parent record - Serializing a `hasMany` relationship does not remove the property that refers to - the parent record. - @method removeEmbeddedForeignKey - @param {DS.Snapshot} snapshot - @param {DS.Snapshot} embeddedSnapshot - @param {Object} relationship - @param {Object} json - */ - removeEmbeddedForeignKey: function removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json) { - if (relationship.kind === 'hasMany') { - return; - } else if (relationship.kind === 'belongsTo') { - var parentRecord = snapshot.type.inverseFor(relationship.key, this.store); - if (parentRecord) { - var name = parentRecord.name; - var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName); - var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize'); - if (parentKey) { - delete json[parentKey]; - } - } - } - }, - - // checks config for attrs option to embedded (always) - serialize and deserialize - hasEmbeddedAlwaysOption: function hasEmbeddedAlwaysOption(attr) { - var option = this.attrsOption(attr); - return option && option.embedded === 'always'; - }, - - // checks config for attrs option to serialize ids - hasSerializeRecordsOption: function hasSerializeRecordsOption(attr) { - var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); - var option = this.attrsOption(attr); - return alwaysEmbed || option && option.serialize === 'records'; - }, - - // checks config for attrs option to serialize records - hasSerializeIdsOption: function hasSerializeIdsOption(attr) { - var option = this.attrsOption(attr); - return option && (option.serialize === 'ids' || option.serialize === 'id'); - }, - - // checks config for attrs option to serialize records - noSerializeOptionSpecified: function noSerializeOptionSpecified(attr) { - var option = this.attrsOption(attr); - return !(option && (option.serialize || option.embedded)); - }, - - // checks config for attrs option to deserialize records - // a defined option object for a resource is treated the same as - // `deserialize: 'records'` - hasDeserializeRecordsOption: function hasDeserializeRecordsOption(attr) { - var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); - var option = this.attrsOption(attr); - return alwaysEmbed || option && option.deserialize === 'records'; - }, - - attrsOption: function attrsOption(attr) { - var attrs = this.get('attrs'); - return attrs && (attrs[camelize(attr)] || attrs[attr]); - }, - - /** - @method _extractEmbeddedRecords - @private - */ - _extractEmbeddedRecords: function _extractEmbeddedRecords(serializer, store, typeClass, partial) { - var _this = this; - - typeClass.eachRelationship(function (key, relationship) { - if (serializer.hasDeserializeRecordsOption(key)) { - if (relationship.kind === "hasMany") { - _this._extractEmbeddedHasMany(store, key, partial, relationship); - } - if (relationship.kind === "belongsTo") { - _this._extractEmbeddedBelongsTo(store, key, partial, relationship); - } - } - }); - return partial; - }, - - /** - @method _extractEmbeddedHasMany - @private - */ - _extractEmbeddedHasMany: function _extractEmbeddedHasMany(store, key, hash, relationshipMeta) { - var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); - - if (!relationshipHash) { - return; - } - - var hasMany = new Array(relationshipHash.length); - - for (var i = 0; i < relationshipHash.length; i++) { - var item = relationshipHash[i]; - - var _normalizeEmbeddedRelationship2 = this._normalizeEmbeddedRelationship(store, relationshipMeta, item); - - var data = _normalizeEmbeddedRelationship2.data; - var included = _normalizeEmbeddedRelationship2.included; - - hash.included = hash.included || []; - hash.included.push(data); - if (included) { - var _hash$included; - - (_hash$included = hash.included).push.apply(_hash$included, _toConsumableArray(included)); - } - - hasMany[i] = { id: data.id, type: data.type }; - } - - var relationship = { data: hasMany }; - set(hash, 'data.relationships.' + key, relationship); - }, - - /** - @method _extractEmbeddedBelongsTo - @private - */ - _extractEmbeddedBelongsTo: function _extractEmbeddedBelongsTo(store, key, hash, relationshipMeta) { - var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); - if (!relationshipHash) { - return; - } - - var _normalizeEmbeddedRelationship3 = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash); - - var data = _normalizeEmbeddedRelationship3.data; - var included = _normalizeEmbeddedRelationship3.included; - - hash.included = hash.included || []; - hash.included.push(data); - if (included) { - var _hash$included2; - - (_hash$included2 = hash.included).push.apply(_hash$included2, _toConsumableArray(included)); - } - - var belongsTo = { id: data.id, type: data.type }; - var relationship = { data: belongsTo }; - - set(hash, 'data.relationships.' + key, relationship); - }, - - /** - @method _normalizeEmbeddedRelationship - @private - */ - _normalizeEmbeddedRelationship: function _normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash) { - var modelName = relationshipMeta.type; - if (relationshipMeta.options.polymorphic) { - modelName = relationshipHash.type; - } - var modelClass = store.modelFor(modelName); - var serializer = store.serializerFor(modelName); - - return serializer.normalize(modelClass, relationshipHash, null); - } - }); -}); -define('ember-data/serializers/json-api', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializers/json', 'ember-data/-private/system/normalize-model-name', 'ember-inflector'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializersJson, _emberDataPrivateSystemNormalizeModelName, _emberInflector) { - /** - @module ember-data - */ - - 'use strict'; - - var dasherize = _ember['default'].String.dasherize; - - /** - Ember Data 2.0 Serializer: - - In Ember Data a Serializer is used to serialize and deserialize - records when they are transferred in and out of an external source. - This process involves normalizing property names, transforming - attribute values and serializing relationships. - - `JSONAPISerializer` supports the http://jsonapi.org/ spec and is the - serializer recommended by Ember Data. - - This serializer normalizes a JSON API payload that looks like: - - ```js - - // models/player.js - import DS from "ember-data"; - - export default DS.Model.extend({ - name: DS.attr(), - skill: DS.attr(), - gamesPlayed: DS.attr(), - club: DS.belongsTo('club') - }); - - // models/club.js - import DS from "ember-data"; - - export default DS.Model.extend({ - name: DS.attr(), - location: DS.attr(), - players: DS.hasMany('player') - }); - ``` - - ```js - - { - "data": [ - { - "attributes": { - "name": "Benfica", - "location": "Portugal" - }, - "id": "1", - "relationships": { - "players": { - "data": [ - { - "id": "3", - "type": "players" - } - ] - } - }, - "type": "clubs" - } - ], - "included": [ - { - "attributes": { - "name": "Eusebio Silva Ferreira", - "skill": "Rocket shot", - "games-played": 431 - }, - "id": "3", - "relationships": { - "club": { - "data": { - "id": "1", - "type": "clubs" - } - } - }, - "type": "players" - } - ] - } - ``` - - to the format that the Ember Data store expects. - - @class JSONAPISerializer - @namespace DS - @extends DS.JSONSerializer - */ - var JSONAPISerializer = _emberDataSerializersJson['default'].extend({ - - /** - @method _normalizeDocumentHelper - @param {Object} documentHash - @return {Object} - @private - */ - _normalizeDocumentHelper: function _normalizeDocumentHelper(documentHash) { - - if (_ember['default'].typeOf(documentHash.data) === 'object') { - documentHash.data = this._normalizeResourceHelper(documentHash.data); - } else if (Array.isArray(documentHash.data)) { - var ret = new Array(documentHash.data.length); - - for (var i = 0; i < documentHash.data.length; i++) { - var data = documentHash.data[i]; - ret[i] = this._normalizeResourceHelper(data); - } - - documentHash.data = ret; - } - - if (Array.isArray(documentHash.included)) { - var ret = new Array(documentHash.included.length); - - for (var i = 0; i < documentHash.included.length; i++) { - var included = documentHash.included[i]; - ret[i] = this._normalizeResourceHelper(included); - } - - documentHash.included = ret; - } - - return documentHash; - }, - - /** - @method _normalizeRelationshipDataHelper - @param {Object} relationshipDataHash - @return {Object} - @private - */ - _normalizeRelationshipDataHelper: function _normalizeRelationshipDataHelper(relationshipDataHash) { - var type = this.modelNameFromPayloadKey(relationshipDataHash.type); - relationshipDataHash.type = type; - return relationshipDataHash; - }, - - /** - @method _normalizeResourceHelper - @param {Object} resourceHash - @return {Object} - @private - */ - _normalizeResourceHelper: function _normalizeResourceHelper(resourceHash) { - (0, _emberDataPrivateDebug.assert)(this.warnMessageForUndefinedType(), !_ember['default'].isNone(resourceHash.type), { - id: 'ds.serializer.type-is-undefined' - }); - - var modelName = this.modelNameFromPayloadKey(resourceHash.type); - - if (!this.store._hasModelFor(modelName)) { - (0, _emberDataPrivateDebug.warn)(this.warnMessageNoModelForType(modelName, resourceHash.type), false, { - id: 'ds.serializer.model-for-type-missing' - }); - return null; - } - - var modelClass = this.store.modelFor(modelName); - var serializer = this.store.serializerFor(modelName); - - var _serializer$normalize = serializer.normalize(modelClass, resourceHash); - - var data = _serializer$normalize.data; - - return data; - }, - - /** - @method pushPayload - @param {DS.Store} store - @param {Object} payload - */ - pushPayload: function pushPayload(store, payload) { - var normalizedPayload = this._normalizeDocumentHelper(payload); - store.push(normalizedPayload); - }, - - /** - @method _normalizeResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @param {Boolean} isSingle - @return {Object} JSON-API Document - @private - */ - _normalizeResponse: function _normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) { - var normalizedPayload = this._normalizeDocumentHelper(payload); - return normalizedPayload; - }, - - /** - @method extractAttributes - @param {DS.Model} modelClass - @param {Object} resourceHash - @return {Object} - */ - extractAttributes: function extractAttributes(modelClass, resourceHash) { - var _this = this; - - var attributes = {}; - - if (resourceHash.attributes) { - modelClass.eachAttribute(function (key) { - var attributeKey = _this.keyForAttribute(key, 'deserialize'); - if (resourceHash.attributes.hasOwnProperty(attributeKey)) { - attributes[key] = resourceHash.attributes[attributeKey]; - } - }); - } - - return attributes; - }, - - /** - @method extractRelationship - @param {Object} relationshipHash - @return {Object} - */ - extractRelationship: function extractRelationship(relationshipHash) { - - if (_ember['default'].typeOf(relationshipHash.data) === 'object') { - relationshipHash.data = this._normalizeRelationshipDataHelper(relationshipHash.data); - } - - if (Array.isArray(relationshipHash.data)) { - var ret = new Array(relationshipHash.data.length); - - for (var i = 0; i < relationshipHash.data.length; i++) { - var data = relationshipHash.data[i]; - ret[i] = this._normalizeRelationshipDataHelper(data); - } - - relationshipHash.data = ret; - } - - return relationshipHash; - }, - - /** - @method extractRelationships - @param {Object} modelClass - @param {Object} resourceHash - @return {Object} - */ - extractRelationships: function extractRelationships(modelClass, resourceHash) { - var _this2 = this; - - var relationships = {}; - - if (resourceHash.relationships) { - modelClass.eachRelationship(function (key, relationshipMeta) { - var relationshipKey = _this2.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); - if (resourceHash.relationships.hasOwnProperty(relationshipKey)) { - - var relationshipHash = resourceHash.relationships[relationshipKey]; - relationships[key] = _this2.extractRelationship(relationshipHash); - } - }); - } - - return relationships; - }, - - /** - @method _extractType - @param {DS.Model} modelClass - @param {Object} resourceHash - @return {String} - @private - */ - _extractType: function _extractType(modelClass, resourceHash) { - return this.modelNameFromPayloadKey(resourceHash.type); - }, - - /** - @method modelNameFromPayloadKey - @param {String} key - @return {String} the model's modelName - */ - modelNameFromPayloadKey: function modelNameFromPayloadKey(key) { - return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName['default'])(key)); - }, - - /** - @method payloadKeyFromModelName - @param {String} modelName - @return {String} - */ - payloadKeyFromModelName: function payloadKeyFromModelName(modelName) { - return (0, _emberInflector.pluralize)(modelName); - }, - - /** - @method normalize - @param {DS.Model} modelClass - @param {Object} resourceHash the resource hash from the adapter - @return {Object} the normalized resource hash - */ - normalize: function normalize(modelClass, resourceHash) { - if (resourceHash.attributes) { - this.normalizeUsingDeclaredMapping(modelClass, resourceHash.attributes); - } - - if (resourceHash.relationships) { - this.normalizeUsingDeclaredMapping(modelClass, resourceHash.relationships); - } - - var data = { - id: this.extractId(modelClass, resourceHash), - type: this._extractType(modelClass, resourceHash), - attributes: this.extractAttributes(modelClass, resourceHash), - relationships: this.extractRelationships(modelClass, resourceHash) - }; - - this.applyTransforms(modelClass, data.attributes); - - return { data: data }; - }, - - /** - `keyForAttribute` can be used to define rules for how to convert an - attribute name in your model to a key in your JSON. - By default `JSONAPISerializer` follows the format used on the examples of - http://jsonapi.org/format and uses dashes as the word separator in the JSON - attribute keys. - This behaviour can be easily customized by extending this method. - Example - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.JSONAPISerializer.extend({ - keyForAttribute: function(attr, method) { - return Ember.String.dasherize(attr).toUpperCase(); - } - }); - ``` - @method keyForAttribute - @param {String} key - @param {String} method - @return {String} normalized key - */ - keyForAttribute: function keyForAttribute(key, method) { - return dasherize(key); - }, - - /** - `keyForRelationship` can be used to define a custom key when - serializing and deserializing relationship properties. - By default `JSONAPISerializer` follows the format used on the examples of - http://jsonapi.org/format and uses dashes as word separators in - relationship properties. - This behaviour can be easily customized by extending this method. - Example - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.JSONAPISerializer.extend({ - keyForRelationship: function(key, relationship, method) { - return Ember.String.underscore(key); - } - }); - ``` - @method keyForRelationship - @param {String} key - @param {String} typeClass - @param {String} method - @return {String} normalized key - */ - keyForRelationship: function keyForRelationship(key, typeClass, method) { - return dasherize(key); - }, - - /** - @method serialize - @param {DS.Snapshot} snapshot - @param {Object} options - @return {Object} json - */ - serialize: function serialize(snapshot, options) { - var data = this._super.apply(this, arguments); - data.type = this.payloadKeyFromModelName(snapshot.modelName); - return { data: data }; - }, - - /** - @method serializeAttribute - @param {DS.Snapshot} snapshot - @param {Object} json - @param {String} key - @param {Object} attribute - */ - serializeAttribute: function serializeAttribute(snapshot, json, key, attribute) { - var type = attribute.type; - - if (this._canSerialize(key)) { - json.attributes = json.attributes || {}; - - var value = snapshot.attr(key); - if (type) { - var transform = this.transformFor(type); - value = transform.serialize(value); - } - - var payloadKey = this._getMappedKey(key, snapshot.type); - - if (payloadKey === key) { - payloadKey = this.keyForAttribute(key, 'serialize'); - } - - json.attributes[payloadKey] = value; - } - }, - - /** - @method serializeBelongsTo - @param {DS.Snapshot} snapshot - @param {Object} json - @param {Object} relationship - */ - serializeBelongsTo: function serializeBelongsTo(snapshot, json, relationship) { - var key = relationship.key; - - if (this._canSerialize(key)) { - var belongsTo = snapshot.belongsTo(key); - if (belongsTo !== undefined) { - - json.relationships = json.relationships || {}; - - var payloadKey = this._getMappedKey(key, snapshot.type); - if (payloadKey === key) { - payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize'); - } - - var data = null; - if (belongsTo) { - data = { - type: this.payloadKeyFromModelName(belongsTo.modelName), - id: belongsTo.id - }; - } - - json.relationships[payloadKey] = { data: data }; - } - } - }, - - /** - @method serializeHasMany - @param {DS.Snapshot} snapshot - @param {Object} json - @param {Object} relationship - */ - serializeHasMany: function serializeHasMany(snapshot, json, relationship) { - var key = relationship.key; - - if (this._shouldSerializeHasMany(snapshot, key, relationship)) { - var hasMany = snapshot.hasMany(key); - if (hasMany !== undefined) { - - json.relationships = json.relationships || {}; - - var payloadKey = this._getMappedKey(key, snapshot.type); - if (payloadKey === key && this.keyForRelationship) { - payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize'); - } - - var data = new Array(hasMany.length); - - for (var i = 0; i < hasMany.length; i++) { - var item = hasMany[i]; - data[i] = { - type: this.payloadKeyFromModelName(item.modelName), - id: item.id - }; - } - - json.relationships[payloadKey] = { data: data }; - } - } - } - }); - - (0, _emberDataPrivateDebug.runInDebug)(function () { - JSONAPISerializer.reopen({ - warnMessageForUndefinedType: function warnMessageForUndefinedType() { - return 'Encountered a resource object with an undefined type (resolved resource using ' + this.constructor.toString() + ')'; - }, - warnMessageNoModelForType: function warnMessageNoModelForType(modelName, originalType) { - return 'Encountered a resource object with type "' + originalType + '", but no model was found for model name "' + modelName + '" (resolved model name using ' + this.constructor.toString() + '.modelNameFromPayloadKey("' + originalType + '"))'; - } - }); - }); - - exports['default'] = JSONAPISerializer; -}); -define('ember-data/serializers/json', ['exports', 'ember', 'ember-data/-private/debug', 'ember-data/serializer', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/utils', 'ember-data/-private/adapters/errors'], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializer, _emberDataPrivateSystemCoerceId, _emberDataPrivateSystemNormalizeModelName, _emberDataPrivateUtils, _emberDataPrivateAdaptersErrors) { - 'use strict'; - - function _toConsumableArray(arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; - } else { - return Array.from(arr); - } - } - - var get = _ember['default'].get; - var isNone = _ember['default'].isNone; - var merge = _ember['default'].merge; - - /** - Ember Data 2.0 Serializer: - - In Ember Data a Serializer is used to serialize and deserialize - records when they are transferred in and out of an external source. - This process involves normalizing property names, transforming - attribute values and serializing relationships. - - By default, Ember Data uses and recommends the `JSONAPISerializer`. - - `JSONSerializer` is useful for simpler or legacy backends that may - not support the http://jsonapi.org/ spec. - - For example, given the following `User` model and JSON payload: - - ```app/models/user.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - friends: DS.hasMany('user'), - house: DS.belongsTo('location'), - - name: DS.attr('string') - }); - ``` - - ```js - { - id: 1, - name: 'Sebastian', - friends: [3, 4], - links: { - house: '/houses/lefkada' - } - } - ``` - - `JSONSerializer` will normalize the JSON payload to the JSON API format that the - Ember Data store expects. - - You can customize how JSONSerializer processes its payload by passing options in - the `attrs` hash or by subclassing the `JSONSerializer` and overriding hooks: - - - To customize how a single record is normalized, use the `normalize` hook. - - To customize how `JSONSerializer` normalizes the whole server response, use the - `normalizeResponse` hook. - - To customize how `JSONSerializer` normalizes a specific response from the server, - use one of the many specific `normalizeResponse` hooks. - - To customize how `JSONSerializer` normalizes your id, attributes or relationships, - use the `extractId`, `extractAttributes` and `extractRelationships` hooks. - - The `JSONSerializer` normalization process follows these steps: - - - `normalizeResponse` - entry method to the serializer. - - `normalizeCreateRecordResponse` - a `normalizeResponse` for a specific operation is called. - - `normalizeSingleResponse`|`normalizeArrayResponse` - for methods like `createRecord` we expect - a single record back, while for methods like `findAll` we expect multiple methods back. - - `normalize` - `normalizeArray` iterates and calls `normalize` for each of its records while `normalizeSingle` - calls it once. This is the method you most likely want to subclass. - - `extractId` | `extractAttributes` | `extractRelationships` - `normalize` delegates to these methods to - turn the record payload into the JSON API format. - - @class JSONSerializer - @namespace DS - @extends DS.Serializer - */ - exports['default'] = _emberDataSerializer['default'].extend({ - - /** - The `primaryKey` is used when serializing and deserializing - data. Ember Data always uses the `id` property to store the id of - the record. The external source may not always follow this - convention. In these cases it is useful to override the - `primaryKey` property to match the `primaryKey` of your external - store. - Example - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - primaryKey: '_id' - }); - ``` - @property primaryKey - @type {String} - @default 'id' - */ - primaryKey: 'id', - - /** - The `attrs` object can be used to declare a simple mapping between - property names on `DS.Model` records and payload keys in the - serialized JSON object representing the record. An object with the - property `key` can also be used to designate the attribute's key on - the response payload. - Example - ```app/models/person.js - import DS from 'ember-data'; - export default DS.Model.extend({ - firstName: DS.attr('string'), - lastName: DS.attr('string'), - occupation: DS.attr('string'), - admin: DS.attr('boolean') - }); - ``` - ```app/serializers/person.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - attrs: { - admin: 'is_admin', - occupation: { key: 'career' } - } - }); - ``` - You can also remove attributes by setting the `serialize` key to - `false` in your mapping object. - Example - ```app/serializers/person.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - attrs: { - admin: { serialize: false }, - occupation: { key: 'career' } - } - }); - ``` - When serialized: - ```javascript - { - "firstName": "Harry", - "lastName": "Houdini", - "career": "magician" - } - ``` - Note that the `admin` is now not included in the payload. - @property attrs - @type {Object} - */ - mergedProperties: ['attrs'], - - /** - Given a subclass of `DS.Model` and a JSON object this method will - iterate through each attribute of the `DS.Model` and invoke the - `DS.Transform#deserialize` method on the matching property of the - JSON object. This method is typically called after the - serializer's `normalize` method. - @method applyTransforms - @private - @param {DS.Model} typeClass - @param {Object} data The data to transform - @return {Object} data The transformed data object - */ - applyTransforms: function applyTransforms(typeClass, data) { - var _this = this; - - typeClass.eachTransformedAttribute(function (key, typeClass) { - if (!data.hasOwnProperty(key)) { - return; - } - - var transform = _this.transformFor(typeClass); - data[key] = transform.deserialize(data[key]); - }); - - return data; - }, - - /** - The `normalizeResponse` method is used to normalize a payload from the - server to a JSON-API Document. - http://jsonapi.org/format/#document-structure - This method delegates to a more specific normalize method based on - the `requestType`. - To override this method with a custom one, make sure to call - `return this._super(store, primaryModelClass, payload, id, requestType)` with your - pre-processed data. - Here's an example of using `normalizeResponse` manually: - ```javascript - socket.on('message', function(message) { - var data = message.data; - var modelClass = store.modelFor(data.modelName); - var serializer = store.serializerFor(data.modelName); - var json = serializer.normalizeSingleResponse(store, modelClass, data, data.id); - store.push(normalized); - }); - ``` - @method normalizeResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeResponse: function normalizeResponse(store, primaryModelClass, payload, id, requestType) { - switch (requestType) { - case 'findRecord': - return this.normalizeFindRecordResponse.apply(this, arguments); - case 'queryRecord': - return this.normalizeQueryRecordResponse.apply(this, arguments); - case 'findAll': - return this.normalizeFindAllResponse.apply(this, arguments); - case 'findBelongsTo': - return this.normalizeFindBelongsToResponse.apply(this, arguments); - case 'findHasMany': - return this.normalizeFindHasManyResponse.apply(this, arguments); - case 'findMany': - return this.normalizeFindManyResponse.apply(this, arguments); - case 'query': - return this.normalizeQueryResponse.apply(this, arguments); - case 'createRecord': - return this.normalizeCreateRecordResponse.apply(this, arguments); - case 'deleteRecord': - return this.normalizeDeleteRecordResponse.apply(this, arguments); - case 'updateRecord': - return this.normalizeUpdateRecordResponse.apply(this, arguments); - } - }, - - /** - @method normalizeFindRecordResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeFindRecordResponse: function normalizeFindRecordResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeSingleResponse.apply(this, arguments); - }, - - /** - @method normalizeQueryRecordResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeQueryRecordResponse: function normalizeQueryRecordResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeSingleResponse.apply(this, arguments); - }, - - /** - @method normalizeFindAllResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeFindAllResponse: function normalizeFindAllResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeArrayResponse.apply(this, arguments); - }, - - /** - @method normalizeFindBelongsToResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeFindBelongsToResponse: function normalizeFindBelongsToResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeSingleResponse.apply(this, arguments); - }, - - /** - @method normalizeFindHasManyResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeFindHasManyResponse: function normalizeFindHasManyResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeArrayResponse.apply(this, arguments); - }, - - /** - @method normalizeFindManyResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeFindManyResponse: function normalizeFindManyResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeArrayResponse.apply(this, arguments); - }, - - /** - @method normalizeQueryResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeQueryResponse: function normalizeQueryResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeArrayResponse.apply(this, arguments); - }, - - /** - @method normalizeCreateRecordResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeCreateRecordResponse: function normalizeCreateRecordResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeSaveResponse.apply(this, arguments); - }, - - /** - @method normalizeDeleteRecordResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeDeleteRecordResponse: function normalizeDeleteRecordResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeSaveResponse.apply(this, arguments); - }, - - /** - @method normalizeUpdateRecordResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeUpdateRecordResponse: function normalizeUpdateRecordResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeSaveResponse.apply(this, arguments); - }, - - /** - @method normalizeSaveResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeSaveResponse: function normalizeSaveResponse(store, primaryModelClass, payload, id, requestType) { - return this.normalizeSingleResponse.apply(this, arguments); - }, - - /** - @method normalizeSingleResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeSingleResponse: function normalizeSingleResponse(store, primaryModelClass, payload, id, requestType) { - return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true); - }, - - /** - @method normalizeArrayResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @return {Object} JSON-API Document - */ - normalizeArrayResponse: function normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) { - return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, false); - }, - - /** - @method _normalizeResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @param {Boolean} isSingle - @return {Object} JSON-API Document - @private - */ - _normalizeResponse: function _normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) { - var documentHash = { - data: null, - included: [] - }; - - var meta = this.extractMeta(store, primaryModelClass, payload); - if (meta) { - (0, _emberDataPrivateDebug.assert)('The `meta` returned from `extractMeta` has to be an object, not "' + _ember['default'].typeOf(meta) + '".', _ember['default'].typeOf(meta) === 'object'); - documentHash.meta = meta; - } - - if (isSingle) { - var _normalize = this.normalize(primaryModelClass, payload); - - var data = _normalize.data; - var included = _normalize.included; - - documentHash.data = data; - if (included) { - documentHash.included = included; - } - } else { - var ret = new Array(payload.length); - for (var i = 0, l = payload.length; i < l; i++) { - var item = payload[i]; - - var _normalize2 = this.normalize(primaryModelClass, item); - - var data = _normalize2.data; - var included = _normalize2.included; - - if (included) { - var _documentHash$included; - - (_documentHash$included = documentHash.included).push.apply(_documentHash$included, _toConsumableArray(included)); - } - ret[i] = data; - } - - documentHash.data = ret; - } - - return documentHash; - }, - - /** - Normalizes a part of the JSON payload returned by - the server. You should override this method, munge the hash - and call super if you have generic normalization to do. - It takes the type of the record that is being normalized - (as a DS.Model class), the property where the hash was - originally found, and the hash to normalize. - You can use this method, for example, to normalize underscored keys to camelized - or other general-purpose normalizations. - Example - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - normalize: function(typeClass, hash) { - var fields = Ember.get(typeClass, 'fields'); - fields.forEach(function(field) { - var payloadField = Ember.String.underscore(field); - if (field === payloadField) { return; } - hash[field] = hash[payloadField]; - delete hash[payloadField]; - }); - return this._super.apply(this, arguments); - } - }); - ``` - @method normalize - @param {DS.Model} typeClass - @param {Object} hash - @return {Object} - */ - normalize: function normalize(modelClass, resourceHash) { - var data = null; - - if (resourceHash) { - this.normalizeUsingDeclaredMapping(modelClass, resourceHash); - - data = { - id: this.extractId(modelClass, resourceHash), - type: modelClass.modelName, - attributes: this.extractAttributes(modelClass, resourceHash), - relationships: this.extractRelationships(modelClass, resourceHash) - }; - - this.applyTransforms(modelClass, data.attributes); - } - - return { data: data }; - }, - - /** - Returns the resource's ID. - @method extractId - @param {Object} modelClass - @param {Object} resourceHash - @return {String} - */ - extractId: function extractId(modelClass, resourceHash) { - var primaryKey = get(this, 'primaryKey'); - var id = resourceHash[primaryKey]; - return (0, _emberDataPrivateSystemCoerceId['default'])(id); - }, - - /** - Returns the resource's attributes formatted as a JSON-API "attributes object". - http://jsonapi.org/format/#document-resource-object-attributes - @method extractAttributes - @param {Object} modelClass - @param {Object} resourceHash - @return {Object} - */ - extractAttributes: function extractAttributes(modelClass, resourceHash) { - var _this2 = this; - - var attributeKey; - var attributes = {}; - - modelClass.eachAttribute(function (key) { - attributeKey = _this2.keyForAttribute(key, 'deserialize'); - if (resourceHash.hasOwnProperty(attributeKey)) { - attributes[key] = resourceHash[attributeKey]; - } - }); - - return attributes; - }, - - /** - Returns a relationship formatted as a JSON-API "relationship object". - http://jsonapi.org/format/#document-resource-object-relationships - @method extractRelationship - @param {Object} relationshipModelName - @param {Object} relationshipHash - @return {Object} - */ - extractRelationship: function extractRelationship(relationshipModelName, relationshipHash) { - if (_ember['default'].isNone(relationshipHash)) { - return null; - } - /* - When `relationshipHash` is an object it usually means that the relationship - is polymorphic. It could however also be embedded resources that the - EmbeddedRecordsMixin has be able to process. - */ - if (_ember['default'].typeOf(relationshipHash) === 'object') { - if (relationshipHash.id) { - relationshipHash.id = (0, _emberDataPrivateSystemCoerceId['default'])(relationshipHash.id); - } - - var modelClass = this.store.modelFor(relationshipModelName); - if (relationshipHash.type && !(0, _emberDataPrivateUtils.modelHasAttributeOrRelationshipNamedType)(modelClass)) { - relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type); - } - return relationshipHash; - } - return { id: (0, _emberDataPrivateSystemCoerceId['default'])(relationshipHash), type: relationshipModelName }; - }, - - /** - Returns a polymorphic relationship formatted as a JSON-API "relationship object". - http://jsonapi.org/format/#document-resource-object-relationships - `relationshipOptions` is a hash which contains more information about the - polymorphic relationship which should be extracted: - - `resourceHash` complete hash of the resource the relationship should be - extracted from - - `relationshipKey` key under which the value for the relationship is - extracted from the resourceHash - - `relationshipMeta` meta information about the relationship - @method extractPolymorphicRelationship - @param {Object} relationshipModelName - @param {Object} relationshipHash - @param {Object} relationshipOptions - @return {Object} - */ - extractPolymorphicRelationship: function extractPolymorphicRelationship(relationshipModelName, relationshipHash, relationshipOptions) { - return this.extractRelationship(relationshipModelName, relationshipHash); - }, - - /** - Returns the resource's relationships formatted as a JSON-API "relationships object". - http://jsonapi.org/format/#document-resource-object-relationships - @method extractRelationships - @param {Object} modelClass - @param {Object} resourceHash - @return {Object} - */ - extractRelationships: function extractRelationships(modelClass, resourceHash) { - var _this3 = this; - - var relationships = {}; - - modelClass.eachRelationship(function (key, relationshipMeta) { - var relationship = null; - var relationshipKey = _this3.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); - if (resourceHash.hasOwnProperty(relationshipKey)) { - var data = null; - var relationshipHash = resourceHash[relationshipKey]; - if (relationshipMeta.kind === 'belongsTo') { - if (relationshipMeta.options.polymorphic) { - // extracting a polymorphic belongsTo may need more information - // than the type and the hash (which might only be an id) for the - // relationship, hence we pass the key, resource and - // relationshipMeta too - data = _this3.extractPolymorphicRelationship(relationshipMeta.type, relationshipHash, { key: key, resourceHash: resourceHash, relationshipMeta: relationshipMeta }); - } else { - data = _this3.extractRelationship(relationshipMeta.type, relationshipHash); - } - } else if (relationshipMeta.kind === 'hasMany') { - if (!_ember['default'].isNone(relationshipHash)) { - data = new Array(relationshipHash.length); - for (var i = 0, l = relationshipHash.length; i < l; i++) { - var item = relationshipHash[i]; - data[i] = _this3.extractRelationship(relationshipMeta.type, item); - } - } - } - relationship = { data: data }; - } - - var linkKey = _this3.keyForLink(key, relationshipMeta.kind); - if (resourceHash.links && resourceHash.links.hasOwnProperty(linkKey)) { - var related = resourceHash.links[linkKey]; - relationship = relationship || {}; - relationship.links = { related: related }; - } - - if (relationship) { - relationships[key] = relationship; - } - }); - - return relationships; - }, - - /** - @method modelNameFromPayloadKey - @param {String} key - @return {String} the model's modelName - */ - modelNameFromPayloadKey: function modelNameFromPayloadKey(key) { - return (0, _emberDataPrivateSystemNormalizeModelName['default'])(key); - }, - - /** - @method normalizeAttributes - @private - */ - normalizeAttributes: function normalizeAttributes(typeClass, hash) { - var _this4 = this; - - var payloadKey; - - if (this.keyForAttribute) { - typeClass.eachAttribute(function (key) { - payloadKey = _this4.keyForAttribute(key, 'deserialize'); - if (key === payloadKey) { - return; - } - if (!hash.hasOwnProperty(payloadKey)) { - return; - } - - hash[key] = hash[payloadKey]; - delete hash[payloadKey]; - }); - } - }, - - /** - @method normalizeRelationships - @private - */ - normalizeRelationships: function normalizeRelationships(typeClass, hash) { - var _this5 = this; - - var payloadKey; - - if (this.keyForRelationship) { - typeClass.eachRelationship(function (key, relationship) { - payloadKey = _this5.keyForRelationship(key, relationship.kind, 'deserialize'); - if (key === payloadKey) { - return; - } - if (!hash.hasOwnProperty(payloadKey)) { - return; - } - - hash[key] = hash[payloadKey]; - delete hash[payloadKey]; - }); - } - }, - - /** - @method normalizeUsingDeclaredMapping - @private - */ - normalizeUsingDeclaredMapping: function normalizeUsingDeclaredMapping(modelClass, hash) { - var attrs = get(this, 'attrs'); - var normalizedKey, payloadKey, key; - - if (attrs) { - for (key in attrs) { - normalizedKey = payloadKey = this._getMappedKey(key, modelClass); - - if (!hash.hasOwnProperty(payloadKey)) { - continue; - } - - if (get(modelClass, 'attributes').has(key)) { - normalizedKey = this.keyForAttribute(key); - } - - if (get(modelClass, 'relationshipsByName').has(key)) { - normalizedKey = this.keyForRelationship(key); - } - - if (payloadKey !== normalizedKey) { - hash[normalizedKey] = hash[payloadKey]; - delete hash[payloadKey]; - } - } - } - }, - - /** - Looks up the property key that was set by the custom `attr` mapping - passed to the serializer. - @method _getMappedKey - @private - @param {String} key - @return {String} key - */ - _getMappedKey: function _getMappedKey(key, modelClass) { - (0, _emberDataPrivateDebug.warn)('There is no attribute or relationship with the name `' + key + '` on `' + modelClass.modelName + '`. Check your serializers attrs hash.', get(modelClass, 'attributes').has(key) || get(modelClass, 'relationshipsByName').has(key), { - id: 'ds.serializer.no-mapped-attrs-key' - }); - - var attrs = get(this, 'attrs'); - var mappedKey; - if (attrs && attrs[key]) { - mappedKey = attrs[key]; - //We need to account for both the { title: 'post_title' } and - //{ title: { key: 'post_title' }} forms - if (mappedKey.key) { - mappedKey = mappedKey.key; - } - if (typeof mappedKey === 'string') { - key = mappedKey; - } - } - - return key; - }, - - /** - Check attrs.key.serialize property to inform if the `key` - can be serialized - @method _canSerialize - @private - @param {String} key - @return {boolean} true if the key can be serialized - */ - _canSerialize: function _canSerialize(key) { - var attrs = get(this, 'attrs'); - - return !attrs || !attrs[key] || attrs[key].serialize !== false; - }, - - /** - When attrs.key.serialize is set to true then - it takes priority over the other checks and the related - attribute/relationship will be serialized - @method _mustSerialize - @private - @param {String} key - @return {boolean} true if the key must be serialized - */ - _mustSerialize: function _mustSerialize(key) { - var attrs = get(this, 'attrs'); - - return attrs && attrs[key] && attrs[key].serialize === true; - }, - - /** - Check if the given hasMany relationship should be serialized - @method _shouldSerializeHasMany - @private - @param {DS.Snapshot} snapshot - @param {String} key - @param {String} relationshipType - @return {boolean} true if the hasMany relationship should be serialized - */ - _shouldSerializeHasMany: function _shouldSerializeHasMany(snapshot, key, relationship) { - var relationshipType = snapshot.type.determineRelationshipType(relationship, this.store); - if (this._mustSerialize(key)) { - return true; - } - return this._canSerialize(key) && (relationshipType === 'manyToNone' || relationshipType === 'manyToMany'); - }, - - // SERIALIZE - /** - Called when a record is saved in order to convert the - record into JSON. - By default, it creates a JSON object with a key for - each attribute and belongsTo relationship. - For example, consider this model: - ```app/models/comment.js - import DS from 'ember-data'; - export default DS.Model.extend({ - title: DS.attr(), - body: DS.attr(), - author: DS.belongsTo('user') - }); - ``` - The default serialization would create a JSON object like: - ```javascript - { - "title": "Rails is unagi", - "body": "Rails? Omakase? O_O", - "author": 12 - } - ``` - By default, attributes are passed through as-is, unless - you specified an attribute type (`DS.attr('date')`). If - you specify a transform, the JavaScript value will be - serialized when inserted into the JSON hash. - By default, belongs-to relationships are converted into - IDs when inserted into the JSON hash. - ## IDs - `serialize` takes an options hash with a single option: - `includeId`. If this option is `true`, `serialize` will, - by default include the ID in the JSON object it builds. - The adapter passes in `includeId: true` when serializing - a record for `createRecord`, but not for `updateRecord`. - ## Customization - Your server may expect a different JSON format than the - built-in serialization format. - In that case, you can implement `serialize` yourself and - return a JSON hash of your choosing. - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - serialize: function(snapshot, options) { - var json = { - POST_TTL: snapshot.attr('title'), - POST_BDY: snapshot.attr('body'), - POST_CMS: snapshot.hasMany('comments', { ids: true }) - } - if (options.includeId) { - json.POST_ID_ = snapshot.id; - } - return json; - } - }); - ``` - ## Customizing an App-Wide Serializer - If you want to define a serializer for your entire - application, you'll probably want to use `eachAttribute` - and `eachRelationship` on the record. - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - serialize: function(snapshot, options) { - var json = {}; - snapshot.eachAttribute(function(name) { - json[serverAttributeName(name)] = snapshot.attr(name); - }) - snapshot.eachRelationship(function(name, relationship) { - if (relationship.kind === 'hasMany') { - json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); - } - }); - if (options.includeId) { - json.ID_ = snapshot.id; - } - return json; - } - }); - function serverAttributeName(attribute) { - return attribute.underscore().toUpperCase(); - } - function serverHasManyName(name) { - return serverAttributeName(name.singularize()) + "_IDS"; - } - ``` - This serializer will generate JSON that looks like this: - ```javascript - { - "TITLE": "Rails is omakase", - "BODY": "Yep. Omakase.", - "COMMENT_IDS": [ 1, 2, 3 ] - } - ``` - ## Tweaking the Default JSON - If you just want to do some small tweaks on the default JSON, - you can call super first and make the tweaks on the returned - JSON. - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - serialize: function(snapshot, options) { - var json = this._super.apply(this, arguments); - json.subject = json.title; - delete json.title; - return json; - } - }); - ``` - @method serialize - @param {DS.Snapshot} snapshot - @param {Object} options - @return {Object} json - */ - serialize: function serialize(snapshot, options) { - var _this6 = this; - - var json = {}; - - if (options && options.includeId) { - var id = snapshot.id; - - if (id) { - json[get(this, 'primaryKey')] = id; - } - } - - snapshot.eachAttribute(function (key, attribute) { - _this6.serializeAttribute(snapshot, json, key, attribute); - }); - - snapshot.eachRelationship(function (key, relationship) { - if (relationship.kind === 'belongsTo') { - _this6.serializeBelongsTo(snapshot, json, relationship); - } else if (relationship.kind === 'hasMany') { - _this6.serializeHasMany(snapshot, json, relationship); - } - }); - - return json; - }, - - /** - You can use this method to customize how a serialized record is added to the complete - JSON hash to be sent to the server. By default the JSON Serializer does not namespace - the payload and just sends the raw serialized JSON object. - If your server expects namespaced keys, you should consider using the RESTSerializer. - Otherwise you can override this method to customize how the record is added to the hash. - The hash property should be modified by reference. - For example, your server may expect underscored root objects. - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - serializeIntoHash: function(data, type, snapshot, options) { - var root = Ember.String.decamelize(type.modelName); - data[root] = this.serialize(snapshot, options); - } - }); - ``` - @method serializeIntoHash - @param {Object} hash - @param {DS.Model} typeClass - @param {DS.Snapshot} snapshot - @param {Object} options - */ - serializeIntoHash: function serializeIntoHash(hash, typeClass, snapshot, options) { - merge(hash, this.serialize(snapshot, options)); - }, - - /** - `serializeAttribute` can be used to customize how `DS.attr` - properties are serialized - For example if you wanted to ensure all your attributes were always - serialized as properties on an `attributes` object you could - write: - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - serializeAttribute: function(snapshot, json, key, attributes) { - json.attributes = json.attributes || {}; - this._super(snapshot, json.attributes, key, attributes); - } - }); - ``` - @method serializeAttribute - @param {DS.Snapshot} snapshot - @param {Object} json - @param {String} key - @param {Object} attribute - */ - serializeAttribute: function serializeAttribute(snapshot, json, key, attribute) { - var type = attribute.type; - - if (this._canSerialize(key)) { - var value = snapshot.attr(key); - if (type) { - var transform = this.transformFor(type); - value = transform.serialize(value); - } - - // if provided, use the mapping provided by `attrs` in - // the serializer - var payloadKey = this._getMappedKey(key, snapshot.type); - - if (payloadKey === key && this.keyForAttribute) { - payloadKey = this.keyForAttribute(key, 'serialize'); - } - - json[payloadKey] = value; - } - }, - - /** - `serializeBelongsTo` can be used to customize how `DS.belongsTo` - properties are serialized. - Example - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - serializeBelongsTo: function(snapshot, json, relationship) { - var key = relationship.key; - var belongsTo = snapshot.belongsTo(key); - key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo", "serialize") : key; - json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.record.toJSON(); - } - }); - ``` - @method serializeBelongsTo - @param {DS.Snapshot} snapshot - @param {Object} json - @param {Object} relationship - */ - serializeBelongsTo: function serializeBelongsTo(snapshot, json, relationship) { - var key = relationship.key; - - if (this._canSerialize(key)) { - var belongsToId = snapshot.belongsTo(key, { id: true }); - - // if provided, use the mapping provided by `attrs` in - // the serializer - var payloadKey = this._getMappedKey(key, snapshot.type); - if (payloadKey === key && this.keyForRelationship) { - payloadKey = this.keyForRelationship(key, "belongsTo", "serialize"); - } - - //Need to check whether the id is there for new&async records - if (isNone(belongsToId)) { - json[payloadKey] = null; - } else { - json[payloadKey] = belongsToId; - } - - if (relationship.options.polymorphic) { - this.serializePolymorphicType(snapshot, json, relationship); - } - } - }, - - /** - `serializeHasMany` can be used to customize how `DS.hasMany` - properties are serialized. - Example - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - serializeHasMany: function(snapshot, json, relationship) { - var key = relationship.key; - if (key === 'comments') { - return; - } else { - this._super.apply(this, arguments); - } - } - }); - ``` - @method serializeHasMany - @param {DS.Snapshot} snapshot - @param {Object} json - @param {Object} relationship - */ - serializeHasMany: function serializeHasMany(snapshot, json, relationship) { - var key = relationship.key; - - if (this._shouldSerializeHasMany(snapshot, key, relationship)) { - var hasMany = snapshot.hasMany(key, { ids: true }); - if (hasMany !== undefined) { - // if provided, use the mapping provided by `attrs` in - // the serializer - var payloadKey = this._getMappedKey(key, snapshot.type); - if (payloadKey === key && this.keyForRelationship) { - payloadKey = this.keyForRelationship(key, "hasMany", "serialize"); - } - - json[payloadKey] = hasMany; - // TODO support for polymorphic manyToNone and manyToMany relationships - } - } - }, - - /** - You can use this method to customize how polymorphic objects are - serialized. Objects are considered to be polymorphic if - `{ polymorphic: true }` is pass as the second argument to the - `DS.belongsTo` function. - Example - ```app/serializers/comment.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - serializePolymorphicType: function(snapshot, json, relationship) { - var key = relationship.key, - belongsTo = snapshot.belongsTo(key); - key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; - if (Ember.isNone(belongsTo)) { - json[key + "_type"] = null; - } else { - json[key + "_type"] = belongsTo.modelName; - } - } - }); - ``` - @method serializePolymorphicType - @param {DS.Snapshot} snapshot - @param {Object} json - @param {Object} relationship - */ - serializePolymorphicType: _ember['default'].K, - - /** - `extractMeta` is used to deserialize any meta information in the - adapter payload. By default Ember Data expects meta information to - be located on the `meta` property of the payload object. - Example - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - extractMeta: function(store, typeClass, payload) { - if (payload && payload._pagination) { - store.setMetadataFor(typeClass, payload._pagination); - delete payload._pagination; - } - } - }); - ``` - @method extractMeta - @param {DS.Store} store - @param {DS.Model} modelClass - @param {Object} payload - */ - extractMeta: function extractMeta(store, modelClass, payload) { - if (payload && payload.hasOwnProperty('meta')) { - var meta = payload.meta; - delete payload.meta; - return meta; - } - }, - - /** - `extractErrors` is used to extract model errors when a call is made - to `DS.Model#save` which fails with an `InvalidError`. By default - Ember Data expects error information to be located on the `errors` - property of the payload object. - Example - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - extractErrors: function(store, typeClass, payload, id) { - if (payload && typeof payload === 'object' && payload._problems) { - payload = payload._problems; - this.normalizeErrors(typeClass, payload); - } - return payload; - } - }); - ``` - @method extractErrors - @param {DS.Store} store - @param {DS.Model} typeClass - @param {Object} payload - @param {(String|Number)} id - @return {Object} json The deserialized errors - */ - extractErrors: function extractErrors(store, typeClass, payload, id) { - var _this7 = this; - - if (payload && typeof payload === 'object' && payload.errors) { - payload = (0, _emberDataPrivateAdaptersErrors.errorsArrayToHash)(payload.errors); - - this.normalizeUsingDeclaredMapping(typeClass, payload); - - typeClass.eachAttribute(function (name) { - var key = _this7.keyForAttribute(name, 'deserialize'); - if (key !== name && payload.hasOwnProperty(key)) { - payload[name] = payload[key]; - delete payload[key]; - } - }); - - typeClass.eachRelationship(function (name) { - var key = _this7.keyForRelationship(name, 'deserialize'); - if (key !== name && payload.hasOwnProperty(key)) { - payload[name] = payload[key]; - delete payload[key]; - } - }); - } - - return payload; - }, - - /** - `keyForAttribute` can be used to define rules for how to convert an - attribute name in your model to a key in your JSON. - Example - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - keyForAttribute: function(attr, method) { - return Ember.String.underscore(attr).toUpperCase(); - } - }); - ``` - @method keyForAttribute - @param {String} key - @param {String} method - @return {String} normalized key - */ - keyForAttribute: function keyForAttribute(key, method) { - return key; - }, - - /** - `keyForRelationship` can be used to define a custom key when - serializing and deserializing relationship properties. By default - `JSONSerializer` does not provide an implementation of this method. - Example - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.JSONSerializer.extend({ - keyForRelationship: function(key, relationship, method) { - return 'rel_' + Ember.String.underscore(key); - } - }); - ``` - @method keyForRelationship - @param {String} key - @param {String} typeClass - @param {String} method - @return {String} normalized key - */ - keyForRelationship: function keyForRelationship(key, typeClass, method) { - return key; - }, - - /** - `keyForLink` can be used to define a custom key when deserializing link - properties. - @method keyForLink - @param {String} key - @param {String} kind `belongsTo` or `hasMany` - @return {String} normalized key - */ - keyForLink: function keyForLink(key, kind) { - return key; - }, - - // HELPERS - - /** - @method transformFor - @private - @param {String} attributeType - @param {Boolean} skipAssertion - @return {DS.Transform} transform - */ - transformFor: function transformFor(attributeType, skipAssertion) { - var transform = (0, _emberDataPrivateUtils.getOwner)(this).lookup('transform:' + attributeType); - - (0, _emberDataPrivateDebug.assert)("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform); - - return transform; - } - }); -}); -define("ember-data/serializers/rest", ["exports", "ember", "ember-data/-private/debug", "ember-data/serializers/json", "ember-data/-private/system/normalize-model-name", "ember-inflector", "ember-data/-private/system/coerce-id", "ember-data/-private/utils"], function (exports, _ember, _emberDataPrivateDebug, _emberDataSerializersJson, _emberDataPrivateSystemNormalizeModelName, _emberInflector, _emberDataPrivateSystemCoerceId, _emberDataPrivateUtils) { - "use strict"; - - function _toConsumableArray(arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];return arr2; - } else { - return Array.from(arr); - } - } - - /** - @module ember-data - */ - - var camelize = _ember["default"].String.camelize; - - /** - Normally, applications will use the `RESTSerializer` by implementing - the `normalize` method and individual normalizations under - `normalizeHash`. - - This allows you to do whatever kind of munging you need, and is - especially useful if your server is inconsistent and you need to - do munging differently for many different kinds of responses. - - See the `normalize` documentation for more information. - - ## Across the Board Normalization - - There are also a number of hooks that you might find useful to define - across-the-board rules for your payload. These rules will be useful - if your server is consistent, or if you're building an adapter for - an infrastructure service, like Parse, and want to encode service - conventions. - - For example, if all of your keys are underscored and all-caps, but - otherwise consistent with the names you use in your models, you - can implement across-the-board rules for how to convert an attribute - name in your model to a key in your JSON. - - ```app/serializers/application.js - import DS from 'ember-data'; - - export default DS.RESTSerializer.extend({ - keyForAttribute: function(attr, method) { - return Ember.String.underscore(attr).toUpperCase(); - } - }); - ``` - - You can also implement `keyForRelationship`, which takes the name - of the relationship as the first parameter, the kind of - relationship (`hasMany` or `belongsTo`) as the second parameter, and - the method (`serialize` or `deserialize`) as the third parameter. - - @class RESTSerializer - @namespace DS - @extends DS.JSONSerializer - */ - var RESTSerializer = _emberDataSerializersJson["default"].extend({ - - /** - `keyForPolymorphicType` can be used to define a custom key when - serializing and deserializing a polymorphic type. By default, the - returned key is `${key}Type`. - Example - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - keyForPolymorphicType: function(key, relationship) { - var relationshipKey = this.keyForRelationship(key); - return 'type-' + relationshipKey; - } - }); - ``` - @method keyForPolymorphicType - @param {String} key - @param {String} typeClass - @param {String} method - @return {String} normalized key - */ - keyForPolymorphicType: function keyForPolymorphicType(key, typeClass, method) { - var relationshipKey = this.keyForRelationship(key); - - return relationshipKey + "Type"; - }, - - /** - Normalizes a part of the JSON payload returned by - the server. You should override this method, munge the hash - and call super if you have generic normalization to do. - It takes the type of the record that is being normalized - (as a DS.Model class), the property where the hash was - originally found, and the hash to normalize. - For example, if you have a payload that looks like this: - ```js - { - "post": { - "id": 1, - "title": "Rails is omakase", - "comments": [ 1, 2 ] - }, - "comments": [{ - "id": 1, - "body": "FIRST" - }, { - "id": 2, - "body": "Rails is unagi" - }] - } - ``` - The `normalize` method will be called three times: - * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` - * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` - * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` - You can use this method, for example, to normalize underscored keys to camelized - or other general-purpose normalizations. - If you want to do normalizations specific to some part of the payload, you - can specify those under `normalizeHash`. - For example, if the `IDs` under `"comments"` are provided as `_id` instead of - `id`, you can specify how to normalize just the comments: - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - normalizeHash: { - comments: function(hash) { - hash.id = hash._id; - delete hash._id; - return hash; - } - } - }); - ``` - The key under `normalizeHash` is just the original key that was in the original - payload. - @method normalize - @param {DS.Model} modelClass - @param {Object} resourceHash - @param {String} prop - @return {Object} - */ - normalize: function normalize(modelClass, resourceHash, prop) { - if (this.normalizeHash && this.normalizeHash[prop]) { - this.normalizeHash[prop](resourceHash); - } - return this._super(modelClass, resourceHash, prop); - }, - - /** - Normalizes an array of resource payloads and returns a JSON-API Document - with primary data and, if any, included data as `{ data, included }`. - @method _normalizeArray - @param {DS.Store} store - @param {String} modelName - @param {Object} arrayHash - @param {String} prop - @return {Object} - @private - */ - _normalizeArray: function _normalizeArray(store, modelName, arrayHash, prop) { - var _this = this; - - var documentHash = { - data: [], - included: [] - }; - - var modelClass = store.modelFor(modelName); - var serializer = store.serializerFor(modelName); - - /*jshint loopfunc:true*/ - arrayHash.forEach(function (hash) { - var _normalizePolymorphicRecord2 = _this._normalizePolymorphicRecord(store, hash, prop, modelClass, serializer); - - var data = _normalizePolymorphicRecord2.data; - var included = _normalizePolymorphicRecord2.included; - - documentHash.data.push(data); - if (included) { - var _documentHash$included; - - (_documentHash$included = documentHash.included).push.apply(_documentHash$included, _toConsumableArray(included)); - } - }); - - return documentHash; - }, - - _normalizePolymorphicRecord: function _normalizePolymorphicRecord(store, hash, prop, primaryModelClass, primarySerializer) { - var serializer = undefined, - modelClass = undefined; - var primaryHasTypeAttribute = (0, _emberDataPrivateUtils.modelHasAttributeOrRelationshipNamedType)(primaryModelClass); - // Support polymorphic records in async relationships - if (!primaryHasTypeAttribute && hash.type && store._hasModelFor(this.modelNameFromPayloadKey(hash.type))) { - serializer = store.serializerFor(hash.type); - modelClass = store.modelFor(hash.type); - } else { - serializer = primarySerializer; - modelClass = primaryModelClass; - } - return serializer.normalize(modelClass, hash, prop); - }, - - /* - @method _normalizeResponse - @param {DS.Store} store - @param {DS.Model} primaryModelClass - @param {Object} payload - @param {String|Number} id - @param {String} requestType - @param {Boolean} isSingle - @return {Object} JSON-API Document - @private - */ - _normalizeResponse: function _normalizeResponse(store, primaryModelClass, payload, id, requestType, isSingle) { - var documentHash = { - data: null, - included: [] - }; - - var meta = this.extractMeta(store, primaryModelClass, payload); - if (meta) { - (0, _emberDataPrivateDebug.assert)('The `meta` returned from `extractMeta` has to be an object, not "' + _ember["default"].typeOf(meta) + '".', _ember["default"].typeOf(meta) === 'object'); - documentHash.meta = meta; - } - - var keys = Object.keys(payload); - - for (var i = 0, _length = keys.length; i < _length; i++) { - var prop = keys[i]; - var modelName = prop; - var forcedSecondary = false; - - /* - If you want to provide sideloaded records of the same type that the - primary data you can do that by prefixing the key with `_`. - Example - ``` - { - users: [ - { id: 1, title: 'Tom', manager: 3 }, - { id: 2, title: 'Yehuda', manager: 3 } - ], - _users: [ - { id: 3, title: 'Tomster' } - ] - } - ``` - This forces `_users` to be added to `included` instead of `data`. - */ - if (prop.charAt(0) === '_') { - forcedSecondary = true; - modelName = prop.substr(1); - } - - var typeName = this.modelNameFromPayloadKey(modelName); - if (!store.modelFactoryFor(typeName)) { - (0, _emberDataPrivateDebug.warn)(this.warnMessageNoModelForKey(modelName, typeName), false, { - id: 'ds.serializer.model-for-key-missing' - }); - continue; - } - - var isPrimary = !forcedSecondary && this.isPrimaryType(store, typeName, primaryModelClass); - var value = payload[prop]; - - if (value === null) { - continue; - } - - /* - Support primary data as an object instead of an array. - Example - ``` - { - user: { id: 1, title: 'Tom', manager: 3 } - } - ``` - */ - if (isPrimary && _ember["default"].typeOf(value) !== 'array') { - var _normalizePolymorphicRecord3 = this._normalizePolymorphicRecord(store, value, prop, primaryModelClass, this); - - var _data = _normalizePolymorphicRecord3.data; - var _included = _normalizePolymorphicRecord3.included; - - documentHash.data = _data; - if (_included) { - var _documentHash$included2; - - (_documentHash$included2 = documentHash.included).push.apply(_documentHash$included2, _toConsumableArray(_included)); - } - continue; - } - - var _normalizeArray2 = this._normalizeArray(store, typeName, value, prop); - - var data = _normalizeArray2.data; - var included = _normalizeArray2.included; - - if (included) { - var _documentHash$included3; - - (_documentHash$included3 = documentHash.included).push.apply(_documentHash$included3, _toConsumableArray(included)); - } - - if (isSingle) { - /*jshint loopfunc:true*/ - data.forEach(function (resource) { - - /* - Figures out if this is the primary record or not. - It's either: - 1. The record with the same ID as the original request - 2. If it's a newly created record without an ID, the first record - in the array - */ - var isUpdatedRecord = isPrimary && (0, _emberDataPrivateSystemCoerceId["default"])(resource.id) === id; - var isFirstCreatedRecord = isPrimary && !id && !documentHash.data; - - if (isFirstCreatedRecord || isUpdatedRecord) { - documentHash.data = resource; - } else { - documentHash.included.push(resource); - } - }); - } else { - if (isPrimary) { - documentHash.data = data; - } else { - if (data) { - var _documentHash$included4; - - (_documentHash$included4 = documentHash.included).push.apply(_documentHash$included4, _toConsumableArray(data)); - } - } - } - } - - return documentHash; - }, - - isPrimaryType: function isPrimaryType(store, typeName, primaryTypeClass) { - var typeClass = store.modelFor(typeName); - return typeClass.modelName === primaryTypeClass.modelName; - }, - - /** - This method allows you to push a payload containing top-level - collections of records organized per type. - ```js - { - "posts": [{ - "id": "1", - "title": "Rails is omakase", - "author", "1", - "comments": [ "1" ] - }], - "comments": [{ - "id": "1", - "body": "FIRST" - }], - "users": [{ - "id": "1", - "name": "@d2h" - }] - } - ``` - It will first normalize the payload, so you can use this to push - in data streaming in from your server structured the same way - that fetches and saves are structured. - @method pushPayload - @param {DS.Store} store - @param {Object} payload - */ - pushPayload: function pushPayload(store, payload) { - var documentHash = { - data: [], - included: [] - }; - - for (var prop in payload) { - var modelName = this.modelNameFromPayloadKey(prop); - if (!store.modelFactoryFor(modelName)) { - (0, _emberDataPrivateDebug.warn)(this.warnMessageNoModelForKey(prop, modelName), false, { - id: 'ds.serializer.model-for-key-missing' - }); - continue; - } - var type = store.modelFor(modelName); - var typeSerializer = store.serializerFor(type.modelName); - - /*jshint loopfunc:true*/ - _ember["default"].makeArray(payload[prop]).forEach(function (hash) { - var _typeSerializer$normalize = typeSerializer.normalize(type, hash, prop); - - var data = _typeSerializer$normalize.data; - var included = _typeSerializer$normalize.included; - - documentHash.data.push(data); - if (included) { - var _documentHash$included5; - - (_documentHash$included5 = documentHash.included).push.apply(_documentHash$included5, _toConsumableArray(included)); - } - }); - } - - store.push(documentHash); - }, - - /** - This method is used to convert each JSON root key in the payload - into a modelName that it can use to look up the appropriate model for - that part of the payload. - For example, your server may send a model name that does not correspond with - the name of the model in your app. Let's take a look at an example model, - and an example payload: - ```app/models/post.js - import DS from 'ember-data'; - export default DS.Model.extend({ - }); - ``` - ```javascript - { - "blog/post": { - "id": "1 - } - } - ``` - Ember Data is going to normalize the payload's root key for the modelName. As a result, - it will try to look up the "blog/post" model. Since we don't have a model called "blog/post" - (or a file called app/models/blog/post.js in ember-cli), Ember Data will throw an error - because it cannot find the "blog/post" model. - Since we want to remove this namespace, we can define a serializer for the application that will - remove "blog/" from the payload key whenver it's encountered by Ember Data: - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - modelNameFromPayloadKey: function(payloadKey) { - if (payloadKey === 'blog/post') { - return this._super(payloadKey.replace('blog/', '')); - } else { - return this._super(payloadKey); - } - } - }); - ``` - After refreshing, Ember Data will appropriately look up the "post" model. - By default the modelName for a model is its - name in dasherized form. This means that a payload key like "blogPost" would be - normalized to "blog-post" when Ember Data looks up the model. Usually, Ember Data - can use the correct inflection to do this for you. Most of the time, you won't - need to override `modelNameFromPayloadKey` for this purpose. - @method modelNameFromPayloadKey - @param {String} key - @return {String} the model's modelName - */ - modelNameFromPayloadKey: function modelNameFromPayloadKey(key) { - return (0, _emberInflector.singularize)((0, _emberDataPrivateSystemNormalizeModelName["default"])(key)); - }, - - // SERIALIZE - - /** - Called when a record is saved in order to convert the - record into JSON. - By default, it creates a JSON object with a key for - each attribute and belongsTo relationship. - For example, consider this model: - ```app/models/comment.js - import DS from 'ember-data'; - export default DS.Model.extend({ - title: DS.attr(), - body: DS.attr(), - author: DS.belongsTo('user') - }); - ``` - The default serialization would create a JSON object like: - ```js - { - "title": "Rails is unagi", - "body": "Rails? Omakase? O_O", - "author": 12 - } - ``` - By default, attributes are passed through as-is, unless - you specified an attribute type (`DS.attr('date')`). If - you specify a transform, the JavaScript value will be - serialized when inserted into the JSON hash. - By default, belongs-to relationships are converted into - IDs when inserted into the JSON hash. - ## IDs - `serialize` takes an options hash with a single option: - `includeId`. If this option is `true`, `serialize` will, - by default include the ID in the JSON object it builds. - The adapter passes in `includeId: true` when serializing - a record for `createRecord`, but not for `updateRecord`. - ## Customization - Your server may expect a different JSON format than the - built-in serialization format. - In that case, you can implement `serialize` yourself and - return a JSON hash of your choosing. - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - serialize: function(snapshot, options) { - var json = { - POST_TTL: snapshot.attr('title'), - POST_BDY: snapshot.attr('body'), - POST_CMS: snapshot.hasMany('comments', { ids: true }) - } - if (options.includeId) { - json.POST_ID_ = snapshot.id; - } - return json; - } - }); - ``` - ## Customizing an App-Wide Serializer - If you want to define a serializer for your entire - application, you'll probably want to use `eachAttribute` - and `eachRelationship` on the record. - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - serialize: function(snapshot, options) { - var json = {}; - snapshot.eachAttribute(function(name) { - json[serverAttributeName(name)] = snapshot.attr(name); - }) - snapshot.eachRelationship(function(name, relationship) { - if (relationship.kind === 'hasMany') { - json[serverHasManyName(name)] = snapshot.hasMany(name, { ids: true }); - } - }); - if (options.includeId) { - json.ID_ = snapshot.id; - } - return json; - } - }); - function serverAttributeName(attribute) { - return attribute.underscore().toUpperCase(); - } - function serverHasManyName(name) { - return serverAttributeName(name.singularize()) + "_IDS"; - } - ``` - This serializer will generate JSON that looks like this: - ```js - { - "TITLE": "Rails is omakase", - "BODY": "Yep. Omakase.", - "COMMENT_IDS": [ 1, 2, 3 ] - } - ``` - ## Tweaking the Default JSON - If you just want to do some small tweaks on the default JSON, - you can call super first and make the tweaks on the returned - JSON. - ```app/serializers/post.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - serialize: function(snapshot, options) { - var json = this._super(snapshot, options); - json.subject = json.title; - delete json.title; - return json; - } - }); - ``` - @method serialize - @param {DS.Snapshot} snapshot - @param {Object} options - @return {Object} json - */ - serialize: function serialize(snapshot, options) { - return this._super.apply(this, arguments); - }, - - /** - You can use this method to customize the root keys serialized into the JSON. - The hash property should be modified by reference (possibly using something like _.extend) - By default the REST Serializer sends the modelName of a model, which is a camelized - version of the name. - For example, your server may expect underscored root objects. - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - serializeIntoHash: function(data, type, record, options) { - var root = Ember.String.decamelize(type.modelName); - data[root] = this.serialize(record, options); - } - }); - ``` - @method serializeIntoHash - @param {Object} hash - @param {DS.Model} typeClass - @param {DS.Snapshot} snapshot - @param {Object} options - */ - serializeIntoHash: function serializeIntoHash(hash, typeClass, snapshot, options) { - var normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName); - hash[normalizedRootKey] = this.serialize(snapshot, options); - }, - - /** - You can use `payloadKeyFromModelName` to override the root key for an outgoing - request. By default, the RESTSerializer returns a camelized version of the - model's name. - For a model called TacoParty, its `modelName` would be the string `taco-party`. The RESTSerializer - will send it to the server with `tacoParty` as the root key in the JSON payload: - ```js - { - "tacoParty": { - "id": "1", - "location": "Matthew Beale's House" - } - } - ``` - For example, your server may expect dasherized root objects: - ```app/serializers/application.js - import DS from 'ember-data'; - export default DS.RESTSerializer.extend({ - payloadKeyFromModelName: function(modelName) { - return Ember.String.dasherize(modelName); - } - }); - ``` - Given a `TacoParty' model, calling `save` on a tacoModel would produce an outgoing - request like: - ```js - { - "taco-party": { - "id": "1", - "location": "Matthew Beale's House" - } - } - ``` - @method payloadKeyFromModelName - @param {String} modelName - @return {String} - */ - payloadKeyFromModelName: function payloadKeyFromModelName(modelName) { - return camelize(modelName); - }, - - /** - You can use this method to customize how polymorphic objects are serialized. - By default the REST Serializer creates the key by appending `Type` to - the attribute and value from the model's camelcased model name. - @method serializePolymorphicType - @param {DS.Snapshot} snapshot - @param {Object} json - @param {Object} relationship - */ - serializePolymorphicType: function serializePolymorphicType(snapshot, json, relationship) { - var key = relationship.key; - var belongsTo = snapshot.belongsTo(key); - var typeKey = this.keyForPolymorphicType(key, relationship.type, 'serialize'); - - // old way of getting the key for the polymorphic type - key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; - key = key + "Type"; - - // The old way of serializing the type of a polymorphic record used - // `keyForAttribute`, which is not correct. The next code checks if the old - // way is used and if it differs from the new way of using - // `keyForPolymorphicType`. If this is the case, a deprecation warning is - // logged and the old way is restored (so nothing breaks). - if (key !== typeKey && this.keyForPolymorphicType === RESTSerializer.prototype.keyForPolymorphicType) { - (0, _emberDataPrivateDebug.deprecate)("The key to serialize the type of a polymorphic record is created via keyForAttribute which has been deprecated. Use the keyForPolymorphicType hook instead.", false, { - id: 'ds.rest-serializer.deprecated-key-for-polymorphic-type', - until: '3.0.0' - }); - - typeKey = key; - } - - if (_ember["default"].isNone(belongsTo)) { - json[typeKey] = null; - } else { - json[typeKey] = camelize(belongsTo.modelName); - } - }, - - /** - You can use this method to customize how a polymorphic relationship should - be extracted. - @method extractPolymorphicRelationship - @param {Object} relationshipType - @param {Object} relationshipHash - @param {Object} relationshipOptions - @return {Object} - */ - extractPolymorphicRelationship: function extractPolymorphicRelationship(relationshipType, relationshipHash, relationshipOptions) { - var key = relationshipOptions.key; - var resourceHash = relationshipOptions.resourceHash; - var relationshipMeta = relationshipOptions.relationshipMeta; - - // A polymorphic belongsTo relationship can be present in the payload - // either in the form where the `id` and the `type` are given: - // - // { - // message: { id: 1, type: 'post' } - // } - // - // or by the `id` and a `Type` attribute: - // - // { - // message: 1, - // messageType: 'post' - // } - // - // The next code checks if the latter case is present and returns the - // corresponding JSON-API representation. The former case is handled within - // the base class JSONSerializer. - var isPolymorphic = relationshipMeta.options.polymorphic; - var typeProperty = this.keyForPolymorphicType(key, relationshipType, 'deserialize'); - - if (isPolymorphic && resourceHash.hasOwnProperty(typeProperty) && typeof relationshipHash !== 'object') { - var type = this.modelNameFromPayloadKey(resourceHash[typeProperty]); - return { - id: relationshipHash, - type: type - }; - } - - return this._super.apply(this, arguments); - } - }); - - (0, _emberDataPrivateDebug.runInDebug)(function () { - RESTSerializer.reopen({ - warnMessageNoModelForKey: function warnMessageNoModelForKey(prop, typeKey) { - return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.modelNameFromPayloadKey("' + prop + '"))'; - } - }); - }); - - exports["default"] = RESTSerializer; -}); -define('ember-data/setup-container', ['exports', 'ember-data/-private/initializers/store', 'ember-data/-private/initializers/transforms', 'ember-data/-private/initializers/store-injections', 'ember-data/-private/initializers/data-adapter'], function (exports, _emberDataPrivateInitializersStore, _emberDataPrivateInitializersTransforms, _emberDataPrivateInitializersStoreInjections, _emberDataPrivateInitializersDataAdapter) { - 'use strict'; - - exports['default'] = setupContainer; - - function setupContainer(application) { - (0, _emberDataPrivateInitializersDataAdapter['default'])(application); - (0, _emberDataPrivateInitializersTransforms['default'])(application); - (0, _emberDataPrivateInitializersStoreInjections['default'])(application); - (0, _emberDataPrivateInitializersStore['default'])(application); - } -}); -define("ember-data/store", ["exports", "ember-data/-private/system/store"], function (exports, _emberDataPrivateSystemStore) { - "use strict"; - - exports["default"] = _emberDataPrivateSystemStore["default"]; -}); -define('ember-data/transform', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - /** - The `DS.Transform` class is used to serialize and deserialize model - attributes when they are saved or loaded from an - adapter. Subclassing `DS.Transform` is useful for creating custom - attributes. All subclasses of `DS.Transform` must implement a - `serialize` and a `deserialize` method. - - Example - - ```app/transforms/temperature.js - import DS from 'ember-data'; - - // Converts centigrade in the JSON to fahrenheit in the app - export default DS.Transform.extend({ - deserialize: function(serialized) { - return (serialized * 1.8) + 32; - }, - serialize: function(deserialized) { - return (deserialized - 32) / 1.8; - } - }); - ``` - - Usage - - ```app/models/requirement.js - import DS from 'ember-data'; - - export default DS.Model.extend({ - name: DS.attr('string'), - temperature: DS.attr('temperature') - }); - ``` - - @class Transform - @namespace DS - */ - exports['default'] = _ember['default'].Object.extend({ - /** - When given a deserialized value from a record attribute this - method must return the serialized value. - Example - ```javascript - serialize: function(deserialized) { - return Ember.isEmpty(deserialized) ? null : Number(deserialized); - } - ``` - @method serialize - @param deserialized The deserialized value - @return The serialized value - */ - serialize: null, - - /** - When given a serialize value from a JSON object this method must - return the deserialized value for the record attribute. - Example - ```javascript - deserialize: function(serialized) { - return empty(serialized) ? null : Number(serialized); - } - ``` - @method deserialize - @param serialized The serialized value - @return The deserialized value - */ - deserialize: null - }); -}); -define("ember-data/version", ["exports"], function (exports) { - "use strict"; - - exports["default"] = "2.4.0"; -}); -define("ember-inflector/index", ["exports", "ember", "ember-inflector/lib/system", "ember-inflector/lib/ext/string"], function (exports, _ember, _emberInflectorLibSystem, _emberInflectorLibExtString) { - /* global define, module */ - - "use strict"; - - _emberInflectorLibSystem.Inflector.defaultRules = _emberInflectorLibSystem.defaultRules; - _ember["default"].Inflector = _emberInflectorLibSystem.Inflector; - - _ember["default"].String.pluralize = _emberInflectorLibSystem.pluralize; - _ember["default"].String.singularize = _emberInflectorLibSystem.singularize;exports["default"] = _emberInflectorLibSystem.Inflector; - exports.pluralize = _emberInflectorLibSystem.pluralize; - exports.singularize = _emberInflectorLibSystem.singularize; - exports.defaultRules = _emberInflectorLibSystem.defaultRules; - - if (typeof define !== 'undefined' && define.amd) { - define('ember-inflector', ['exports'], function (__exports__) { - __exports__['default'] = _emberInflectorLibSystem.Inflector; - return _emberInflectorLibSystem.Inflector; - }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = _emberInflectorLibSystem.Inflector; - } -}); -define('ember-inflector/lib/ext/string', ['exports', 'ember', 'ember-inflector/lib/system/string'], function (exports, _ember, _emberInflectorLibSystemString) { - 'use strict'; - - if (_ember['default'].EXTEND_PROTOTYPES === true || _ember['default'].EXTEND_PROTOTYPES.String) { - /** - See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} - @method pluralize - @for String - */ - String.prototype.pluralize = function () { - return (0, _emberInflectorLibSystemString.pluralize)(this); - }; - - /** - See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} - @method singularize - @for String - */ - String.prototype.singularize = function () { - return (0, _emberInflectorLibSystemString.singularize)(this); - }; - } -}); -define('ember-inflector/lib/helpers/pluralize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _emberInflectorLibUtilsMakeHelper) { - 'use strict'; - - /** - * - * If you have Ember Inflector (such as if Ember Data is present), - * pluralize a word. For example, turn "ox" into "oxen". - * - * Example: - * - * {{pluralize count myProperty}} - * {{pluralize 1 "oxen"}} - * {{pluralize myProperty}} - * {{pluralize "ox"}} - * - * @for Ember.HTMLBars.helpers - * @method pluralize - * @param {Number|Property} [count] count of objects - * @param {String|Property} word word to pluralize - */ - exports['default'] = (0, _emberInflectorLibUtilsMakeHelper['default'])(function (params) { - var count = undefined, - word = undefined; - - if (params.length === 1) { - word = params[0]; - return (0, _emberInflector.pluralize)(word); - } else { - count = params[0]; - word = params[1]; - - if (parseFloat(count) !== 1) { - word = (0, _emberInflector.pluralize)(word); - } - - return count + " " + word; - } - }); -}); -define('ember-inflector/lib/helpers/singularize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _emberInflectorLibUtilsMakeHelper) { - 'use strict'; - - /** - * - * If you have Ember Inflector (such as if Ember Data is present), - * singularize a word. For example, turn "oxen" into "ox". - * - * Example: - * - * {{singularize myProperty}} - * {{singularize "oxen"}} - * - * @for Ember.HTMLBars.helpers - * @method singularize - * @param {String|Property} word word to singularize - */ - exports['default'] = (0, _emberInflectorLibUtilsMakeHelper['default'])(function (params) { - return (0, _emberInflector.singularize)(params[0]); - }); -}); -define('ember-inflector/lib/system/inflections', ['exports'], function (exports) { - 'use strict'; - - exports['default'] = { - plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes']], - - singular: [[/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1']], - - irregularPairs: [['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies']], - - uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police'] - }; -}); -define('ember-inflector/lib/system/inflector', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - var capitalize = _ember['default'].String.capitalize; - - var BLANK_REGEX = /^\s*$/; - var LAST_WORD_DASHED_REGEX = /([\w/-]+[_/\s-])([a-z\d]+$)/; - var LAST_WORD_CAMELIZED_REGEX = /([\w/\s-]+)([A-Z][a-z\d]*$)/; - var CAMELIZED_REGEX = /[A-Z][a-z\d]*$/; - - function loadUncountable(rules, uncountable) { - for (var i = 0, length = uncountable.length; i < length; i++) { - rules.uncountable[uncountable[i].toLowerCase()] = true; - } - } - - function loadIrregular(rules, irregularPairs) { - var pair; - - for (var i = 0, length = irregularPairs.length; i < length; i++) { - pair = irregularPairs[i]; - - //pluralizing - rules.irregular[pair[0].toLowerCase()] = pair[1]; - rules.irregular[pair[1].toLowerCase()] = pair[1]; - - //singularizing - rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; - rules.irregularInverse[pair[0].toLowerCase()] = pair[0]; - } - } - - /** - Inflector.Ember provides a mechanism for supplying inflection rules for your - application. Ember includes a default set of inflection rules, and provides an - API for providing additional rules. - - Examples: - - Creating an inflector with no rules. - - ```js - var inflector = new Ember.Inflector(); - ``` - - Creating an inflector with the default ember ruleset. - - ```js - var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); - - inflector.pluralize('cow'); //=> 'kine' - inflector.singularize('kine'); //=> 'cow' - ``` - - Creating an inflector and adding rules later. - - ```javascript - var inflector = Ember.Inflector.inflector; - - inflector.pluralize('advice'); // => 'advices' - inflector.uncountable('advice'); - inflector.pluralize('advice'); // => 'advice' - - inflector.pluralize('formula'); // => 'formulas' - inflector.irregular('formula', 'formulae'); - inflector.pluralize('formula'); // => 'formulae' - - // you would not need to add these as they are the default rules - inflector.plural(/$/, 's'); - inflector.singular(/s$/i, ''); - ``` - - Creating an inflector with a nondefault ruleset. - - ```javascript - var rules = { - plurals: [ /$/, 's' ], - singular: [ /\s$/, '' ], - irregularPairs: [ - [ 'cow', 'kine' ] - ], - uncountable: [ 'fish' ] - }; - - var inflector = new Ember.Inflector(rules); - ``` - - @class Inflector - @namespace Ember - */ - function Inflector(ruleSet) { - ruleSet = ruleSet || {}; - ruleSet.uncountable = ruleSet.uncountable || makeDictionary(); - ruleSet.irregularPairs = ruleSet.irregularPairs || makeDictionary(); - - var rules = this.rules = { - plurals: ruleSet.plurals || [], - singular: ruleSet.singular || [], - irregular: makeDictionary(), - irregularInverse: makeDictionary(), - uncountable: makeDictionary() - }; - - loadUncountable(rules, ruleSet.uncountable); - loadIrregular(rules, ruleSet.irregularPairs); - - this.enableCache(); - } - - if (!Object.create && !Object.create(null).hasOwnProperty) { - throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); - } - - function makeDictionary() { - var cache = Object.create(null); - cache['_dict'] = null; - delete cache['_dict']; - return cache; - } - - Inflector.prototype = { - /** - @public - As inflections can be costly, and commonly the same subset of words are repeatedly - inflected an optional cache is provided. - @method enableCache - */ - enableCache: function enableCache() { - this.purgeCache(); - - this.singularize = function (word) { - this._cacheUsed = true; - return this._sCache[word] || (this._sCache[word] = this._singularize(word)); - }; - - this.pluralize = function (word) { - this._cacheUsed = true; - return this._pCache[word] || (this._pCache[word] = this._pluralize(word)); - }; - }, - - /** - @public - @method purgedCache - */ - purgeCache: function purgeCache() { - this._cacheUsed = false; - this._sCache = makeDictionary(); - this._pCache = makeDictionary(); - }, - - /** - @public - disable caching - @method disableCache; - */ - disableCache: function disableCache() { - this._sCache = null; - this._pCache = null; - this.singularize = function (word) { - return this._singularize(word); - }; - - this.pluralize = function (word) { - return this._pluralize(word); - }; - }, - - /** - @method plural - @param {RegExp} regex - @param {String} string - */ - plural: function plural(regex, string) { - if (this._cacheUsed) { - this.purgeCache(); - } - this.rules.plurals.push([regex, string.toLowerCase()]); - }, - - /** - @method singular - @param {RegExp} regex - @param {String} string - */ - singular: function singular(regex, string) { - if (this._cacheUsed) { - this.purgeCache(); - } - this.rules.singular.push([regex, string.toLowerCase()]); - }, - - /** - @method uncountable - @param {String} regex - */ - uncountable: function uncountable(string) { - if (this._cacheUsed) { - this.purgeCache(); - } - loadUncountable(this.rules, [string.toLowerCase()]); - }, - - /** - @method irregular - @param {String} singular - @param {String} plural - */ - irregular: function irregular(singular, plural) { - if (this._cacheUsed) { - this.purgeCache(); - } - loadIrregular(this.rules, [[singular, plural]]); - }, - - /** - @method pluralize - @param {String} word - */ - pluralize: function pluralize(word) { - return this._pluralize(word); - }, - - _pluralize: function _pluralize(word) { - return this.inflect(word, this.rules.plurals, this.rules.irregular); - }, - /** - @method singularize - @param {String} word - */ - singularize: function singularize(word) { - return this._singularize(word); - }, - - _singularize: function _singularize(word) { - return this.inflect(word, this.rules.singular, this.rules.irregularInverse); - }, - - /** - @protected - @method inflect - @param {String} word - @param {Object} typeRules - @param {Object} irregular - */ - inflect: function inflect(word, typeRules, irregular) { - var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, rule, isUncountable; - - isBlank = !word || BLANK_REGEX.test(word); - - isCamelized = CAMELIZED_REGEX.test(word); - firstPhrase = ""; - - if (isBlank) { - return word; - } - - lowercase = word.toLowerCase(); - wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word); - - if (wordSplit) { - firstPhrase = wordSplit[1]; - lastWord = wordSplit[2].toLowerCase(); - } - - isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord]; - - if (isUncountable) { - return word; - } - - for (rule in this.rules.irregular) { - if (lowercase.match(rule + "$")) { - substitution = irregular[rule]; - - if (isCamelized && irregular[lastWord]) { - substitution = capitalize(substitution); - rule = capitalize(rule); - } - - return word.replace(rule, substitution); - } - } - - for (var i = typeRules.length, min = 0; i > min; i--) { - inflection = typeRules[i - 1]; - rule = inflection[0]; - - if (rule.test(word)) { - break; - } - } - - inflection = inflection || []; - - rule = inflection[0]; - substitution = inflection[1]; - - result = word.replace(rule, substitution); - - return result; - } - }; - - exports['default'] = Inflector; -}); -define('ember-inflector/lib/system/string', ['exports', 'ember-inflector/lib/system/inflector'], function (exports, _emberInflectorLibSystemInflector) { - 'use strict'; - - function pluralize(word) { - return _emberInflectorLibSystemInflector['default'].inflector.pluralize(word); - } - - function singularize(word) { - return _emberInflectorLibSystemInflector['default'].inflector.singularize(word); - } - - exports.pluralize = pluralize; - exports.singularize = singularize; -}); -define("ember-inflector/lib/system", ["exports", "ember-inflector/lib/system/inflector", "ember-inflector/lib/system/string", "ember-inflector/lib/system/inflections"], function (exports, _emberInflectorLibSystemInflector, _emberInflectorLibSystemString, _emberInflectorLibSystemInflections) { - "use strict"; - - _emberInflectorLibSystemInflector["default"].inflector = new _emberInflectorLibSystemInflector["default"](_emberInflectorLibSystemInflections["default"]); - - exports.Inflector = _emberInflectorLibSystemInflector["default"]; - exports.singularize = _emberInflectorLibSystemString.singularize; - exports.pluralize = _emberInflectorLibSystemString.pluralize; - exports.defaultRules = _emberInflectorLibSystemInflections["default"]; -}); -define('ember-inflector/lib/utils/make-helper', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports['default'] = makeHelper; - - function makeHelper(helperFunction) { - if (_ember['default'].Helper) { - return _ember['default'].Helper.helper(helperFunction); - } - if (_ember['default'].HTMLBars) { - return _ember['default'].HTMLBars.makeBoundHelper(helperFunction); - } - return _ember['default'].Handlebars.makeBoundHelper(helperFunction); - } -}); -define('ember-load-initializers/index', ['exports', 'ember'], function (exports, _ember) { - 'use strict'; - - exports['default'] = function (app, prefix) { - var regex = new RegExp('^' + prefix + '\/((?:instance-)?initializers)\/'); - var getKeys = Object.keys || _ember['default'].keys; - - getKeys(requirejs._eak_seen).map(function (moduleName) { - return { - moduleName: moduleName, - matches: regex.exec(moduleName) - }; - }).filter(function (dep) { - return dep.matches && dep.matches.length === 2; - }).forEach(function (dep) { - var moduleName = dep.moduleName; - - var module = require(moduleName, null, null, true); - if (!module) { - throw new Error(moduleName + ' must export an initializer.'); - } - - var initializerType = _ember['default'].String.camelize(dep.matches[1].substring(0, dep.matches[1].length - 1)); - var initializer = module['default']; - if (!initializer.name) { - var initializerName = moduleName.match(/[^\/]+\/?$/)[0]; - initializer.name = initializerName; - } - - if (app[initializerType]) { - app[initializerType](initializer); - } - }); - }; -}); -define('ember-resolver/container-debug-adapter', ['exports', 'ember', 'ember-resolver/utils/module-registry'], function (exports, _ember, _emberResolverUtilsModuleRegistry) { - 'use strict'; - - var ContainerDebugAdapter = _ember['default'].ContainerDebugAdapter; - - var ModulesContainerDebugAdapter = null; - - function getPod(type, key, prefix) { - var match = key.match(new RegExp('^/?' + prefix + '/(.+)/' + type + '$')); - if (match) { - return match[1]; - } - } - - // Support Ember < 1.5-beta.4 - // TODO: Remove this after 1.5.0 is released - if (typeof ContainerDebugAdapter !== 'undefined') { - - /* - * This module defines a subclass of Ember.ContainerDebugAdapter that adds two - * important features: - * - * 1) is able provide injections to classes that implement `extend` - * (as is typical with Ember). - */ - - ModulesContainerDebugAdapter = ContainerDebugAdapter.extend({ - _moduleRegistry: null, - - init: function init() { - this._super.apply(this, arguments); - - if (!this._moduleRegistry) { - this._moduleRegistry = new _emberResolverUtilsModuleRegistry['default'](); - } - }, - - /** - The container of the application being debugged. - This property will be injected - on creation. - @property container - @default null - */ - - /** - The resolver instance of the application - being debugged. This property will be injected - on creation. - @property resolver - @default null - */ - - /** - Returns true if it is possible to catalog a list of available - classes in the resolver for a given type. - @method canCatalogEntriesByType - @param {string} type The type. e.g. "model", "controller", "route" - @return {boolean} whether a list is available for this type. - */ - canCatalogEntriesByType: function canCatalogEntriesByType() /* type */{ - return true; - }, - - /** - Returns the available classes a given type. - @method catalogEntriesByType - @param {string} type The type. e.g. "model", "controller", "route" - @return {Array} An array of classes. - */ - catalogEntriesByType: function catalogEntriesByType(type) { - var moduleNames = this._moduleRegistry.moduleNames(); - var types = _ember['default'].A(); - - var prefix = this.namespace.modulePrefix; - - for (var i = 0, l = moduleNames.length; i < l; i++) { - var key = moduleNames[i]; - - if (key.indexOf(type) !== -1) { - // Check if it's a pod module - var name = getPod(type, key, this.namespace.podModulePrefix || prefix); - if (!name) { - // Not pod - name = key.split(type + 's/').pop(); - - // Support for different prefix (such as ember-cli addons). - // Uncomment the code below when - // https://github.com/ember-cli/ember-resolver/pull/80 is merged. - - //var match = key.match('^/?(.+)/' + type); - //if (match && match[1] !== prefix) { - // Different prefix such as an addon - //name = match[1] + '@' + name; - //} - } - types.addObject(name); - } - } - return types; - } - }); - } - - exports['default'] = ModulesContainerDebugAdapter; -}); -define('ember-resolver/index', ['exports', 'ember-resolver/resolver'], function (exports, _emberResolverResolver) { - 'use strict'; - - Object.defineProperty(exports, 'default', { - enumerable: true, - get: function get() { - return _emberResolverResolver['default']; - } - }); -}); -define('ember-resolver/resolver', ['exports', 'ember', 'ember-resolver/utils/module-registry', 'ember-resolver/utils/class-factory', 'ember-resolver/utils/make-dictionary'], function (exports, _ember, _emberResolverUtilsModuleRegistry, _emberResolverUtilsClassFactory, _emberResolverUtilsMakeDictionary) { - /*globals require */ - - 'use strict'; - - /* - * This module defines a subclass of Ember.DefaultResolver that adds two - * important features: - * - * 1) The resolver makes the container aware of es6 modules via the AMD - * output. The loader's _moduleEntries is consulted so that classes can be - * resolved directly via the module loader, without needing a manual - * `import`. - * 2) is able to provide injections to classes that implement `extend` - * (as is typical with Ember). - */ - - var _Ember$String = _ember['default'].String; - var underscore = _Ember$String.underscore; - var classify = _Ember$String.classify; - var get = _ember['default'].get; - var DefaultResolver = _ember['default'].DefaultResolver; - - function parseName(fullName) { - /*jshint validthis:true */ - - if (fullName.parsedName === true) { - return fullName; - } - - var prefix, type, name; - var fullNameParts = fullName.split('@'); - - // HTMLBars uses helper:@content-helper which collides - // with ember-cli namespace detection. - // This will be removed in a future release of HTMLBars. - if (fullName !== 'helper:@content-helper' && fullNameParts.length === 2) { - var prefixParts = fullNameParts[0].split(':'); - - if (prefixParts.length === 2) { - prefix = prefixParts[1]; - type = prefixParts[0]; - name = fullNameParts[1]; - } else { - var nameParts = fullNameParts[1].split(':'); - - prefix = fullNameParts[0]; - type = nameParts[0]; - name = nameParts[1]; - } - } else { - fullNameParts = fullName.split(':'); - type = fullNameParts[0]; - name = fullNameParts[1]; - } - - var fullNameWithoutType = name; - var namespace = get(this, 'namespace'); - var root = namespace; - - return { - parsedName: true, - fullName: fullName, - prefix: prefix || this.prefix({ type: type }), - type: type, - fullNameWithoutType: fullNameWithoutType, - name: name, - root: root, - resolveMethodName: "resolve" + classify(type) - }; - } - - function resolveOther(parsedName) { - /*jshint validthis:true */ - - _ember['default'].assert('`modulePrefix` must be defined', this.namespace.modulePrefix); - - var normalizedModuleName = this.findModuleName(parsedName); - - if (normalizedModuleName) { - var defaultExport = this._extractDefaultExport(normalizedModuleName, parsedName); - - if (defaultExport === undefined) { - throw new Error(" Expected to find: '" + parsedName.fullName + "' within '" + normalizedModuleName + "' but got 'undefined'. Did you forget to `export default` within '" + normalizedModuleName + "'?"); - } - - if (this.shouldWrapInClassFactory(defaultExport, parsedName)) { - defaultExport = (0, _emberResolverUtilsClassFactory['default'])(defaultExport); - } - - return defaultExport; - } else { - return this._super(parsedName); - } - } - - // Ember.DefaultResolver docs: - // https://github.com/emberjs/ember.js/blob/master/packages/ember-application/lib/system/resolver.js - var Resolver = DefaultResolver.extend({ - resolveOther: resolveOther, - parseName: parseName, - resolveTemplate: resolveOther, - pluralizedTypes: null, - moduleRegistry: null, - - makeToString: function makeToString(factory, fullName) { - return '' + this.namespace.modulePrefix + '@' + fullName + ':'; - }, - - shouldWrapInClassFactory: function shouldWrapInClassFactory() /* module, parsedName */{ - return false; - }, - - init: function init() { - this._super(); - this.moduleBasedResolver = true; - - if (!this._moduleRegistry) { - this._moduleRegistry = new _emberResolverUtilsModuleRegistry['default'](); - } - - this._normalizeCache = (0, _emberResolverUtilsMakeDictionary['default'])(); - - this.pluralizedTypes = this.pluralizedTypes || (0, _emberResolverUtilsMakeDictionary['default'])(); - - if (!this.pluralizedTypes.config) { - this.pluralizedTypes.config = 'config'; - } - - this._deprecatedPodModulePrefix = false; - }, - - normalize: function normalize(fullName) { - return this._normalizeCache[fullName] || (this._normalizeCache[fullName] = this._normalize(fullName)); - }, - - _normalize: function _normalize(fullName) { - // replace `.` with `/` in order to make nested controllers work in the following cases - // 1. `needs: ['posts/post']` - // 2. `{{render "posts/post"}}` - // 3. `this.render('posts/post')` from Route - var split = fullName.split(':'); - if (split.length > 1) { - return split[0] + ':' + _ember['default'].String.dasherize(split[1].replace(/\./g, '/')); - } else { - return fullName; - } - }, - - pluralize: function pluralize(type) { - return this.pluralizedTypes[type] || (this.pluralizedTypes[type] = type + 's'); - }, - - podBasedLookupWithPrefix: function podBasedLookupWithPrefix(podPrefix, parsedName) { - var fullNameWithoutType = parsedName.fullNameWithoutType; - - if (parsedName.type === 'template') { - fullNameWithoutType = fullNameWithoutType.replace(/^components\//, ''); - } - - return podPrefix + '/' + fullNameWithoutType + '/' + parsedName.type; - }, - - podBasedModuleName: function podBasedModuleName(parsedName) { - var podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix; - - return this.podBasedLookupWithPrefix(podPrefix, parsedName); - }, - - podBasedComponentsInSubdir: function podBasedComponentsInSubdir(parsedName) { - var podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix; - podPrefix = podPrefix + '/components'; - - if (parsedName.type === 'component' || parsedName.fullNameWithoutType.match(/^components/)) { - return this.podBasedLookupWithPrefix(podPrefix, parsedName); - } - }, - - mainModuleName: function mainModuleName(parsedName) { - // if router:main or adapter:main look for a module with just the type first - var tmpModuleName = parsedName.prefix + '/' + parsedName.type; - - if (parsedName.fullNameWithoutType === 'main') { - return tmpModuleName; - } - }, - - defaultModuleName: function defaultModuleName(parsedName) { - return parsedName.prefix + '/' + this.pluralize(parsedName.type) + '/' + parsedName.fullNameWithoutType; - }, - - prefix: function prefix(parsedName) { - var tmpPrefix = this.namespace.modulePrefix; - - if (this.namespace[parsedName.type + 'Prefix']) { - tmpPrefix = this.namespace[parsedName.type + 'Prefix']; - } - - return tmpPrefix; - }, - - /** - A listing of functions to test for moduleName's based on the provided - `parsedName`. This allows easy customization of additional module based - lookup patterns. - @property moduleNameLookupPatterns - @returns {Ember.Array} - */ - moduleNameLookupPatterns: _ember['default'].computed(function () { - return [this.podBasedModuleName, this.podBasedComponentsInSubdir, this.mainModuleName, this.defaultModuleName]; - }), - - findModuleName: function findModuleName(parsedName, loggingDisabled) { - var moduleNameLookupPatterns = this.get('moduleNameLookupPatterns'); - var moduleName; - - for (var index = 0, _length = moduleNameLookupPatterns.length; index < _length; index++) { - var item = moduleNameLookupPatterns[index]; - - var tmpModuleName = item.call(this, parsedName); - - // allow treat all dashed and all underscored as the same thing - // supports components with dashes and other stuff with underscores. - if (tmpModuleName) { - tmpModuleName = this.chooseModuleName(tmpModuleName); - } - - if (tmpModuleName && this._moduleRegistry.has(tmpModuleName)) { - moduleName = tmpModuleName; - } - - if (!loggingDisabled) { - this._logLookup(moduleName, parsedName, tmpModuleName); - } - - if (moduleName) { - return moduleName; - } - } - }, - - chooseModuleName: function chooseModuleName(moduleName) { - var underscoredModuleName = underscore(moduleName); - - if (moduleName !== underscoredModuleName && this._moduleRegistry.has(moduleName) && this._moduleRegistry.has(underscoredModuleName)) { - throw new TypeError("Ambiguous module names: `" + moduleName + "` and `" + underscoredModuleName + "`"); - } - - if (this._moduleRegistry.has(moduleName)) { - return moduleName; - } else if (this._moduleRegistry.has(underscoredModuleName)) { - return underscoredModuleName; - } else { - // workaround for dasherized partials: - // something/something/-something => something/something/_something - var partializedModuleName = moduleName.replace(/\/-([^\/]*)$/, '/_$1'); - - if (this._moduleRegistry.has(partializedModuleName)) { - _ember['default'].deprecate('Modules should not contain underscores. ' + 'Attempted to lookup "' + moduleName + '" which ' + 'was not found. Please rename "' + partializedModuleName + '" ' + 'to "' + moduleName + '" instead.', false); - - return partializedModuleName; - } else { - return moduleName; - } - } - }, - - // used by Ember.DefaultResolver.prototype._logLookup - lookupDescription: function lookupDescription(fullName) { - var parsedName = this.parseName(fullName); - - var moduleName = this.findModuleName(parsedName, true); - - return moduleName; - }, - - // only needed until 1.6.0-beta.2 can be required - _logLookup: function _logLookup(found, parsedName, description) { - if (!_ember['default'].ENV.LOG_MODULE_RESOLVER && !parsedName.root.LOG_RESOLVER) { - return; - } - - var symbol, padding; - - if (found) { - symbol = '[✓]'; - } else { - symbol = '[ ]'; - } - - if (parsedName.fullName.length > 60) { - padding = '.'; - } else { - padding = new Array(60 - parsedName.fullName.length).join('.'); - } - - if (!description) { - description = this.lookupDescription(parsedName); - } - - _ember['default'].Logger.info(symbol, parsedName.fullName, padding, description); - }, - - knownForType: function knownForType(type) { - var moduleKeys = this._moduleRegistry.moduleNames(); - - var items = (0, _emberResolverUtilsMakeDictionary['default'])(); - for (var index = 0, length = moduleKeys.length; index < length; index++) { - var moduleName = moduleKeys[index]; - var fullname = this.translateToContainerFullname(type, moduleName); - - if (fullname) { - items[fullname] = true; - } - } - - return items; - }, - - translateToContainerFullname: function translateToContainerFullname(type, moduleName) { - var prefix = this.prefix({ type: type }); - - // Note: using string manipulation here rather than regexes for better performance. - // pod modules - // '^' + prefix + '/(.+)/' + type + '$' - var podPrefix = prefix + '/'; - var podSuffix = '/' + type; - var start = moduleName.indexOf(podPrefix); - var end = moduleName.indexOf(podSuffix); - - if (start === 0 && end === moduleName.length - podSuffix.length && moduleName.length > podPrefix.length + podSuffix.length) { - return type + ':' + moduleName.slice(start + podPrefix.length, end); - } - - // non-pod modules - // '^' + prefix + '/' + pluralizedType + '/(.+)$' - var pluralizedType = this.pluralize(type); - var nonPodPrefix = prefix + '/' + pluralizedType + '/'; - - if (moduleName.indexOf(nonPodPrefix) === 0 && moduleName.length > nonPodPrefix.length) { - return type + ':' + moduleName.slice(nonPodPrefix.length); - } - }, - - _extractDefaultExport: function _extractDefaultExport(normalizedModuleName) { - var module = require(normalizedModuleName, null, null, true /* force sync */); - - if (module && module['default']) { - module = module['default']; - } - - return module; - } - }); - - Resolver.reopenClass({ - moduleBasedResolver: true - }); - - exports['default'] = Resolver; -}); -define('ember-resolver/utils/class-factory', ['exports'], function (exports) { - 'use strict'; - - exports['default'] = classFactory; - - function classFactory(klass) { - return { - create: function create(injections) { - if (typeof klass.extend === 'function') { - return klass.extend(injections); - } else { - return klass; - } - } - }; - } -}); -define("ember-resolver/utils/create", ["exports", "ember"], function (exports, _ember) { - "use strict"; - - var create = Object.create || _ember["default"].create; - if (!(create && !create(null).hasOwnProperty)) { - throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); - } - - exports["default"] = create; -}); -define('ember-resolver/utils/make-dictionary', ['exports', 'ember-resolver/utils/create'], function (exports, _emberResolverUtilsCreate) { - 'use strict'; - - exports['default'] = makeDictionary; - - function makeDictionary() { - var cache = (0, _emberResolverUtilsCreate['default'])(null); - cache['_dict'] = null; - delete cache['_dict']; - return cache; - } -}); -define('ember-resolver/utils/module-registry', ['exports', 'ember'], function (exports, _ember) { - /*globals requirejs, require */ - - 'use strict'; - - if (typeof requirejs.entries === 'undefined') { - requirejs.entries = requirejs._eak_seen; - } - - function ModuleRegistry(entries) { - this._entries = entries || requirejs.entries; - } - - ModuleRegistry.prototype.moduleNames = function ModuleRegistry_moduleNames() { - return (Object.keys || _ember['default'].keys)(this._entries); - }; - - ModuleRegistry.prototype.has = function ModuleRegistry_has(moduleName) { - return moduleName in this._entries; - }; - - ModuleRegistry.prototype.get = function ModuleRegistry_get(moduleName) { - var exportName = arguments.length <= 1 || arguments[1] === undefined ? 'default' : arguments[1]; - - var module = require(moduleName); - return module && module[exportName]; - }; - - exports['default'] = ModuleRegistry; -}); -;/* jshint ignore:start */ - - - -/* jshint ignore:end */ -//# sourceMappingURL=vendor.map \ No newline at end of file diff --git a/packages/fastboot/test/fixtures/html-entrypoint/index.html b/packages/fastboot/test/fixtures/html-entrypoint/index.html deleted file mode 100644 index 799caba10..000000000 --- a/packages/fastboot/test/fixtures/html-entrypoint/index.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - FastbootTest - - - - - - - - - - - - - diff --git a/packages/fastboot/test/fixtures/html-entrypoint/package.json b/packages/fastboot/test/fixtures/html-entrypoint/package.json deleted file mode 100644 index ca8aed90f..000000000 --- a/packages/fastboot/test/fixtures/html-entrypoint/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "fastboot-test", - "dependencies": {}, - "fastboot": { - "schemaVersion": 5, - "moduleWhitelist": [], - "htmlEntrypoint": "index.html", - "config": { - "fastboot-test": { - "modulePrefix": "fastboot-test", - "environment": "development", - "rootURL": "/", - "locationType": "auto", - "EmberENV": { - "FEATURES": {}, - "EXTEND_PROTOTYPES": { - "Date": false - }, - "_APPLICATION_TEMPLATE_WRAPPER": false, - "_DEFAULT_ASYNC_OBSERVERS": true, - "_JQUERY_INTEGRATION": false, - "_TEMPLATE_ONLY_GLIMMER_COMPONENTS": true - }, - "APP": { - "name": "fastboot-test", - "version": "0.0.0+e168a770", - "autoboot": false - }, - "exportApplicationGlobal": true - } - } - } -} diff --git a/packages/fastboot/test/html-entrypoint-test.js b/packages/fastboot/test/html-entrypoint-test.js index a9290486e..014cd1540 100644 --- a/packages/fastboot/test/html-entrypoint-test.js +++ b/packages/fastboot/test/html-entrypoint-test.js @@ -219,6 +219,96 @@ describe('htmlEntrypoint', function() { expect(scripts).to.deep.equal([]); }); + it('support config in HTML', function() { + let tmpobj = tmp.dirSync(); + let tmpLocation = tmpobj.name; + let configObj = { + 'my-app': { + APP: { + autoboot: false, + }, + configKey: 'someValue', + }, + 'my-engine': { + APP: { + autoboot: false, + }, + engineKey: 'engineValue', + }, + }; + let metaTags = Object.entries(configObj) + .map( + ([name, options]) => + `` + ) + .join('\n'); + + let project = { + 'index.html': ` + + + ${metaTags} + + + + + + `, + }; + + fixturify.writeSync(tmpLocation, project); + + let { config } = htmlEntrypoint('my-app', tmpLocation, 'index.html'); + expect(config).to.deep.equal(configObj); + }); + + it('support config fallback name "config/environement" instead of fastboot-environement in HTML', function() { + let tmpobj = tmp.dirSync(); + let tmpLocation = tmpobj.name; + let configObj = { + 'my-app': { + APP: { + autoboot: false, + }, + configKey: 'someValue', + }, + 'my-engine': { + APP: { + autoboot: false, + }, + engineKey: 'engineValue', + }, + }; + let metaTags = Object.entries(configObj) + .map( + ([name, options]) => + `` + ) + .join('\n'); + + let project = { + 'index.html': ` + + + ${metaTags} + + + + + + `, + }; + + fixturify.writeSync(tmpLocation, project); + + let { config } = htmlEntrypoint('my-app', tmpLocation, 'index.html'); + expect(config).to.deep.equal(configObj); + }); + it('understands customized rootURL', function() { let tmpobj = tmp.dirSync(); let tmpLocation = tmpobj.name; @@ -228,9 +318,21 @@ describe('htmlEntrypoint', function() { }, }; + let metaTags = Object.entries(config) + .map( + ([name, options]) => + `` + ) + .join('\n'); + let project = { 'index.html': ` + + ${metaTags} + @@ -240,7 +342,7 @@ describe('htmlEntrypoint', function() { fixturify.writeSync(tmpLocation, project); - let { scripts } = htmlEntrypoint('my-app', tmpLocation, 'index.html', config); + let { scripts } = htmlEntrypoint('my-app', tmpLocation, 'index.html'); expect(scripts).to.deep.equal([`${tmpLocation}/bar.js`]); }); }); diff --git a/test-packages/basic-app/test/package-json-test.js b/test-packages/basic-app/test/package-json-test.js index 0cc69fc81..592c9f472 100644 --- a/test-packages/basic-app/test/package-json-test.js +++ b/test-packages/basic-app/test/package-json-test.js @@ -36,7 +36,7 @@ describe("generating package.json", function () { it("contains a schema version", function () { let pkg = fs.readJSONSync("dist/package.json"); - expect(pkg.fastboot.schemaVersion).to.deep.equal(3); + expect(pkg.fastboot.schemaVersion).to.deep.equal(5); }); it("contains a whitelist of allowed module names", function () { @@ -54,25 +54,6 @@ describe("generating package.json", function () { ]); }); - it("contains a manifest of FastBoot assets", function () { - let pkg = fs.readJSONSync("dist/package.json"); - - expect(pkg.fastboot.manifest).to.deep.equal({ - appFiles: [ - "assets/basic-app.js", - "assets/basic-app-fastboot.js", - "example-addon/bar.js", - ], - htmlFile: "index.html", - vendorFiles: [ - "example-addon/foo.js", - "assets/vendor.js", - "assets/auto-import-fastboot.js", - "ember-fetch/fetch-fastboot.js", - ], - }); - }); - it("contains a list of whitelisted hosts from environment.js", function () { let pkg = fs.readJSONSync("dist/package.json"); @@ -86,74 +67,7 @@ describe("generating package.json", function () { it("contains app name", function () { let pkg = fs.readJSONSync("dist/package.json"); - expect(pkg.fastboot.appName).to.equal("basic-app"); - }); - - it("contains the application config", function () { - let pkg = fs.readJSONSync("dist/package.json"); - - let config = pkg.fastboot.config["basic-app"]; - - expect(config.APP.version).to.be; - - delete config.APP.version; - expect(config).to.deep.equal({ - modulePrefix: "basic-app", - environment: "development", - rootURL: "/", - locationType: "auto", - EmberENV: { - EXTEND_PROTOTYPES: { - Date: false, - }, - FEATURES: {}, - _APPLICATION_TEMPLATE_WRAPPER: false, - _DEFAULT_ASYNC_OBSERVERS: true, - _JQUERY_INTEGRATION: false, - _TEMPLATE_ONLY_GLIMMER_COMPONENTS: true, - }, - APP: { - name: "basic-app", - autoboot: false, - }, - fastboot: { - hostWhitelist: [ - "example.com", - "subdomain.example.com", - "/localhost:\\d+/", - ], - }, - exportApplicationGlobal: true, - }); - }); - - it("contains additional config from example-addon", function () { - let pkg = fs.readJSONSync("dist/package.json"); - - expect(pkg.fastboot.config["foo"]).to.equal("bar"); - }); - - }); - - describe("with production FastBoot builds", function () { - before(async function () { - await execa("yarn", ["build", "--environment=production"]); - }); - - it("contains a manifest of FastBoot assets", function () { - let pkg = fs.readJSONSync("dist/package.json"); - - let manifest = pkg.fastboot.manifest; - - manifest.appFiles.forEach((file) => { - expect(`dist/${file}`).to.be.a.file(); - }); - - expect(`dist/${manifest.htmlFile}`).to.be.a.file(); - - manifest.vendorFiles.forEach((file) => { - expect(`dist/${file}`).to.be.a.file(); - }); + expect(pkg.name).to.equal("basic-app"); }); }); }); diff --git a/test-packages/custom-fastboot-app/package.json b/test-packages/custom-fastboot-app/package.json index f2027bd30..f801dc89c 100644 --- a/test-packages/custom-fastboot-app/package.json +++ b/test-packages/custom-fastboot-app/package.json @@ -53,6 +53,7 @@ "eslint": "^7.1.0", "eslint-plugin-ember": "^8.6.0", "eslint-plugin-node": "^11.1.0", + "jsdom": "^16.2.2", "loader.js": "^4.7.0", "mocha": "^8.0.1", "npm-run-all": "^4.1.5", diff --git a/test-packages/custom-fastboot-app/public/custom-index.html b/test-packages/custom-fastboot-app/public/custom-index.html index a21d3d3e3..129015759 100644 --- a/test-packages/custom-fastboot-app/public/custom-index.html +++ b/test-packages/custom-fastboot-app/public/custom-index.html @@ -10,12 +10,12 @@ - + - +
{{author}}
Called {{i}} times
{{props.title}}
by {{byline}}
Hello world
by Yehuda Katz
Goodbye world