ember-source
Version:
A JavaScript framework for creating ambitious web applications
642 lines (615 loc) • 22.9 kB
JavaScript
import { i as isFirefox, a as isChrome } from './index-BGP1rw3B.js';
import { E as ENV } from './env-BJLX2Arx.js';
import { isTesting } from '../@ember/debug/lib/testing.js';
import { registerHandler as registerHandler$2, invoke } from '../@ember/debug/lib/handlers.js';
import { isDevelopingApp } from '@embroider/macros';
import '../@ember/debug/lib/capture-render-tree.js';
/**
@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$1 = () => {};
if (isDevelopingApp()) {
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$1 = function deprecate(message, test, options) {
assert(missingOptionsDeprecation$1, Boolean(options && (options.id || options.until)));
assert(missingOptionsIdDeprecation$1, Boolean(options.id));
assert(missingOptionDeprecation(options.id, 'until'), Boolean(options.until));
assert(missingOptionDeprecation(options.id, 'for'), Boolean(options.for));
assert(missingOptionDeprecation(options.id, 'since'), Boolean(options.since));
invoke('deprecate', message, test, options);
};
}
const _deprecate = deprecate$1;
let registerHandler = () => {};
let warn$1 = () => {};
let missingOptionsDeprecation;
let missingOptionsIdDeprecation;
/**
@module @ember/debug
*/
if (isDevelopingApp()) {
/**
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
to change the behavior (raise, log, or silence) for that specific warning.
The `id` should be namespaced by dots, e.g. "ember-debug.feature-flag-with-features-stripped"
@public
@since 1.0.0
*/
warn$1 = function warn(message, test, options) {
if (arguments.length === 2 && typeof test === 'object') {
options = test;
test = false;
}
assert(missingOptionsDeprecation, Boolean(options));
assert(missingOptionsIdDeprecation, Boolean(options && options.id));
// SAFETY: we have explicitly assigned `false` if the user invoked the
// arity-2 version of the overload, so we know `test` is always either
// `undefined` or a `boolean` for type-safe callers.
invoke('warn', message, test, options);
};
}
const _warn = warn$1;
const {
toString: objectToString
} = Object.prototype;
const {
toString: functionToString
} = Function.prototype;
const {
isArray
} = Array;
const {
keys: objectKeys
} = Object;
const {
stringify
} = JSON;
const LIST_LIMIT = 100;
const DEPTH_LIMIT = 4;
const SAFE_KEY = /^[\w$]+$/;
/**
@module @ember/debug
*/
/**
Convenience method to inspect an object. This method will attempt to
convert the object into a useful string description.
It is a pretty simple implementation. If you want something more robust,
use something like JSDump: https://github.com/NV/jsDump
@method inspect
@static
@param {Object} obj The object you want to inspect.
@return {String} A description of the object
@since 1.4.0
@private
*/
function inspect(obj) {
// detect Node util.inspect call inspect(depth: number, opts: object)
if (typeof obj === 'number' && arguments.length === 2) {
return this;
}
return inspectValue(obj, 0);
}
function inspectValue(value, depth, seen) {
let valueIsArray = false;
switch (typeof value) {
case 'undefined':
return 'undefined';
case 'object':
if (value === null) return 'null';
if (isArray(value)) {
valueIsArray = true;
break;
}
// is toString Object.prototype.toString or undefined then traverse
if (value.toString === objectToString || value.toString === undefined) {
break;
}
// custom toString
return value.toString();
case 'function':
return value.toString === functionToString ? value.name ? `[Function:${value.name}]` : `[Function]` : value.toString();
case 'string':
return stringify(value);
case 'symbol':
case 'boolean':
case 'number':
default:
return value.toString();
}
if (seen === undefined) {
seen = new WeakSet();
} else {
if (seen.has(value)) return `[Circular]`;
}
seen.add(value);
return valueIsArray ? inspectArray(value, depth + 1, seen) : inspectObject(value, depth + 1, seen);
}
function inspectKey(key) {
return SAFE_KEY.test(key) ? key : stringify(key);
}
function inspectObject(obj, depth, seen) {
if (depth > DEPTH_LIMIT) {
return '[Object]';
}
let s = '{';
let keys = objectKeys(obj);
for (let i = 0; i < keys.length; i++) {
s += i === 0 ? ' ' : ', ';
if (i >= LIST_LIMIT) {
s += `... ${keys.length - LIST_LIMIT} more keys`;
break;
}
let key = keys[i];
(isDevelopingApp() && !(key) && assert('has key', key)); // Looping over array
s += `${inspectKey(String(key))}: ${inspectValue(obj[key], depth, seen)}`;
}
s += ' }';
return s;
}
function inspectArray(arr, depth, seen) {
if (depth > DEPTH_LIMIT) {
return '[Array]';
}
let s = '[';
for (let i = 0; i < arr.length; i++) {
s += i === 0 ? ' ' : ', ';
if (i >= LIST_LIMIT) {
s += `... ${arr.length - LIST_LIMIT} more items`;
break;
}
s += inspectValue(arr[i], depth, seen);
}
s += ' ]';
return s;
}
// These are the default production build versions:
const noop = () => {};
// SAFETY: these casts are just straight-up lies, but the point is that they do
// not do anything in production builds.
let assert = noop;
let info = noop;
let warn = noop;
let debug = noop;
let deprecate = noop;
let debugSeal = noop;
let debugFreeze = noop;
let runInDebug = noop;
let setDebugFunction = noop;
let getDebugFunction = noop;
let deprecateFunc = function () {
return arguments[arguments.length - 1];
};
if (isDevelopingApp()) {
setDebugFunction = function (type, callback) {
switch (type) {
case 'assert':
return assert = callback;
case 'info':
return info = callback;
case 'warn':
return warn = callback;
case 'debug':
return debug = callback;
case 'deprecate':
return deprecate = callback;
case 'debugSeal':
return debugSeal = callback;
case 'debugFreeze':
return debugFreeze = callback;
case 'runInDebug':
return runInDebug = callback;
case 'deprecateFunc':
return deprecateFunc = callback;
}
};
getDebugFunction = function (type) {
switch (type) {
case 'assert':
return assert;
case 'info':
return info;
case 'warn':
return warn;
case 'debug':
return debug;
case 'deprecate':
return deprecate;
case 'debugSeal':
return debugSeal;
case 'debugFreeze':
return debugFreeze;
case 'runInDebug':
return runInDebug;
case 'deprecateFunc':
return deprecateFunc;
}
};
}
/**
@module @ember/debug
*/
if (isDevelopingApp()) {
/**
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}`);
}
}
setDebugFunction('assert', assert);
/**
Display a debug notice.
Calls to this function are not invoked in production builds.
```javascript
import { debug } from '@ember/debug';
debug('I\'m a debug notice!');
```
@method debug
@for @ember/debug
@static
@param {String} message A debug message to display.
@public
*/
setDebugFunction('debug', function debug(message) {
console.debug(`DEBUG: ${message}`); /* eslint-disable-line no-console */
});
/**
Display an info notice.
Calls to this function are removed from production builds, so they can be
freely added for documentation and debugging purposes without worries of
incuring any performance penalty.
@method info
@private
*/
setDebugFunction('info', function info() {
console.info(...arguments); /* eslint-disable-line no-console */
});
/**
@module @ember/debug
@public
*/
/**
Alias an old, deprecated method with its new counterpart.
Display a deprecation warning with the provided message and a stack trace
(Chrome and Firefox only) when the assigned method is called.
Calls to this function are removed from production builds, so they can be
freely added for documentation and debugging purposes without worries of
incuring any performance penalty.
```javascript
import { deprecateFunc } from '@ember/debug';
Ember.oldMethod = deprecateFunc('Please use the new, updated method', options, Ember.newMethod);
```
@method deprecateFunc
@static
@for @ember/debug
@param {String} message A description of the deprecation.
@param {Object} [options] The options object for `deprecate`.
@param {Function} func The new function called to replace its deprecated counterpart.
@return {Function} A new function that wraps the original function with a deprecation warning
@private
*/
setDebugFunction('deprecateFunc', function deprecateFunc(...args) {
if (args.length === 3) {
let [message, options, func] = args;
return function (...args) {
deprecate(message, false, options);
return func.apply(this, args);
};
} else {
let [message, func] = args;
return function () {
deprecate(message);
return func.apply(this, arguments);
};
}
});
/**
@module @ember/debug
@public
*/
/**
Run a function meant for debugging.
Calls to this function are removed from production builds, so they can be
freely added for documentation and debugging purposes without worries of
incuring any performance penalty.
```javascript
import Component from '@ember/component';
import { runInDebug } from '@ember/debug';
runInDebug(() => {
Component.reopen({
didInsertElement() {
console.log("I'm happy");
}
});
});
```
@method runInDebug
@for @ember/debug
@static
@param {Function} func The function to be executed.
@since 1.5.0
@public
*/
setDebugFunction('runInDebug', function runInDebug(func) {
func();
});
setDebugFunction('debugSeal', function debugSeal(obj) {
Object.seal(obj);
});
setDebugFunction('debugFreeze', function debugFreeze(obj) {
// re-freezing an already frozen object introduces a significant
// performance penalty on Chrome (tested through 59).
//
// See: https://bugs.chromium.org/p/v8/issues/detail?id=6450
if (!Object.isFrozen(obj)) {
Object.freeze(obj);
}
});
setDebugFunction('deprecate', _deprecate);
setDebugFunction('warn', _warn);
}
let _warnIfUsingStrippedFeatureFlags;
if (isDevelopingApp() && !isTesting()) {
if (typeof window !== 'undefined' && (isFirefox || isChrome) && window.addEventListener) {
window.addEventListener('load', () => {
if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset['emberExtension']) {
let downloadURL;
if (isChrome) {
downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi';
} else if (isFirefox) {
downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/';
}
debug(`For more advanced debugging, install the Ember Inspector from ${downloadURL}`);
}
}, false);
}
}
export { _deprecate as _, assert as a, inspect as b, debug as c, deprecate as d, deprecateFunc as e, registerHandler$1 as f, registerHandler as g, debugFreeze as h, info as i, missingOptionsIdDeprecation$1 as j, missingOptionDeprecation as k, _warn as l, missingOptionsDeprecation$1 as m, missingOptionsIdDeprecation as n, missingOptionsDeprecation as o, debugSeal as p, getDebugFunction as q, runInDebug as r, setDebugFunction as s, _warnIfUsingStrippedFeatureFlags as t, warn as w };