UNPKG

ember-source

Version:

A JavaScript framework for creating ambitious web applications

1,213 lines (1,112 loc) 2.03 MB
/*! * @overview Ember - JavaScript Application Framework * @copyright Copyright 2011 Tilde Inc. and contributors * Portions Copyright 2006-2011 Strobe Inc. * Portions Copyright 2008-2011 Apple Inc. All rights reserved. * @license Licensed under MIT license * See https://raw.github.com/emberjs/ember.js/master/LICENSE * @version 6.1.0 */ /* eslint-disable no-var */ /* globals global globalThis self */ /* eslint-disable-next-line no-unused-vars */ var define, require; (function () { var globalObj = typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : null; if (globalObj === null) { throw new Error('unable to locate global object'); } if (typeof globalObj.define === 'function' && typeof globalObj.require === 'function') { define = globalObj.define; require = globalObj.require; return; } var registry = Object.create(null); var seen = Object.create(null); function missingModule(name, referrerName) { if (referrerName) { throw new Error('Could not find module ' + name + ' required by: ' + referrerName); } else { throw new Error('Could not find module ' + name); } } function internalRequire(_name, referrerName) { var name = _name; var mod = registry[name]; if (!mod) { name = name + '/index'; mod = registry[name]; } var exports = seen[name]; if (exports !== undefined) { return exports; } exports = seen[name] = {}; if (!mod) { missingModule(_name, referrerName); } var deps = mod.deps; var callback = mod.callback; var reified = new Array(deps.length); for (var i = 0; i < deps.length; i++) { if (deps[i] === 'exports') { reified[i] = exports; } else if (deps[i] === 'require') { reified[i] = require; } else { reified[i] = require(deps[i], name); } } var result = callback.apply(this, reified); if (!deps.includes('exports') || result !== undefined) { exports = seen[name] = result; } return exports; } require = function (name) { return internalRequire(name, null); }; define = function (name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; // setup `require` module require['default'] = require; require.has = function registryHas(moduleName) { return Boolean(registry[moduleName]) || Boolean(registry[moduleName + '/index']); }; require._eak_seen = require.entries = registry; })(); (function () { 'use strict'; function d(name, mod) { Object.defineProperty(mod, '__esModule', { value: true }); define(name, [], () => mod); } // check if window exists and actually is the global const hasDOM = typeof self === 'object' && self !== null && self.Object === Object && typeof Window !== 'undefined' && self.constructor === Window && typeof document === 'object' && document !== null && self.document === document && typeof location === 'object' && location !== null && self.location === location && typeof history === 'object' && history !== null && self.history === history && typeof navigator === 'object' && navigator !== null && self.navigator === navigator && typeof navigator.userAgent === 'string'; const window$1 = hasDOM ? self : null; const location$1 = hasDOM ? self.location : null; const history$1 = hasDOM ? self.history : null; const userAgent = hasDOM ? self.navigator.userAgent : 'Lynx (textmode)'; const isChrome = hasDOM ? typeof chrome === 'object' && !(typeof opera === 'object') : false; const isFirefox = hasDOM ? /Firefox|FxiOS/.test(userAgent) : false; const emberinternalsBrowserEnvironmentIndex = /*#__PURE__*/Object.defineProperty({ __proto__: null, hasDOM, history: history$1, isChrome, isFirefox, location: location$1, userAgent, window: window$1 }, Symbol.toStringTag, { value: 'Module' }); /** Strongly hint runtimes to intern the provided string. When do I need to use this function? For the most part, never. Pre-mature optimization is bad, and often the runtime does exactly what you need it to, and more often the trade-off isn't worth it. Why? Runtimes store strings in at least 2 different representations: Ropes and Symbols (interned strings). The Rope provides a memory efficient data-structure for strings created from concatenation or some other string manipulation like splitting. Unfortunately checking equality of different ropes can be quite costly as runtimes must resort to clever string comparison algorithms. These algorithms typically cost in proportion to the length of the string. Luckily, this is where the Symbols (interned strings) shine. As Symbols are unique by their string content, equality checks can be done by pointer comparison. How do I know if my string is a rope or symbol? Typically (warning general sweeping statement, but truthy in runtimes at present) static strings created as part of the JS source are interned. Strings often used for comparisons can be interned at runtime if some criteria are met. One of these criteria can be the size of the entire rope. For example, in chrome 38 a rope longer then 12 characters will not intern, nor will segments of that rope. Some numbers: http://jsperf.com/eval-vs-keys/8 Known Trick™ @private @return {String} interned version of the provided string */ function intern$1(str) { let obj = Object.create(null); obj[str] = 1; for (let key in obj) { if (key === str) { return key; } } return str; } /** Returns whether Type(value) is Object. Useful for checking whether a value is a valid WeakMap key. Refs: https://tc39.github.io/ecma262/#sec-typeof-operator-runtime-semantics-evaluation https://tc39.github.io/ecma262/#sec-weakmap.prototype.set @private @function isObject */ function isObject$1(value) { return value !== null && (typeof value === 'object' || typeof value === 'function'); } /** @module @ember/object */ /** @private @return {Number} the uuid */ let _uuid$1 = 0; /** Generates a universally unique identifier. This method is used internally by Ember for assisting with the generation of GUID's and other unique identifiers. @public @return {Number} [description] */ function uuid$1() { return ++_uuid$1; } /** Prefix used for guids through out Ember. @private @property GUID_PREFIX @for Ember @type String @final */ const GUID_PREFIX = 'ember'; // Used for guid generation... const OBJECT_GUIDS = new WeakMap(); const NON_OBJECT_GUIDS = new Map(); /** A unique key used to assign guids and other private metadata to objects. If you inspect an object in your browser debugger you will often see these. They can be safely ignored. On browsers that support it, these properties are added with enumeration disabled so they won't show up when you iterate over your properties. @private @property GUID_KEY @for Ember @type String @final */ const GUID_KEY = intern$1(`__ember${Date.now()}`); /** Generates a new guid, optionally saving the guid to the object that you pass in. You will rarely need to use this method. Instead you should call `guidFor(obj)`, which return an existing guid if available. @private @method generateGuid @static @for @ember/object/internals @param {Object} [obj] Object the guid will be used for. If passed in, the guid will be saved on the object and reused whenever you pass the same object again. If no object is passed, just generate a new guid. @param {String} [prefix] Prefix to place in front of the guid. Useful when you want to separate the guid into separate namespaces. @return {String} the guid */ function generateGuid(obj, prefix = GUID_PREFIX) { let guid = prefix + uuid$1().toString(); if (isObject$1(obj)) { OBJECT_GUIDS.set(obj, guid); } return guid; } /** Returns a unique id for the object. If the object does not yet have a guid, one will be assigned to it. You can call this on any object, `EmberObject`-based or not. You can also use this method on DOM Element objects. @public @static @method guidFor @for @ember/object/internals @param {Object} obj any object, string, number, Element, or primitive @return {String} the unique guid for this instance. */ function guidFor(value) { let guid; if (isObject$1(value)) { guid = OBJECT_GUIDS.get(value); if (guid === undefined) { guid = `${GUID_PREFIX}${uuid$1()}`; OBJECT_GUIDS.set(value, guid); } } else { guid = NON_OBJECT_GUIDS.get(value); if (guid === undefined) { let type = typeof value; if (type === 'string') { guid = `st${uuid$1()}`; } else if (type === 'number') { guid = `nu${uuid$1()}`; } else if (type === 'symbol') { guid = `sy${uuid$1()}`; } else { guid = `(${value})`; } NON_OBJECT_GUIDS.set(value, guid); } } return guid; } const GENERATED_SYMBOLS = []; function isInternalSymbol(possibleSymbol) { return GENERATED_SYMBOLS.indexOf(possibleSymbol) !== -1; } // Some legacy symbols still need to be enumerable for a variety of reasons. // This code exists for that, and as a fallback in IE11. In general, prefer // `symbol` below when creating a new symbol. function enumerableSymbol(debugName) { // TODO: Investigate using platform symbols, but we do not // want to require non-enumerability for this API, which // would introduce a large cost. let id = GUID_KEY + Math.floor(Math.random() * Date.now()).toString(); let symbol = intern$1(`__${debugName}${id}__`); { GENERATED_SYMBOLS.push(symbol); } return symbol; } const symbol = Symbol; // the delete is meant to hint at runtimes that this object should remain in // dictionary mode. This is clearly a runtime specific hack, but currently it // appears worthwhile in some usecases. Please note, these deletes do increase // the cost of creation dramatically over a plain Object.create. And as this // only makes sense for long-lived dictionaries that aren't instantiated often. function makeDictionary(parent) { let dict = Object.create(parent); dict['_dict'] = null; delete dict['_dict']; return dict; } let getDebugName; { let getFunctionName = fn => { let functionName = fn.name; if (functionName === undefined) { let match = Function.prototype.toString.call(fn).match(/function (\w+)\s*\(/); functionName = match && match[1] || ''; } return functionName.replace(/^bound /, ''); }; let getObjectName = obj => { let name; let className; if (obj.constructor && obj.constructor !== Object) { className = getFunctionName(obj.constructor); } if ('toString' in obj && obj.toString !== Object.prototype.toString && obj.toString !== Function.prototype.toString) { name = obj.toString(); } // If the class has a decent looking name, and the `toString` is one of the // default Ember toStrings, replace the constructor portion of the toString // with the class name. We check the length of the class name to prevent doing // this when the value is minified. if (name && name.match(/<.*:ember\d+>/) && className && className[0] !== '_' && className.length > 2 && className !== 'Class') { return name.replace(/<.*:/, `<${className}:`); } return name || className; }; let getPrimitiveName = value => { return String(value); }; getDebugName = value => { if (typeof value === 'function') { return getFunctionName(value) || `(unknown function)`; } else if (typeof value === 'object' && value !== null) { return getObjectName(value) || `(unknown object)`; } else { return getPrimitiveName(value); } }; } const getDebugName$1 = getDebugName; const HAS_SUPER_PATTERN = /\.(_super|call\(this|apply\(this)/; const fnToString = Function.prototype.toString; const checkHasSuper = (() => { let sourceAvailable = fnToString.call(function () { return this; }).indexOf('return this') > -1; if (sourceAvailable) { return function checkHasSuper(func) { return HAS_SUPER_PATTERN.test(fnToString.call(func)); }; } return function checkHasSuper() { return true; }; })(); const HAS_SUPER_MAP = new WeakMap(); const ROOT = Object.freeze(function () {}); HAS_SUPER_MAP.set(ROOT, false); function hasSuper(func) { let hasSuper = HAS_SUPER_MAP.get(func); if (hasSuper === undefined) { hasSuper = checkHasSuper(func); HAS_SUPER_MAP.set(func, hasSuper); } return hasSuper; } class ObserverListenerMeta { listeners = undefined; observers = undefined; } const OBSERVERS_LISTENERS_MAP = new WeakMap(); function createObserverListenerMetaFor(fn) { let meta = OBSERVERS_LISTENERS_MAP.get(fn); if (meta === undefined) { meta = new ObserverListenerMeta(); OBSERVERS_LISTENERS_MAP.set(fn, meta); } return meta; } function observerListenerMetaFor(fn) { return OBSERVERS_LISTENERS_MAP.get(fn); } function setObservers(func, observers) { let meta = createObserverListenerMetaFor(func); meta.observers = observers; } function setListeners(func, listeners) { let meta = createObserverListenerMetaFor(func); meta.listeners = listeners; } const IS_WRAPPED_FUNCTION_SET = new WeakSet(); /** Wraps the passed function so that `this._super` will point to the superFunc when the function is invoked. This is the primitive we use to implement calls to super. @private @method wrap @for Ember @param {Function} func The function to call @param {Function} superFunc The super function. @return {Function} wrapped function. */ function wrap$1(func, superFunc) { if (!hasSuper(func)) { return func; } // ensure an unwrapped super that calls _super is wrapped with a terminal _super if (!IS_WRAPPED_FUNCTION_SET.has(superFunc) && hasSuper(superFunc)) { return _wrap(func, _wrap(superFunc, ROOT)); } return _wrap(func, superFunc); } function _wrap(func, superFunc) { function superWrapper() { let orig = this._super; this._super = superFunc; let ret = func.apply(this, arguments); this._super = orig; return ret; } IS_WRAPPED_FUNCTION_SET.add(superWrapper); let meta = OBSERVERS_LISTENERS_MAP.get(func); if (meta !== undefined) { OBSERVERS_LISTENERS_MAP.set(superWrapper, meta); } return superWrapper; } function lookupDescriptor(obj, keyName) { let current = obj; do { let descriptor = Object.getOwnPropertyDescriptor(current, keyName); if (descriptor !== undefined) { return descriptor; } current = Object.getPrototypeOf(current); } while (current !== null); return null; } /** Checks to see if the `methodName` exists on the `obj`. ```javascript let foo = { bar: function() { return 'bar'; }, baz: null }; Ember.canInvoke(foo, 'bar'); // true Ember.canInvoke(foo, 'baz'); // false Ember.canInvoke(foo, 'bat'); // false ``` @method canInvoke @for Ember @param {Object} obj The object to check for the method @param {String} methodName The method name to check for @return {Boolean} @private */ function canInvoke(obj, methodName) { return obj != null && typeof obj[methodName] === 'function'; } /** @module @ember/utils */ const NAMES = new WeakMap(); function setName(obj, name) { if (isObject$1(obj)) NAMES.set(obj, name); } function getName(obj) { return NAMES.get(obj); } const objectToString$1 = Object.prototype.toString; function isNone$1(obj) { return obj === null || obj === undefined; } /* A `toString` util function that supports objects without a `toString` method, e.g. an object created with `Object.create(null)`. */ function toString$1(obj) { if (typeof obj === 'string') { return obj; } if (null === obj) return 'null'; if (undefined === obj) return 'undefined'; if (Array.isArray(obj)) { // Reimplement Array.prototype.join according to spec (22.1.3.13) // Changing ToString(element) with this safe version of ToString. let r = ''; for (let k = 0; k < obj.length; k++) { if (k > 0) { r += ','; } if (!isNone$1(obj[k])) { r += toString$1(obj[k]); } } return r; } if (typeof obj.toString === 'function') { return obj.toString(); } return objectToString$1.call(obj); } const PROXIES = new WeakSet(); function isProxy(value) { if (isObject$1(value)) { return PROXIES.has(value); } return false; } function setProxy(object) { if (isObject$1(object)) { PROXIES.add(object); } } class Cache { size = 0; misses = 0; hits = 0; constructor(limit, func, store = new Map()) { this.limit = limit; this.func = func; this.store = store; } get(key) { if (this.store.has(key)) { this.hits++; // SAFETY: we know the value is present because `.has(key)` was `true`. return this.store.get(key); } else { this.misses++; return this.set(key, this.func(key)); } } set(key, value) { if (this.limit > this.size) { this.size++; this.store.set(key, value); } return value; } purge() { this.store.clear(); this.size = 0; this.hits = 0; this.misses = 0; } } /* globals window, self */ // from lodash to catch fake globals function checkGlobal(value) { return value && value.Object === Object ? value : undefined; } // element ids can ruin global miss checks function checkElementIdShadowing(value) { return value && value.nodeType === undefined ? value : undefined; } // export real global const global$1 = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || typeof mainContext !== 'undefined' && mainContext || // set before strict mode in Ember loader/wrapper new Function('return this')(); // eval outside of strict mode // legacy imports/exports/lookup stuff (should we keep this??) const context$1 = function (global, Ember) { return Ember === undefined ? { imports: global, exports: global, lookup: global } : { // import jQuery imports: Ember.imports || global, // export Ember exports: Ember.exports || global, // search for Namespaces lookup: Ember.lookup || global }; }(global$1, global$1.Ember); function getLookup() { return context$1.lookup; } function setLookup(value) { context$1.lookup = value; } /** The hash of environment variables used to control various configuration settings. To specify your own or override default settings, add the desired properties to a global hash named `EmberENV` (or `ENV` for backwards compatibility with earlier versions of Ember). The `EmberENV` hash must be created before loading Ember. @class EmberENV @type Object @public */ const ENV = { ENABLE_OPTIONAL_FEATURES: false, /** Determines whether Ember should add to `Array` native object prototypes, a few extra methods in order to provide a more friendly API. The behavior from setting this option to `true` was deprecated in Ember 5.10. @property EXTEND_PROTOTYPES @type Boolean @default true @for EmberENV @private @deprecated in v5.10 */ EXTEND_PROTOTYPES: { Array: false }, /** The `LOG_STACKTRACE_ON_DEPRECATION` property, when true, tells Ember to log a full stack trace during deprecation warnings. @property LOG_STACKTRACE_ON_DEPRECATION @type Boolean @default true @for EmberENV @public */ LOG_STACKTRACE_ON_DEPRECATION: true, /** The `LOG_VERSION` property, when true, tells Ember to log versions of all dependent libraries in use. @property LOG_VERSION @type Boolean @default true @for EmberENV @public */ LOG_VERSION: true, RAISE_ON_DEPRECATION: false, STRUCTURED_PROFILE: false, /** Whether to perform extra bookkeeping needed to make the `captureRenderTree` API work. This has to be set before the ember JavaScript code is evaluated. This is usually done by setting `window.EmberENV = { _DEBUG_RENDER_TREE: true };` before the "vendor" `<script>` tag in `index.html`. Setting the flag after Ember is already loaded will not work correctly. It may appear to work somewhat, but fundamentally broken. This is not intended to be set directly. Ember Inspector will enable the flag on behalf of the user as needed. This flag is always on in development mode. The flag is off by default in production mode, due to the cost associated with the the bookkeeping work. The expected flow is that Ember Inspector will ask the user to refresh the page after enabling the feature. It could also offer a feature where the user add some domains to the "always on" list. In either case, Ember Inspector will inject the code on the page to set the flag if needed. @property _DEBUG_RENDER_TREE @for EmberENV @type Boolean @default false @private */ _DEBUG_RENDER_TREE: true /* DEBUG */, /** Whether to force all deprecations to be enabled. This is used internally by Ember to enable deprecations in tests. It is not intended to be set in projects. @property _ALL_DEPRECATIONS_ENABLED @for EmberENV @type Boolean @default false @private */ _ALL_DEPRECATIONS_ENABLED: false, /** Override the version of ember-source used to determine when deprecations "break". This is used internally by Ember to test with deprecated features "removed". This is never intended to be set by projects. @property _OVERRIDE_DEPRECATION_VERSION @for EmberENV @type string | null @default null @private */ _OVERRIDE_DEPRECATION_VERSION: null, /** Whether the app defaults to using async observers. This is not intended to be set directly, as the implementation may change in the future. Use `@ember/optional-features` instead. @property _DEFAULT_ASYNC_OBSERVERS @for EmberENV @type Boolean @default false @private */ _DEFAULT_ASYNC_OBSERVERS: false, /** Whether the app still has default record-loading behavior in the model hook from RFC https://rfcs.emberjs.com/id/0774-implicit-record-route-loading This will also remove the default store property from the route. This is not intended to be set directly, as the implementation may change in the future. Use `@ember/optional-features` instead. @property _NO_IMPLICIT_ROUTE_MODEL @for EmberENV @type Boolean @default false @private */ _NO_IMPLICIT_ROUTE_MODEL: false, /** Controls the maximum number of scheduled rerenders without "settling". In general, applications should not need to modify this environment variable, but please open an issue so that we can determine if a better default value is needed. @property _RERENDER_LOOP_LIMIT @for EmberENV @type number @default 1000 @private */ _RERENDER_LOOP_LIMIT: 1000, EMBER_LOAD_HOOKS: {}, FEATURES: {} }; (EmberENV => { if (typeof EmberENV !== 'object' || EmberENV === null) return; for (let flag in EmberENV) { if (!Object.prototype.hasOwnProperty.call(EmberENV, flag) || flag === 'EXTEND_PROTOTYPES' || flag === 'EMBER_LOAD_HOOKS') continue; let defaultValue = ENV[flag]; if (defaultValue === true) { ENV[flag] = EmberENV[flag] !== false; } else if (defaultValue === false) { ENV[flag] = EmberENV[flag] === true; } else { ENV[flag] = EmberENV[flag]; } } // TODO: Remove in Ember 6.5. This setting code for EXTEND_PROTOTYPES // should stay for at least an LTS cycle so that users get the explicit // deprecation exception when it breaks in >= 6.0.0. let { EXTEND_PROTOTYPES } = EmberENV; if (EXTEND_PROTOTYPES !== undefined) { if (typeof EXTEND_PROTOTYPES === 'object' && EXTEND_PROTOTYPES !== null) { ENV.EXTEND_PROTOTYPES.Array = EXTEND_PROTOTYPES.Array !== false; } else { ENV.EXTEND_PROTOTYPES.Array = EXTEND_PROTOTYPES !== false; } } // TODO this does not seem to be used by anything, // can we remove it? do we need to deprecate it? let { EMBER_LOAD_HOOKS } = EmberENV; if (typeof EMBER_LOAD_HOOKS === 'object' && EMBER_LOAD_HOOKS !== null) { for (let hookName in EMBER_LOAD_HOOKS) { if (!Object.prototype.hasOwnProperty.call(EMBER_LOAD_HOOKS, hookName)) continue; let hooks = EMBER_LOAD_HOOKS[hookName]; if (Array.isArray(hooks)) { ENV.EMBER_LOAD_HOOKS[hookName] = hooks.filter(hook => typeof hook === 'function'); } } } let { FEATURES } = EmberENV; if (typeof FEATURES === 'object' && FEATURES !== null) { for (let feature in FEATURES) { if (!Object.prototype.hasOwnProperty.call(FEATURES, feature)) continue; ENV.FEATURES[feature] = FEATURES[feature] === true; } } { ENV._DEBUG_RENDER_TREE = true; } })(global$1.EmberENV); function getENV() { return ENV; } const emberinternalsEnvironmentIndex = /*#__PURE__*/Object.defineProperty({ __proto__: null, ENV, context: context$1, getENV, getLookup, global: global$1, setLookup }, Symbol.toStringTag, { value: 'Module' }); let assert$1 = () => {}; function setAssert(implementation) { assert$1 = implementation; return implementation; } { /** Verify that a certain expectation is met, or throw a exception otherwise. This is useful for communicating assumptions in the code to other human readers as well as catching bugs that accidentally violates these expectations. Assertions are removed from production builds, so they can be freely added for documentation and debugging purposes without worries of incuring any performance penalty. However, because of that, they should not be used for checks that could reasonably fail during normal usage. Furthermore, care should be taken to avoid accidentally relying on side-effects produced from evaluating the condition itself, since the code will not run in production. ```javascript import { assert } from '@ember/debug'; // Test for truthiness assert('Must pass a string', typeof str === 'string'); // Fail unconditionally assert('This code path should never be run'); ``` @method assert @static @for @ember/debug @param {String} description Describes the expectation. This will become the text of the Error thrown if the assertion fails. @param {any} condition Must be truthy for the assertion to pass. If falsy, an exception will be thrown. @public @since 1.0.0 */ // eslint-disable-next-line no-inner-declarations function assert(desc, test) { if (!test) { throw new Error(`Assertion Failed: ${desc}`); } } setAssert(assert); } let HANDLERS = {}; let registerHandler$2 = function registerHandler(_type, _callback) {}; let invoke = () => {}; { registerHandler$2 = function registerHandler(type, callback) { let nextHandler = HANDLERS[type] || (() => {}); HANDLERS[type] = (message, options) => { callback(message, options, nextHandler); }; }; invoke = function invoke(type, message, test, options) { if (test) { return; } let handlerForType = HANDLERS[type]; if (handlerForType) { handlerForType(message, options); } }; } const emberDebugLibHandlers = /*#__PURE__*/Object.defineProperty({ __proto__: null, HANDLERS, get invoke () { return invoke; }, get registerHandler () { return registerHandler$2; } }, Symbol.toStringTag, { value: 'Module' }); // This is a "global", but instead of declaring it as `declare global`, which // will expose it to all other modules, declare it *locally* (and don't export // it) so that it has the desired "private global" semantics -- however odd that // particular notion is. /** @module @ember/debug @public */ /** Allows for runtime registration of handler functions that override the default deprecation behavior. Deprecations are invoked by calls to [@ember/debug/deprecate](/ember/release/classes/@ember%2Fdebug/methods/deprecate?anchor=deprecate). The following example demonstrates its usage by registering a handler that throws an error if the message contains the word "should", otherwise defers to the default handler. ```javascript import { registerDeprecationHandler } from '@ember/debug'; registerDeprecationHandler((message, options, next) => { if (message.indexOf('should') !== -1) { throw new Error(`Deprecation message with should: ${message}`); } else { // defer to whatever handler was registered before this one next(message, options); } }); ``` The handler function takes the following arguments: <ul> <li> <code>message</code> - The message received from the deprecation call.</li> <li> <code>options</code> - An object passed in with the deprecation call containing additional information including:</li> <ul> <li> <code>id</code> - An id of the deprecation in the form of <code>package-name.specific-deprecation</code>.</li> <li> <code>until</code> - The Ember version number the feature and deprecation will be removed in.</li> </ul> <li> <code>next</code> - A function that calls into the previously registered handler.</li> </ul> @public @static @method registerDeprecationHandler @for @ember/debug @param handler {Function} A function to handle deprecation calls. @since 2.1.0 */ let registerHandler$1 = () => {}; let missingOptionsDeprecation$1; let missingOptionsIdDeprecation$1; let missingOptionDeprecation = () => ''; let deprecate$3 = () => {}; { registerHandler$1 = function registerHandler(handler) { registerHandler$2('deprecate', handler); }; let formatMessage = function formatMessage(_message, options) { let message = _message; if (options?.id) { message = message + ` [deprecation id: ${options.id}]`; } if (options?.until) { message = message + ` This will be removed in ${options.for} ${options.until}.`; } if (options?.url) { message += ` See ${options.url} for more details.`; } return message; }; registerHandler$1(function logDeprecationToConsole(message, options) { let updatedMessage = formatMessage(message, options); console.warn(`DEPRECATION: ${updatedMessage}`); // eslint-disable-line no-console }); let captureErrorForStack; if (new Error().stack) { captureErrorForStack = () => new Error(); } else { captureErrorForStack = () => { try { __fail__.fail(); return; } catch (e) { return e; } }; } registerHandler$1(function logDeprecationStackTrace(message, options, next) { if (ENV.LOG_STACKTRACE_ON_DEPRECATION) { let stackStr = ''; let error = captureErrorForStack(); let stack; if (error instanceof Error) { if (error.stack) { if (error['arguments']) { // Chrome stack = error.stack.replace(/^\s+at\s+/gm, '').replace(/^([^(]+?)([\n$])/gm, '{anonymous}($1)$2').replace(/^Object.<anonymous>\s*\(([^)]+)\)/gm, '{anonymous}($1)').split('\n'); stack.shift(); } else { // Firefox stack = error.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n'); } stackStr = `\n ${stack.slice(2).join('\n ')}`; } } let updatedMessage = formatMessage(message, options); console.warn(`DEPRECATION: ${updatedMessage}${stackStr}`); // eslint-disable-line no-console } else { next(message, options); } }); registerHandler$1(function raiseOnDeprecation(message, options, next) { if (ENV.RAISE_ON_DEPRECATION) { let updatedMessage = formatMessage(message); throw new Error(updatedMessage); } else { next(message, options); } }); missingOptionsDeprecation$1 = 'When calling `deprecate` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include `id` and `until` properties.'; missingOptionsIdDeprecation$1 = 'When calling `deprecate` you must provide `id` in options.'; missingOptionDeprecation = (id, missingOption) => { return `When calling \`deprecate\` you must provide \`${missingOption}\` in options. Missing options.${missingOption} in "${id}" deprecation`; }; /** @module @ember/debug @public */ /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). Ember itself leverages [Semantic Versioning](https://semver.org) to aid projects in keeping up with changes to the framework. Before any functionality or API is removed, it first flows linearly through a deprecation staging process. The staging process currently contains two stages: available and enabled. Deprecations are initially released into the 'available' stage. Deprecations will stay in this stage until the replacement API has been marked as a recommended practice via the RFC process and the addon ecosystem has generally adopted the change. Once a deprecation meets the above criteria, it will move into the 'enabled' stage where it will remain until the functionality or API is eventually removed. For application and addon developers, "available" deprecations are not urgent and "enabled" deprecations require action. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript import { deprecate } from '@ember/debug'; deprecate( 'Use of `assign` has been deprecated. Please use `Object.assign` or the spread operator instead.', false, { id: 'ember-polyfills.deprecate-assign', until: '5.0.0', url: 'https://deprecations.emberjs.com/v4.x/#toc_ember-polyfills-deprecate-assign', for: 'ember-source', since: { available: '4.0.0', enabled: '4.0.0', }, } ); ``` @method deprecate @for @ember/debug @param {String} message A description of the deprecation. @param {Boolean} test A boolean. If falsy, the deprecation will be displayed. @param {Object} options @param {String} options.id A unique id for this deprecation. The id can be used by Ember debugging tools to change the behavior (raise, log or silence) for that specific deprecation. The id should be namespaced by dots, e.g. "view.helper.select". @param {string} options.until The version of Ember when this deprecation warning will be removed. @param {String} options.for A namespace for the deprecation, usually the package name @param {Object} options.since Describes when the deprecation became available and enabled. @param {String} [options.url] An optional url to the transition guide on the emberjs.com website. @static @public @since 1.0.0 */ deprecate$3 = function deprecate(message, test, options) { assert$1(missingOptionsDeprecation$1, Boolean(options && (options.id || options.until))); assert$1(missingOptionsIdDeprecation$1, Boolean(options.id)); assert$1(missingOptionDeprecation(options.id, 'until'), Boolean(options.until)); assert$1(missingOptionDeprecation(options.id, 'for'), Boolean(options.for)); assert$1(missingOptionDeprecation(options.id, 'since'), Boolean(options.since)); invoke('deprecate', message, test, options); }; } const defaultDeprecate = deprecate$3; const emberDebugLibDeprecate = /*#__PURE__*/Object.defineProperty({ __proto__: null, default: defaultDeprecate, get missingOptionDeprecation () { return missingOptionDeprecation; }, get missingOptionsDeprecation () { return missingOptionsDeprecation$1; }, get missingOptionsIdDeprecation () { return missingOptionsIdDeprecation$1; }, get registerHandler () { return registerHandler$1; } }, Symbol.toStringTag, { value: 'Module' }); let testing = false; function isTesting() { return testing; } function setTesting(value) { testing = Boolean(value); } const emberDebugLibTesting = /*#__PURE__*/Object.defineProperty({ __proto__: null, isTesting, setTesting }, Symbol.toStringTag, { value: 'Module' }); let registerHandler = () => {}; let warn$1 = () => {}; let missingOptionsDeprecation; let missingOptionsIdDeprecation; /** @module @ember/debug */ { /** Allows for runtime registration of handler functions that override the default warning behavior. Warnings are invoked by calls made to [@ember/debug/warn](/ember/release/classes/@ember%2Fdebug/methods/warn?anchor=warn). The following example demonstrates its usage by registering a handler that does nothing overriding Ember's default warning behavior. ```javascript import { registerWarnHandler } from '@ember/debug'; // next is not called, so no warnings get the default behavior registerWarnHandler(() => {}); ``` The handler function takes the following arguments: <ul> <li> <code>message</code> - The message received from the warn call. </li> <li> <code>options</code> - An object passed in with the warn call containing additional information including:</li> <ul> <li> <code>id</code> - An id of the warning in the form of <code>package-name.specific-warning</code>.</li> </ul> <li> <code>next</code> - A function that calls into the previously registered handler.</li> </ul> @public @static @method registerWarnHandler @for @ember/debug @param handler {Function} A function to handle warnings. @since 2.1.0 */ registerHandler = function registerHandler(handler) { registerHandler$2('warn', handler); }; registerHandler(function logWarning(message) { /* eslint-disable no-console */ console.warn(`WARNING: ${message}`); /* eslint-enable no-console */ }); missingOptionsDeprecation = 'When calling `warn` you ' + 'must provide an `options` hash as the third parameter. ' + '`options` should include an `id` property.'; missingOptionsIdDeprecation = 'When calling `warn` you must provide `id` in options.'; /** Display a warning with the provided message. * In a production build, this method is defined as an empty function (NOP). Uses of this method in Ember itself are stripped from the ember.prod.js build. ```javascript import { warn } from '@ember/debug'; import tomsterCount from './tomster-counter'; // a module in my project // Log a warning if we have more than 3 tomsters warn('Too many tomsters!', tomsterCount <= 3, { id: 'ember-debug.too-many-tomsters' }); ``` @method warn @for @ember/debug @static @param {String} message A warning to display. @param {Boolean|Object} test An optional boolean. If falsy, the warning will be displayed. If `test` is an object, the `test` parameter can be used as the `options` parameter and the warning is displayed. @param {Object} options @param {String} options.id The `id` can be used by Ember debugging tools