refactor: migrate zone.js to prettier formatting (#55427)

Migrate formatting to prettier for zone.js from clang-format

PR Close #55427
This commit is contained in:
Joey Perrott
2024-04-19 16:53:49 +00:00
committed by Andrew Kushnir
parent 31fdf0fbea
commit f307e95459
199 changed files with 15270 additions and 12517 deletions
+2
View File
@@ -33,6 +33,7 @@ export const format: FormatConfig = {
'packages/router/**/*.{js,ts}',
'packages/service-worker/**/*.{js,ts}',
'packages/upgrade/**/*.{js,ts}',
'packages/zone.js/**/*.{js,ts}',
// Do not format d.ts files as they are generated
'!**/*.d.ts',
@@ -97,6 +98,7 @@ export const format: FormatConfig = {
'!packages/router/**/*.{js,ts}',
'!packages/service-worker/**/*.{js,ts}',
'!packages/upgrade/**/*.{js,ts}',
'!packages/zone.js/**/*.{js,ts}',
],
},
'buildifier': true,
+5 -4
View File
@@ -7,15 +7,16 @@
*/
const fs = require('fs');
module.exports = function(config) {
module.exports = function (config) {
let chkResult = true;
config.targets.forEach(target => {
config.targets.forEach((target) => {
if (target.checkTarget) {
try {
const stats = fs.statSync(target.path);
if (stats.size > target.limit) {
console.error(`file ${target.path} size over limit, limit is ${target.limit}, actual is ${
stats.size}`);
console.error(
`file ${target.path} size over limit, limit is ${target.limit}, actual is ${stats.size}`,
);
chkResult = false;
}
} catch (err) {
@@ -14,8 +14,8 @@ const callbacks = [];
const size = 100000;
for (let i = 0; i < size; i++) {
const emitter = new EventEmitter();
const callback = (function(i) {
return function() {
const callback = (function (i) {
return function () {
console.log(i);
};
})(i);
@@ -29,19 +29,15 @@ function addRemoveCallback(reuse, useZone) {
for (let i = 0; i < size; i++) {
const emitter = emitters[i];
if (!reuse) callback = callbacks[i];
if (useZone)
emitter.on('msg', callback);
else
emitter.__zone_symbol__addListener('msg', callback);
if (useZone) emitter.on('msg', callback);
else emitter.__zone_symbol__addListener('msg', callback);
}
for (let i = 0; i < size; i++) {
const emitter = emitters[i];
if (!reuse) callback = callbacks[i];
if (useZone)
emitter.removeListener('msg', callback);
else
emitter.__zone_symbol__removeListener('msg', callback);
if (useZone) emitter.removeListener('msg', callback);
else emitter.__zone_symbol__removeListener('msg', callback);
}
const end = new Date();
console.log(useZone ? 'use zone' : 'native', reuse ? 'reuse' : 'new');
+5 -5
View File
@@ -5,7 +5,7 @@
Zone['countingZoneSpec'] = {
name: 'counterZone',
// setTimeout
onScheduleTask: function(delegate, current, target, task) {
onScheduleTask: function (delegate, current, target, task) {
this.data.count += 1;
delegate.scheduleTask(target, task);
},
@@ -13,23 +13,23 @@ Zone['countingZoneSpec'] = {
// fires when...
// - clearTimeout
// - setTimeout finishes
onInvokeTask: function(delegate, current, target, task, applyThis, applyArgs) {
onInvokeTask: function (delegate, current, target, task, applyThis, applyArgs) {
delegate.invokeTask(target, task, applyThis, applyArgs);
this.data.count -= 1;
},
onHasTask: function(delegate, current, target, hasTask) {
onHasTask: function (delegate, current, target, hasTask) {
if (this.data.count === 0 && !this.data.flushed) {
this.data.flushed = true;
target.run(this.onFlush);
}
},
counter: function() {
counter: function () {
return this.data.count;
},
data: {count: 0, flushed: false},
onFlush: function() {}
onFlush: function () {},
};
+8 -6
View File
@@ -6,12 +6,13 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
config.set({
basePath: '',
client: {errorpolicy: config.errorpolicy},
files: [
'node_modules/systemjs/dist/system-polyfills.js', 'node_modules/systemjs/dist/system.src.js',
'node_modules/systemjs/dist/system-polyfills.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/whatwg-fetch/fetch.js',
{pattern: 'node_modules/rxjs/**/**/*.js', included: false, watched: false},
{pattern: 'node_modules/rxjs/**/**/*.js.map', included: false, watched: false},
@@ -21,12 +22,13 @@ module.exports = function(config) {
{pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false},
{pattern: 'test/assets/**/*.*', watched: true, served: true, included: false},
{pattern: 'build/**/*.js.map', watched: true, served: true, included: false},
{pattern: 'build/**/*.js', watched: true, served: true, included: false}
{pattern: 'build/**/*.js', watched: true, served: true, included: false},
],
plugins: [
require('karma-chrome-launcher'), require('karma-firefox-launcher'),
require('karma-sourcemap-loader')
require('karma-chrome-launcher'),
require('karma-firefox-launcher'),
require('karma-sourcemap-loader'),
],
preprocessors: {'**/*.js': ['sourcemap']},
@@ -46,6 +48,6 @@ module.exports = function(config) {
retryLimit: 4,
autoWatch: true,
singleRun: false
singleRun: false,
});
};
+1 -2
View File
@@ -1,5 +1,4 @@
module.exports = function(config) {
module.exports = function (config) {
require('./karma-build.conf.js')(config);
config.plugins.push(require('karma-jasmine'));
@@ -1,5 +1,4 @@
module.exports = function(config) {
module.exports = function (config) {
require('./karma-build-jasmine.conf.js')(config);
config.client.entrypoint = 'browser_es2015_entry_point';
};
+3 -4
View File
@@ -1,11 +1,10 @@
module.exports = function(config) {
module.exports = function (config) {
require('./karma-build.conf.js')(config);
config.plugins.push(require('karma-mocha'));
config.frameworks.push('mocha');
config.client.mocha = {
timeout: 5000 // copied timeout for Jasmine in WebSocket.spec (otherwise Mochas default timeout
// at 2 sec is to low for the tests)
timeout: 5000, // copied timeout for Jasmine in WebSocket.spec (otherwise Mochas default timeout
// at 2 sec is to low for the tests)
};
};
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
require('./karma-dist-mocha.conf.js')(config);
require('./sauce.conf')(config);
};
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
require('./karma-dist-mocha.conf.js')(config);
require('./sauce-selenium3.conf')(config);
};
+1 -1
View File
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
require('./karma-base.conf.js')(config);
config.files.push('build/test/browser-env-setup.js');
config.files.push('build/test/wtf_mock.js');
+1 -2
View File
@@ -1,5 +1,4 @@
module.exports = function(config) {
module.exports = function (config) {
require('./karma-dist.conf.js')(config);
config.plugins.push(require('karma-jasmine'));
+3 -4
View File
@@ -1,5 +1,4 @@
module.exports = function(config) {
module.exports = function (config) {
require('./karma-dist.conf.js')(config);
for (let i = 0; i < config.files.length; i++) {
@@ -17,7 +16,7 @@ module.exports = function(config) {
config.plugins.push(require('karma-mocha'));
config.frameworks.push('mocha');
config.client.mocha = {
timeout: 5000 // copied timeout for Jasmine in WebSocket.spec (otherwise Mochas default timeout
// at 2 sec is to low for the tests)
timeout: 5000, // copied timeout for Jasmine in WebSocket.spec (otherwise Mochas default timeout
// at 2 sec is to low for the tests)
};
};
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
require('./karma-dist-jasmine.conf.js')(config);
require('./sauce.conf')(config, ['SL_IOS9']);
};
@@ -1,5 +1,4 @@
module.exports = function(config) {
module.exports = function (config) {
require('./karma-dist-jasmine.conf.js')(config);
require('./sauce.es2015.conf')(config);
config.files.push('build/test/wtf_mock.js');
@@ -6,10 +6,20 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
require('./karma-dist-jasmine.conf.js')(config);
require('./sauce.conf')(config, [
'SL_IOS9', 'SL_CHROME', 'SL_FIREFOX_54', 'SL_SAFARI8', 'SL_SAFARI9', 'SL_SAFARI10', 'SL_IOS8',
'SL_IOS9', 'SL_IOS10', 'SL_MSEDGE15', 'SL_ANDROID4.4', 'SL_ANDROID5.1'
])
'SL_IOS9',
'SL_CHROME',
'SL_FIREFOX_54',
'SL_SAFARI8',
'SL_SAFARI9',
'SL_SAFARI10',
'SL_IOS8',
'SL_IOS9',
'SL_IOS10',
'SL_MSEDGE15',
'SL_ANDROID4.4',
'SL_ANDROID5.1',
]);
};
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
require('./karma-dist-jasmine.conf.js')(config);
require('./sauce-selenium3.conf')(config);
};
+1 -1
View File
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
require('./karma-base.conf.js')(config);
config.files.push('build/test/browser-env-setup.js');
config.files.push('build/test/wtf_mock.js');
@@ -1,5 +1,4 @@
module.exports = function(config) {
module.exports = function (config) {
require('./karma-evergreen-dist.conf.js')(config);
config.plugins.push(require('karma-jasmine'));
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
require('./karma-evergreen-dist-jasmine.conf.js')(config);
require('./sauce-evergreen.conf')(config);
};
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
module.exports = function(config) {
module.exports = function (config) {
require('./karma-base.conf.js')(config);
config.files.push('build/test/browser-env-setup.js');
config.files.push('build/test/wtf_mock.js');
+30 -4
View File
@@ -6,8 +6,34 @@
* found in the LICENSE file at https://angular.io/license
*/
import {globalSources, patchEventPrototype, patchEventTarget, zoneSymbolEventNames} from '../common/events';
import {ADD_EVENT_LISTENER_STR, ArraySlice, attachOriginToPatched, bindArguments, FALSE_STR, isBrowser, isIEOrEdge, isMix, isNode, ObjectCreate, ObjectDefineProperty, ObjectGetOwnPropertyDescriptor, patchClass, patchMacroTask, patchMethod, patchOnProperties, REMOVE_EVENT_LISTENER_STR, TRUE_STR, wrapWithCurrentZone, ZONE_SYMBOL_PREFIX} from '../common/utils';
import {
globalSources,
patchEventPrototype,
patchEventTarget,
zoneSymbolEventNames,
} from '../common/events';
import {
ADD_EVENT_LISTENER_STR,
ArraySlice,
attachOriginToPatched,
bindArguments,
FALSE_STR,
isBrowser,
isIEOrEdge,
isMix,
isNode,
ObjectCreate,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptor,
patchClass,
patchMacroTask,
patchMethod,
patchOnProperties,
REMOVE_EVENT_LISTENER_STR,
TRUE_STR,
wrapWithCurrentZone,
ZONE_SYMBOL_PREFIX,
} from '../common/utils';
import {ZoneType} from '../zone-impl';
import {patchCallbacks} from './browser-util';
@@ -34,7 +60,7 @@ export function patchUtil(Zone: ZoneType): void {
}
if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
(Zone as any)[SYMBOL_BLACK_LISTED_EVENTS] = (Zone as any)[SYMBOL_UNPATCHED_EVENTS] =
global[SYMBOL_BLACK_LISTED_EVENTS];
global[SYMBOL_BLACK_LISTED_EVENTS];
}
api.patchEventPrototype = patchEventPrototype;
api.patchEventTarget = patchEventTarget;
@@ -60,7 +86,7 @@ export function patchUtil(Zone: ZoneType): void {
FALSE_STR,
ZONE_SYMBOL_PREFIX,
ADD_EVENT_LISTENER_STR,
REMOVE_EVENT_LISTENER_STR
REMOVE_EVENT_LISTENER_STR,
});
});
}
@@ -16,15 +16,19 @@ import {propertyDescriptorLegacyPatch} from './property-descriptor-legacy';
import {registerElementPatch} from './register-element';
export function patchBrowserLegacy(): void {
const _global: any = typeof window !== 'undefined' ? window :
typeof global !== 'undefined' ? global :
typeof self !== 'undefined' ? self :
{};
const _global: any =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: typeof self !== 'undefined'
? self
: {};
const symbolPrefix = _global['__Zone_symbol_prefix'] || '__zone_symbol__';
function __symbol__(name: string) {
return symbolPrefix + name;
}
_global[__symbol__('legacyPatch')] = function() {
_global[__symbol__('legacyPatch')] = function () {
const Zone = _global['Zone'];
Zone.__load_patch('defineProperty', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
api._redefineProperty = _redefineProperty;
+9 -4
View File
@@ -6,15 +6,20 @@
* found in the LICENSE file at https://angular.io/license
*/
export function patchCallbacks(
api: _ZonePrivate, target: any, targetName: string, method: string, callbacks: string[]) {
api: _ZonePrivate,
target: any,
targetName: string,
method: string,
callbacks: string[],
) {
const symbol = Zone.__symbol__(method);
if (target[symbol]) {
return;
}
const nativeDelegate = target[symbol] = target[method];
target[method] = function(name: any, opts: any, options?: any) {
const nativeDelegate = (target[symbol] = target[method]);
target[method] = function (name: any, opts: any, options?: any) {
if (opts && opts.prototype) {
callbacks.forEach(function(callback) {
callbacks.forEach(function (callback) {
const source = `${targetName}.${method}::` + callback;
const prototype = opts.prototype;
// Note: the `patchCallbacks` is used for patching the `document.registerElement` and
+61 -25
View File
@@ -13,7 +13,15 @@
import {findEventTasks} from '../common/events';
import {patchQueueMicrotask} from '../common/queue-microtask';
import {patchTimer} from '../common/timers';
import {patchClass, patchMethod, patchPrototype, scheduleMacroTaskWithCurrentZone, ZONE_SYMBOL_ADD_EVENT_LISTENER, ZONE_SYMBOL_REMOVE_EVENT_LISTENER, zoneSymbol,} from '../common/utils';
import {
patchClass,
patchMethod,
patchPrototype,
scheduleMacroTaskWithCurrentZone,
ZONE_SYMBOL_ADD_EVENT_LISTENER,
ZONE_SYMBOL_REMOVE_EVENT_LISTENER,
zoneSymbol,
} from '../common/utils';
import {ZoneType} from '../zone-impl';
import {patchCustomElements} from './custom-elements';
@@ -47,7 +55,7 @@ export function patchBrowser(Zone: ZoneType): void {
for (let i = 0; i < blockingMethods.length; i++) {
const name = blockingMethods[i];
patchMethod(global, name, (delegate, symbol, name) => {
return function(s: any, args: any[]) {
return function (s: any, args: any[]) {
return Zone.current.run(delegate, global, args, name);
};
});
@@ -144,7 +152,7 @@ export function patchBrowser(Zone: ZoneType): void {
if (listener) {
oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
}
const newListener = target[XHR_LISTENER] = () => {
const newListener = (target[XHR_LISTENER] = () => {
if (target.readyState === target.DONE) {
// sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
// readyState=4 multiple times, so we need to check task state here
@@ -159,7 +167,7 @@ export function patchBrowser(Zone: ZoneType): void {
const loadTasks = target[Zone.__symbol__('loadfalse')];
if (target.status !== 0 && loadTasks && loadTasks.length > 0) {
const oriInvoke = task.invoke;
task.invoke = function() {
task.invoke = function () {
// need to load the tasks again, because in other
// load listener, they may remove themselves
const loadTasks = target[Zone.__symbol__('loadfalse')];
@@ -181,7 +189,7 @@ export function patchBrowser(Zone: ZoneType): void {
target[XHR_ERROR_BEFORE_SCHEDULED] = true;
}
}
};
});
oriAddListener.call(target, READY_STATE_CHANGE, newListener);
const storedTask: Task = target[XHR_TASK];
@@ -203,18 +211,25 @@ export function patchBrowser(Zone: ZoneType): void {
return abortNative!.apply(data.target, data.args);
}
const openNative =
patchMethod(XMLHttpRequestPrototype, 'open', () => function(self: any, args: any[]) {
const openNative = patchMethod(
XMLHttpRequestPrototype,
'open',
() =>
function (self: any, args: any[]) {
self[XHR_SYNC] = args[2] == false;
self[XHR_URL] = args[1];
return openNative!.apply(self, args);
});
},
);
const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
const fetchTaskAborting = zoneSymbol('fetchTaskAborting');
const fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
const sendNative: Function|null =
patchMethod(XMLHttpRequestPrototype, 'send', () => function(self: any, args: any[]) {
const sendNative: Function | null = patchMethod(
XMLHttpRequestPrototype,
'send',
() =>
function (self: any, args: any[]) {
if ((Zone.current as any)[fetchTaskScheduling] === true) {
// a fetch is scheduling, so we are using xhr to polyfill fetch
// and because we already schedule macroTask for fetch, we should
@@ -225,22 +240,40 @@ export function patchBrowser(Zone: ZoneType): void {
// if the XHR is sync there is no task to schedule, just execute the code.
return sendNative!.apply(self, args);
} else {
const options: XHROptions =
{target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false};
const options: XHROptions = {
target: self,
url: self[XHR_URL],
isPeriodic: false,
args: args,
aborted: false,
};
const task = scheduleMacroTaskWithCurrentZone(
XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
task.state === SCHEDULED) {
XMLHTTPREQUEST_SOURCE,
placeholderCallback,
options,
scheduleTask,
clearTask,
);
if (
self &&
self[XHR_ERROR_BEFORE_SCHEDULED] === true &&
!options.aborted &&
task.state === SCHEDULED
) {
// xhr request throw error when send
// we should invoke task instead of leaving a scheduled
// pending macroTask
task.invoke();
}
}
});
},
);
const abortNative =
patchMethod(XMLHttpRequestPrototype, 'abort', () => function(self: any, args: any[]) {
const abortNative = patchMethod(
XMLHttpRequestPrototype,
'abort',
() =>
function (self: any, args: any[]) {
const task: Task = findPendingTask(self);
if (task && typeof task.type == 'string') {
// If the XHR has already completed, do nothing.
@@ -258,7 +291,8 @@ export function patchBrowser(Zone: ZoneType): void {
// Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
// task
// to cancel. Do nothing.
});
},
);
}
});
@@ -272,15 +306,17 @@ export function patchBrowser(Zone: ZoneType): void {
Zone.__load_patch('PromiseRejectionEvent', (global: any, Zone: ZoneType) => {
// handle unhandled promise rejection
function findPromiseRejectionHandler(evtName: string) {
return function(e: any) {
return function (e: any) {
const eventTasks = findEventTasks(global, evtName);
eventTasks.forEach(eventTask => {
eventTasks.forEach((eventTask) => {
// windows has added unhandledrejection event listener
// trigger the event listener
const PromiseRejectionEvent = global['PromiseRejectionEvent'];
if (PromiseRejectionEvent) {
const evt =
new PromiseRejectionEvent(evtName, {promise: e.promise, reason: e.rejection});
const evt = new PromiseRejectionEvent(evtName, {
promise: e.promise,
reason: e.rejection,
});
eventTask.invoke(evt);
}
});
@@ -289,10 +325,10 @@ export function patchBrowser(Zone: ZoneType): void {
if (global['PromiseRejectionEvent']) {
(Zone as any)[zoneSymbol('unhandledPromiseRejectionHandler')] =
findPromiseRejectionHandler('unhandledrejection');
findPromiseRejectionHandler('unhandledrejection');
(Zone as any)[zoneSymbol('rejectionHandledHandler')] =
findPromiseRejectionHandler('rejectionhandled');
findPromiseRejectionHandler('rejectionhandled');
}
});
+5 -2
View File
@@ -11,8 +11,11 @@ import {ZoneType} from '../zone-impl';
export function patchCanvas(Zone: ZoneType): void {
Zone.__load_patch('canvas', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
const HTMLCanvasElement = global['HTMLCanvasElement'];
if (typeof HTMLCanvasElement !== 'undefined' && HTMLCanvasElement.prototype &&
HTMLCanvasElement.prototype.toBlob) {
if (
typeof HTMLCanvasElement !== 'undefined' &&
HTMLCanvasElement.prototype &&
HTMLCanvasElement.prototype.toBlob
) {
api.patchMacroTask(HTMLCanvasElement.prototype, 'toBlob', (self: any, args: any[]) => {
return {name: 'HTMLCanvasElement.toBlob', target: self, cbIdx: 0, args: args};
});
@@ -14,9 +14,14 @@ export function patchCustomElements(_global: any, api: _ZonePrivate) {
// https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-lifecycle-callbacks
const callbacks = [
'connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback',
'formAssociatedCallback', 'formDisabledCallback', 'formResetCallback',
'formStateRestoreCallback'
'connectedCallback',
'disconnectedCallback',
'adoptedCallback',
'attributeChangedCallback',
'formAssociatedCallback',
'formDisabledCallback',
'formResetCallback',
'formStateRestoreCallback',
];
api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
+25 -16
View File
@@ -21,12 +21,12 @@ export function propertyPatch() {
zoneSymbol = Zone.__symbol__;
_defineProperty = (Object as any)[zoneSymbol('defineProperty')] = Object.defineProperty;
_getOwnPropertyDescriptor = (Object as any)[zoneSymbol('getOwnPropertyDescriptor')] =
Object.getOwnPropertyDescriptor;
Object.getOwnPropertyDescriptor;
_create = Object.create;
unconfigurablesKey = zoneSymbol('unconfigurables');
Object.defineProperty = function(obj: any, prop: string, desc: any) {
Object.defineProperty = function (obj: any, prop: string, desc: any) {
if (isUnconfigurable(obj, prop)) {
throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj);
throw new TypeError("Cannot assign to read only property '" + prop + "' of " + obj);
}
const originalConfigurableFlag = desc.configurable;
if (prop !== 'prototype') {
@@ -35,10 +35,14 @@ export function propertyPatch() {
return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
};
Object.defineProperties = function<T>(obj: T, props: PropertyDescriptorMap&ThisType<any>&{
[s: symbol]: PropertyDescriptor;
}): T {
Object.keys(props).forEach(function(prop) {
Object.defineProperties = function <T>(
obj: T,
props: PropertyDescriptorMap &
ThisType<any> & {
[s: symbol]: PropertyDescriptor;
},
): T {
Object.keys(props).forEach(function (prop) {
Object.defineProperty(obj, prop, props[prop]);
});
for (const sym of Object.getOwnPropertySymbols(props)) {
@@ -55,18 +59,18 @@ export function propertyPatch() {
}
}
return obj;
}
};
Object.create = <any>function(proto: any, propertiesObject: any) {
Object.create = <any>function (proto: any, propertiesObject: any) {
if (typeof propertiesObject === 'object' && !Object.isFrozen(propertiesObject)) {
Object.keys(propertiesObject).forEach(function(prop) {
Object.keys(propertiesObject).forEach(function (prop) {
propertiesObject[prop] = rewriteDescriptor(proto, prop, propertiesObject[prop]);
});
}
return _create(proto, propertiesObject);
};
Object.getOwnPropertyDescriptor = function(obj, prop) {
Object.getOwnPropertyDescriptor = function (obj, prop) {
const desc = _getOwnPropertyDescriptor(obj, prop);
if (desc && isUnconfigurable(obj, prop)) {
desc.configurable = false;
@@ -118,8 +122,12 @@ function _tryDefineProperty(obj: any, prop: string, desc: any, originalConfigura
return _defineProperty(obj, prop, desc);
} catch (error) {
let swallowError = false;
if (prop === 'createdCallback' || prop === 'attachedCallback' ||
prop === 'detachedCallback' || prop === 'attributeChangedCallback') {
if (
prop === 'createdCallback' ||
prop === 'attachedCallback' ||
prop === 'detachedCallback' ||
prop === 'attributeChangedCallback'
) {
// We only swallow the error in registerElement patch
// this is the work around since some applications
// fail if we throw the error
@@ -131,14 +139,15 @@ function _tryDefineProperty(obj: any, prop: string, desc: any, originalConfigura
// TODO: @JiaLiPassion, Some application such as `registerElement` patch
// still need to swallow the error, in the future after these applications
// are updated, the following logic can be removed.
let descJson: string|null = null;
let descJson: string | null = null;
try {
descJson = JSON.stringify(desc);
} catch (error) {
descJson = desc.toString();
}
console.log(`Attempting to configure '${prop}' with descriptor '${descJson}' on object '${
obj}' and got error, giving up: ${error}`);
console.log(
`Attempting to configure '${prop}' with descriptor '${descJson}' on object '${obj}' and got error, giving up: ${error}`,
);
}
} else {
throw error;
@@ -8,12 +8,13 @@
export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
const {eventNames, globalSources, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX} =
api.getGlobalObjects()!;
api.getGlobalObjects()!;
const WTF_ISSUE_555 =
'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
const NO_EVENT_TARGET =
'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'
.split(',');
'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'.split(
',',
);
const EVENT_TARGET = 'EventTarget';
let apis: any[] = [];
@@ -48,7 +49,7 @@ export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
'MSPointerMove': 'pointermove',
'MSPointerOut': 'pointerout',
'MSPointerOver': 'pointerover',
'MSPointerUp': 'pointerup'
'MSPointerUp': 'pointerup',
};
// predefine all __zone_symbol__ + eventName + true/false string
@@ -66,20 +67,24 @@ export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
// predefine all task.source string
for (let i = 0; i < WTF_ISSUE_555_ARRAY.length; i++) {
const target: any = WTF_ISSUE_555_ARRAY[i];
const targets: any = globalSources[target] = {};
const targets: any = (globalSources[target] = {});
for (let j = 0; j < eventNames.length; j++) {
const eventName = eventNames[j];
targets[eventName] = target + ADD_EVENT_LISTENER_SOURCE + eventName;
}
}
const checkIEAndCrossContext = function(
nativeDelegate: any, delegate: any, target: any, args: any) {
const checkIEAndCrossContext = function (
nativeDelegate: any,
delegate: any,
target: any,
args: any,
) {
if (!isDisableIECheck && ieOrEdge) {
if (isEnableCrossContextCheck) {
try {
const testString = delegate.toString();
if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
if (testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS) {
nativeDelegate.apply(target, args);
return false;
}
@@ -89,7 +94,7 @@ export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
}
} else {
const testString = delegate.toString();
if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
if (testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS) {
nativeDelegate.apply(target, args);
return false;
}
@@ -117,7 +122,7 @@ export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
transferEventName: (eventName: string) => {
const pointerEventName = pointerEventsMap[eventName];
return pointerEventName || eventName;
}
},
});
(Zone as any)[api.symbol('patchEventTarget')] = !!_global[EVENT_TARGET];
return true;
+1 -1
View File
@@ -12,7 +12,7 @@ export function eventTargetPatch(_global: any, api: _ZonePrivate) {
return;
}
const {eventNames, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX} =
api.getGlobalObjects()!;
api.getGlobalObjects()!;
// predefine all __zone_symbol__ + eventName + true/false string
for (let i = 0; i < eventNames.length; i++) {
const eventName = eventNames[i];
@@ -32,9 +32,11 @@ export function propertyDescriptorLegacyPatch(api: _ZonePrivate, _global: any) {
function canPatchViaPropertyDescriptor(api: _ZonePrivate, _global: any) {
const {isBrowser, isMix} = api.getGlobalObjects()!;
if ((isBrowser || isMix) &&
!api.ObjectGetOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') &&
typeof Element !== 'undefined') {
if (
(isBrowser || isMix) &&
!api.ObjectGetOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') &&
typeof Element !== 'undefined'
) {
// WebKit https://bugs.webkit.org/show_bug.cgi?id=134364
// IDL interface attributes are not configurable
const desc = api.ObjectGetOwnPropertyDescriptor(Element.prototype, 'onclick');
@@ -45,9 +47,9 @@ function canPatchViaPropertyDescriptor(api: _ZonePrivate, _global: any) {
api.ObjectDefineProperty(Element.prototype, 'onclick', {
enumerable: true,
configurable: true,
get: function() {
get: function () {
return true;
}
},
});
const div = document.createElement('div');
const result = !!div.onclick;
@@ -64,8 +66,10 @@ function canPatchViaPropertyDescriptor(api: _ZonePrivate, _global: any) {
const ON_READY_STATE_CHANGE = 'onreadystatechange';
const XMLHttpRequestPrototype = XMLHttpRequest.prototype;
const xhrDesc =
api.ObjectGetOwnPropertyDescriptor(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE);
const xhrDesc = api.ObjectGetOwnPropertyDescriptor(
XMLHttpRequestPrototype,
ON_READY_STATE_CHANGE,
);
// add enumerable and configurable here because in opera
// by default XMLHttpRequest.prototype.onreadystatechange is undefined
@@ -77,9 +81,9 @@ function canPatchViaPropertyDescriptor(api: _ZonePrivate, _global: any) {
api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, {
enumerable: true,
configurable: true,
get: function() {
get: function () {
return true;
}
},
});
const req = new XMLHttpRequest();
const result = !!req.onreadystatechange;
@@ -91,12 +95,12 @@ function canPatchViaPropertyDescriptor(api: _ZonePrivate, _global: any) {
api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, {
enumerable: true,
configurable: true,
get: function() {
get: function () {
return this[SYMBOL_FAKE_ONREADYSTATECHANGE];
},
set: function(value) {
set: function (value) {
this[SYMBOL_FAKE_ONREADYSTATECHANGE] = value;
}
},
});
const req = new XMLHttpRequest();
const detectFunc = () => {};
@@ -203,13 +207,24 @@ const globalEventHandlersEventNames = [
'transitioncancel',
'transitionend',
'waiting',
'wheel'
'wheel',
];
const documentEventNames = [
'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'freeze', 'fullscreenchange',
'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror',
'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange',
'visibilitychange', 'resume'
'afterscriptexecute',
'beforescriptexecute',
'DOMContentLoaded',
'freeze',
'fullscreenchange',
'mozfullscreenchange',
'webkitfullscreenchange',
'msfullscreenchange',
'fullscreenerror',
'mozfullscreenerror',
'webkitfullscreenerror',
'msfullscreenerror',
'readystatechange',
'visibilitychange',
'resume',
];
const windowEventNames = [
'absolutedeviceorientation',
@@ -241,15 +256,33 @@ const windowEventNames = [
'userproximity',
'vrdisplayconnected',
'vrdisplaydisconnected',
'vrdisplaypresentchange'
'vrdisplaypresentchange',
];
const htmlElementEventNames = [
'beforecopy', 'beforecut', 'beforepaste', 'copy', 'cut', 'paste', 'dragstart', 'loadend',
'animationstart', 'search', 'transitionrun', 'transitionstart', 'webkitanimationend',
'webkitanimationiteration', 'webkitanimationstart', 'webkittransitionend'
'beforecopy',
'beforecut',
'beforepaste',
'copy',
'cut',
'paste',
'dragstart',
'loadend',
'animationstart',
'search',
'transitionrun',
'transitionstart',
'webkitanimationend',
'webkitanimationiteration',
'webkitanimationstart',
'webkittransitionend',
];
const mediaElementEventNames = [
'encrypted',
'waitingforkey',
'msneedkey',
'mozinterruptbegin',
'mozinterruptend',
];
const mediaElementEventNames =
['encrypted', 'waitingforkey', 'msneedkey', 'mozinterruptbegin', 'mozinterruptend'];
const ieElementEventNames = [
'activate',
'afterupdate',
@@ -305,15 +338,21 @@ const ieElementEventNames = [
'mssitemodejumplistitemremoved',
'msthumbnailclick',
'stop',
'storagecommit'
'storagecommit',
];
const webglEventNames = ['webglcontextrestored', 'webglcontextlost', 'webglcontextcreationerror'];
const formEventNames = ['autocomplete', 'autocompleteerror'];
const detailEventNames = ['toggle'];
const eventNames = [
...globalEventHandlersEventNames, ...webglEventNames, ...formEventNames, ...detailEventNames,
...documentEventNames, ...windowEventNames, ...htmlElementEventNames, ...ieElementEventNames
...globalEventHandlersEventNames,
...webglEventNames,
...formEventNames,
...detailEventNames,
...documentEventNames,
...windowEventNames,
...htmlElementEventNames,
...ieElementEventNames,
];
// Whenever any eventListener fires, we check the eventListener target and all parents
@@ -324,21 +363,27 @@ function patchViaCapturingAllTheEvents(api: _ZonePrivate) {
for (let i = 0; i < eventNames.length; i++) {
const property = eventNames[i];
const onproperty = 'on' + property;
self.addEventListener(property, function(event) {
let elt: any = <Node>event.target, bound, source;
if (elt) {
source = elt.constructor['name'] + '.' + onproperty;
} else {
source = 'unknown.' + onproperty;
}
while (elt) {
if (elt[onproperty] && !elt[onproperty][unboundKey]) {
bound = api.wrapWithCurrentZone(elt[onproperty], source);
bound[unboundKey] = elt[onproperty];
elt[onproperty] = bound;
self.addEventListener(
property,
function (event) {
let elt: any = <Node>event.target,
bound,
source;
if (elt) {
source = elt.constructor['name'] + '.' + onproperty;
} else {
source = 'unknown.' + onproperty;
}
elt = elt.parentElement;
}
}, true);
while (elt) {
if (elt[onproperty] && !elt[onproperty][unboundKey]) {
bound = api.wrapWithCurrentZone(elt[onproperty], source);
bound[unboundKey] = elt[onproperty];
elt[onproperty] = bound;
}
elt = elt.parentElement;
}
},
true,
);
}
}
@@ -10,7 +10,14 @@
* @suppress {globalThis}
*/
import {isBrowser, isIE, isMix, isNode, ObjectGetPrototypeOf, patchOnProperties} from '../common/utils';
import {
isBrowser,
isIE,
isMix,
isNode,
ObjectGetPrototypeOf,
patchOnProperties,
} from '../common/utils';
export interface IgnoreProperty {
target: any;
@@ -18,22 +25,29 @@ export interface IgnoreProperty {
}
export function filterProperties(
target: any, onProperties: string[], ignoreProperties: IgnoreProperty[]): string[] {
target: any,
onProperties: string[],
ignoreProperties: IgnoreProperty[],
): string[] {
if (!ignoreProperties || ignoreProperties.length === 0) {
return onProperties;
}
const tip: IgnoreProperty[] = ignoreProperties.filter(ip => ip.target === target);
const tip: IgnoreProperty[] = ignoreProperties.filter((ip) => ip.target === target);
if (!tip || tip.length === 0) {
return onProperties;
}
const targetIgnoreProperties: string[] = tip[0].ignoreProperties;
return onProperties.filter(op => targetIgnoreProperties.indexOf(op) === -1);
return onProperties.filter((op) => targetIgnoreProperties.indexOf(op) === -1);
}
export function patchFilteredProperties(
target: any, onProperties: string[], ignoreProperties: IgnoreProperty[], prototype?: any) {
target: any,
onProperties: string[],
ignoreProperties: IgnoreProperty[],
prototype?: any,
) {
// check whether target is available, sometimes target will be undefined
// because different browser or some 3rd party plugin.
if (!target) {
@@ -49,8 +63,8 @@ export function patchFilteredProperties(
*/
export function getOnEventNames(target: Object) {
return Object.getOwnPropertyNames(target)
.filter(name => name.startsWith('on') && name.length > 2)
.map(name => name.substring(2));
.filter((name) => name.startsWith('on') && name.length > 2)
.map((name) => name.substring(2));
}
export function propertyDescriptorPatch(api: _ZonePrivate, _global: any) {
@@ -67,26 +81,49 @@ export function propertyDescriptorPatch(api: _ZonePrivate, _global: any) {
if (isBrowser) {
const internalWindow: any = window;
patchTargets = patchTargets.concat([
'Document', 'SVGElement', 'Element', 'HTMLElement', 'HTMLBodyElement', 'HTMLMediaElement',
'HTMLFrameSetElement', 'HTMLFrameElement', 'HTMLIFrameElement', 'HTMLMarqueeElement', 'Worker'
'Document',
'SVGElement',
'Element',
'HTMLElement',
'HTMLBodyElement',
'HTMLMediaElement',
'HTMLFrameSetElement',
'HTMLFrameElement',
'HTMLIFrameElement',
'HTMLMarqueeElement',
'Worker',
]);
const ignoreErrorProperties =
isIE() ? [{target: internalWindow, ignoreProperties: ['error']}] : [];
const ignoreErrorProperties = isIE()
? [{target: internalWindow, ignoreProperties: ['error']}]
: [];
// in IE/Edge, onProp not exist in window object, but in WindowPrototype
// so we need to pass WindowPrototype to check onProp exist or not
patchFilteredProperties(
internalWindow, getOnEventNames(internalWindow),
ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties,
ObjectGetPrototypeOf(internalWindow));
internalWindow,
getOnEventNames(internalWindow),
ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties,
ObjectGetPrototypeOf(internalWindow),
);
}
patchTargets = patchTargets.concat([
'XMLHttpRequest', 'XMLHttpRequestEventTarget', 'IDBIndex', 'IDBRequest', 'IDBOpenDBRequest',
'IDBDatabase', 'IDBTransaction', 'IDBCursor', 'WebSocket'
'XMLHttpRequest',
'XMLHttpRequestEventTarget',
'IDBIndex',
'IDBRequest',
'IDBOpenDBRequest',
'IDBDatabase',
'IDBTransaction',
'IDBCursor',
'WebSocket',
]);
for (let i = 0; i < patchTargets.length; i++) {
const target = _global[patchTargets[i]];
target && target.prototype &&
patchFilteredProperties(
target.prototype, getOnEventNames(target.prototype), ignoreProperties);
target &&
target.prototype &&
patchFilteredProperties(
target.prototype,
getOnEventNames(target.prototype),
ignoreProperties,
);
}
}
@@ -12,8 +12,12 @@ export function registerElementPatch(_global: any, api: _ZonePrivate) {
return;
}
const callbacks =
['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
const callbacks = [
'createdCallback',
'attachedCallback',
'detachedCallback',
'attributeChangedCallback',
];
api.patchCallbacks(api, document, 'Document', 'registerElement', callbacks);
}
+9 -4
View File
@@ -16,11 +16,16 @@ export function patchShadyDom(Zone: ZoneType): void {
// so zone.js need to patch them again.
const HTMLSlotElement = global.HTMLSlotElement;
const prototypes = [
Object.getPrototypeOf(window), Node.prototype, Text.prototype, Element.prototype,
HTMLElement.prototype, HTMLSlotElement && HTMLSlotElement.prototype,
DocumentFragment.prototype, Document.prototype
Object.getPrototypeOf(window),
Node.prototype,
Text.prototype,
Element.prototype,
HTMLElement.prototype,
HTMLSlotElement && HTMLSlotElement.prototype,
DocumentFragment.prototype,
Document.prototype,
];
prototypes.forEach(function(proto) {
prototypes.forEach(function (proto) {
if (proto && proto.hasOwnProperty('addEventListener')) {
proto[Zone.__symbol__('addEventListener')] = null;
proto[Zone.__symbol__('removeEventListener')] = null;
@@ -67,4 +67,4 @@ export function patchMediaQuery(Zone: ZoneType): void {
});
}
});
}
}
@@ -20,7 +20,7 @@ export function patchResizeObserver(Zone: ZoneType): void {
api.patchMethod(global, 'ResizeObserver', (delegate: Function) => (self: any, args: any[]) => {
const callback = args.length > 0 ? args[0] : null;
if (callback) {
args[0] = function(entries: any, observer: any) {
args[0] = function (entries: any, observer: any) {
const zones: {[zoneName: string]: any} = {};
const currZone = Zone.current;
for (let entry of entries) {
@@ -35,11 +35,15 @@ export function patchResizeObserver(Zone: ZoneType): void {
zoneEntriesInfo.entries.push(entry);
}
Object.keys(zones).forEach(zoneName => {
Object.keys(zones).forEach((zoneName) => {
const zoneEntriesInfo = zones[zoneName];
if (zoneEntriesInfo.zone !== Zone.current) {
zoneEntriesInfo.zone.run(
callback, this, [zoneEntriesInfo.entries, observer], 'ResizeObserver');
callback,
this,
[zoneEntriesInfo.entries, observer],
'ResizeObserver',
);
} else {
callback.call(this, zoneEntriesInfo.entries, observer);
}
@@ -50,50 +54,58 @@ export function patchResizeObserver(Zone: ZoneType): void {
});
api.patchMethod(
ResizeObserver.prototype, 'observe', (delegate: Function) => (self: any, args: any[]) => {
const target = args.length > 0 ? args[0] : null;
if (!target) {
return delegate.apply(self, args);
}
let targets = self[resizeObserverSymbol];
if (!targets) {
targets = self[resizeObserverSymbol] = [];
}
targets.push(target);
target[resizeObserverSymbol] = Zone.current;
ResizeObserver.prototype,
'observe',
(delegate: Function) => (self: any, args: any[]) => {
const target = args.length > 0 ? args[0] : null;
if (!target) {
return delegate.apply(self, args);
});
}
let targets = self[resizeObserverSymbol];
if (!targets) {
targets = self[resizeObserverSymbol] = [];
}
targets.push(target);
target[resizeObserverSymbol] = Zone.current;
return delegate.apply(self, args);
},
);
api.patchMethod(
ResizeObserver.prototype, 'unobserve', (delegate: Function) => (self: any, args: any[]) => {
const target = args.length > 0 ? args[0] : null;
if (!target) {
return delegate.apply(self, args);
}
let targets = self[resizeObserverSymbol];
if (targets) {
for (let i = 0; i < targets.length; i++) {
if (targets[i] === target) {
targets.splice(i, 1);
break;
}
ResizeObserver.prototype,
'unobserve',
(delegate: Function) => (self: any, args: any[]) => {
const target = args.length > 0 ? args[0] : null;
if (!target) {
return delegate.apply(self, args);
}
let targets = self[resizeObserverSymbol];
if (targets) {
for (let i = 0; i < targets.length; i++) {
if (targets[i] === target) {
targets.splice(i, 1);
break;
}
}
target[resizeObserverSymbol] = undefined;
return delegate.apply(self, args);
});
}
target[resizeObserverSymbol] = undefined;
return delegate.apply(self, args);
},
);
api.patchMethod(
ResizeObserver.prototype, 'disconnect',
(delegate: Function) => (self: any, args: any[]) => {
const targets = self[resizeObserverSymbol];
if (targets) {
targets.forEach((target: any) => {
target[resizeObserverSymbol] = undefined;
});
self[resizeObserverSymbol] = undefined;
}
return delegate.apply(self, args);
});
ResizeObserver.prototype,
'disconnect',
(delegate: Function) => (self: any, args: any[]) => {
const targets = self[resizeObserverSymbol];
if (targets) {
targets.forEach((target: any) => {
target[resizeObserverSymbol] = undefined;
});
self[resizeObserverSymbol] = undefined;
}
return delegate.apply(self, args);
},
);
});
}
@@ -11,7 +11,7 @@ import {ZoneType} from '../zone-impl';
export function patchUserMedia(Zone: ZoneType): void {
Zone.__load_patch('getUserMedia', (global: any, Zone: any, api: _ZonePrivate) => {
function wrapFunctionArgs(func: Function, source?: string): Function {
return function(this: unknown) {
return function (this: unknown) {
const args = Array.prototype.slice.call(arguments);
const wrappedArgs = api.bindArguments(args, source ? source : (func as any).name);
return func.apply(this, wrappedArgs);
+15 -14
View File
@@ -15,7 +15,7 @@ export function apply(api: _ZonePrivate, _global: any) {
if (!(<any>_global).EventTarget) {
api.patchEventTarget(_global, api, [WS.prototype]);
}
(<any>_global).WebSocket = function(x: any, y: any) {
(<any>_global).WebSocket = function (x: any, y: any) {
const socket = arguments.length > 1 ? new WS(x, y) : new WS(x);
let proxySocket: any;
@@ -29,20 +29,21 @@ export function apply(api: _ZonePrivate, _global: any) {
// but proxySocket not, so we will keep socket as prototype and pass it to
// patchOnProperties method
proxySocketProto = socket;
[ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(function(
propName) {
proxySocket[propName] = function() {
const args = api.ArraySlice.call(arguments);
if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) {
const eventName = args.length > 0 ? args[0] : undefined;
if (eventName) {
const propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
socket[propertySymbol] = proxySocket[propertySymbol];
[ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(
function (propName) {
proxySocket[propName] = function () {
const args = api.ArraySlice.call(arguments);
if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) {
const eventName = args.length > 0 ? args[0] : undefined;
if (eventName) {
const propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
socket[propertySymbol] = proxySocket[propertySymbol];
}
}
}
return socket[propName].apply(socket, args);
};
});
return socket[propName].apply(socket, args);
};
},
);
} else {
// we can patch the real socket
proxySocket = socket;
+125 -90
View File
@@ -24,11 +24,11 @@ export function patchError(Zone: ZoneType): void {
/// Skip this frame when printing out stack
zoneJsInternal,
/// This frame marks zone transition
transition
transition,
}
const zoneJsInternalStackFramesSymbol = api.symbol('zoneJsInternalStackFrames');
const NativeError = global[api.symbol('Error')] = global['Error'];
const NativeError = (global[api.symbol('Error')] = global['Error']);
// Store the frames which should be removed from the stack frames
const zoneJsInternalStackFrames: {[frame: string]: FrameType} = {};
// We must find the frame where Error was created, otherwise we assume we don't understand stack
@@ -41,10 +41,11 @@ export function patchError(Zone: ZoneType): void {
global['Error'] = ZoneAwareError;
const stackRewrite = 'stackRewrite';
type ZoneJsInternalStackFramesPolicy = 'default'|'disable'|'lazy';
type ZoneJsInternalStackFramesPolicy = 'default' | 'disable' | 'lazy';
const zoneJsInternalStackFramesPolicy: ZoneJsInternalStackFramesPolicy =
global['__Zone_Error_BlacklistedStackFrames_policy'] ||
global['__Zone_Error_ZoneJsInternalStackFrames_policy'] || 'default';
global['__Zone_Error_BlacklistedStackFrames_policy'] ||
global['__Zone_Error_ZoneJsInternalStackFrames_policy'] ||
'default';
interface ZoneFrameName {
zoneName: string;
@@ -64,14 +65,23 @@ export function patchError(Zone: ZoneType): void {
}
function buildZoneAwareStackFrames(
originalStack: string, zoneFrame: _ZoneFrame|ZoneFrameName|null, isZoneFrame = true) {
originalStack: string,
zoneFrame: _ZoneFrame | ZoneFrameName | null,
isZoneFrame = true,
) {
let frames: string[] = originalStack.split('\n');
let i = 0;
// Find the first frame
while (!(frames[i] === zoneAwareFrame1 || frames[i] === zoneAwareFrame2 ||
frames[i] === zoneAwareFrame1WithoutNew || frames[i] === zoneAwareFrame2WithoutNew ||
frames[i] === zoneAwareFrame3WithoutNew) &&
i < frames.length) {
while (
!(
frames[i] === zoneAwareFrame1 ||
frames[i] === zoneAwareFrame2 ||
frames[i] === zoneAwareFrame1WithoutNew ||
frames[i] === zoneAwareFrame2WithoutNew ||
frames[i] === zoneAwareFrame3WithoutNew
) &&
i < frames.length
) {
i++;
}
for (; i < frames.length && zoneFrame; i++) {
@@ -93,8 +103,9 @@ export function patchError(Zone: ZoneType): void {
i--;
break;
default:
frames[i] += isZoneFrame ? ` [${(zoneFrame as _ZoneFrame).zone.name}]` :
` [${(zoneFrame as ZoneFrameName).zoneName}]`;
frames[i] += isZoneFrame
? ` [${(zoneFrame as _ZoneFrame).zone.name}]`
: ` [${(zoneFrame as ZoneFrameName).zoneName}]`;
}
}
}
@@ -104,11 +115,11 @@ export function patchError(Zone: ZoneType): void {
* This is ZoneAwareError which processes the stack frame and cleans up extra frames as well as
* adds zone information to it.
*/
function ZoneAwareError(this: unknown|typeof NativeError): Error {
function ZoneAwareError(this: unknown | typeof NativeError): Error {
// We always have to return native error otherwise the browser console will not work.
let error: Error = NativeError.apply(this, arguments);
// Save original stack trace
const originalStack = (error as any)['originalStack'] = error.stack;
const originalStack = ((error as any)['originalStack'] = error.stack);
// Process the stack trace and rewrite the frames.
if ((ZoneAwareError as any)[stackRewrite] && originalStack) {
@@ -118,8 +129,10 @@ export function patchError(Zone: ZoneType): void {
(error as any)[api.symbol('zoneFrameNames')] = buildZoneFrameNames(zoneFrame);
} else if (zoneJsInternalStackFramesPolicy === 'default') {
try {
error.stack = error.zoneAwareStack =
buildZoneAwareStackFrames(originalStack, zoneFrame);
error.stack = error.zoneAwareStack = buildZoneAwareStackFrames(
originalStack,
zoneFrame,
);
} catch (e) {
// ignore as some browsers don't allow overriding of stack
}
@@ -129,16 +142,18 @@ export function patchError(Zone: ZoneType): void {
if (this instanceof NativeError && this.constructor != NativeError) {
// We got called with a `new` operator AND we are subclass of ZoneAwareError
// in that case we have to copy all of our properties to `this`.
Object.keys(error).concat('stack', 'message').forEach((key) => {
const value = (error as any)[key];
if (value !== undefined) {
try {
this[key] = value;
} catch (e) {
// ignore the assignment in case it is a setter and it throws.
Object.keys(error)
.concat('stack', 'message')
.forEach((key) => {
const value = (error as any)[key];
if (value !== undefined) {
try {
this[key] = value;
} catch (e) {
// ignore the assignment in case it is a setter and it throws.
}
}
}
});
});
return this;
}
return error;
@@ -156,18 +171,24 @@ export function patchError(Zone: ZoneType): void {
Object.defineProperty(ZoneAwareError.prototype, 'zoneAwareStack', {
configurable: true,
enumerable: true,
get: function() {
get: function () {
if (!this[zoneAwareStackSymbol]) {
this[zoneAwareStackSymbol] = buildZoneAwareStackFrames(
this.originalStack, this[api.symbol('zoneFrameNames')], false);
this.originalStack,
this[api.symbol('zoneFrameNames')],
false,
);
}
return this[zoneAwareStackSymbol];
},
set: function(newStack: string) {
set: function (newStack: string) {
this.originalStack = newStack;
this[zoneAwareStackSymbol] = buildZoneAwareStackFrames(
this.originalStack, this[api.symbol('zoneFrameNames')], false);
}
this.originalStack,
this[api.symbol('zoneFrameNames')],
false,
);
},
});
}
@@ -176,15 +197,15 @@ export function patchError(Zone: ZoneType): void {
// those properties of NativeError should be set to ZoneAwareError
const nativeErrorProperties = Object.keys(NativeError);
if (nativeErrorProperties) {
nativeErrorProperties.forEach(prop => {
if (specialPropertyNames.filter(sp => sp === prop).length === 0) {
nativeErrorProperties.forEach((prop) => {
if (specialPropertyNames.filter((sp) => sp === prop).length === 0) {
Object.defineProperty(ZoneAwareError, prop, {
get: function() {
get: function () {
return NativeError[prop];
},
set: function(value) {
set: function (value) {
NativeError[prop] = value;
}
},
});
}
});
@@ -196,12 +217,12 @@ export function patchError(Zone: ZoneType): void {
// make sure that ZoneAwareError has the same property which forwards to NativeError.
Object.defineProperty(ZoneAwareError, 'stackTraceLimit', {
get: function() {
get: function () {
return NativeError.stackTraceLimit;
},
set: function(value) {
return NativeError.stackTraceLimit = value;
}
set: function (value) {
return (NativeError.stackTraceLimit = value);
},
});
}
@@ -211,21 +232,23 @@ export function patchError(Zone: ZoneType): void {
// stack frame when prepareStackTrace below
value: function zoneCaptureStackTrace(targetObject: Object, constructorOpt?: Function) {
NativeError.captureStackTrace(targetObject, constructorOpt);
}
},
});
}
const ZONE_CAPTURESTACKTRACE = 'zoneCaptureStackTrace';
Object.defineProperty(ZoneAwareError, 'prepareStackTrace', {
get: function() {
get: function () {
return NativeError.prepareStackTrace;
},
set: function(value) {
set: function (value) {
if (!value || typeof value !== 'function') {
return NativeError.prepareStackTrace = value;
return (NativeError.prepareStackTrace = value);
}
return NativeError.prepareStackTrace = function(
error: Error, structuredStackTrace: {getFunctionName: Function}[]) {
return (NativeError.prepareStackTrace = function (
error: Error,
structuredStackTrace: {getFunctionName: Function}[],
) {
// remove additional stack information from ZoneAwareError.captureStackTrace
if (structuredStackTrace) {
for (let i = 0; i < structuredStackTrace.length; i++) {
@@ -238,8 +261,8 @@ export function patchError(Zone: ZoneType): void {
}
}
return value.call(this, error, structuredStackTrace);
};
}
});
},
});
if (zoneJsInternalStackFramesPolicy === 'disable') {
@@ -253,11 +276,17 @@ export function patchError(Zone: ZoneType): void {
let detectZone: Zone = Zone.current.fork({
name: 'detect',
onHandleError: function(
parentZD: ZoneDelegate, current: Zone, target: Zone, error: any): boolean {
onHandleError: function (
parentZD: ZoneDelegate,
current: Zone,
target: Zone,
error: any,
): boolean {
if (error.originalStack && Error === ZoneAwareError) {
let frames = error.originalStack.split(/\n/);
let runFrame = false, runGuardedFrame = false, runTaskFrame = false;
let runFrame = false,
runGuardedFrame = false,
runTaskFrame = false;
while (frames.length) {
let frame = frames.shift();
// On safari it is possible to have stack frame with no line number.
@@ -280,8 +309,10 @@ export function patchError(Zone: ZoneType): void {
zoneAwareFrame1WithoutNew = frame;
zoneAwareFrame2WithoutNew = frame.replace('Error.', '');
if (frame.indexOf('Error.ZoneAwareError') === -1) {
zoneAwareFrame3WithoutNew =
frame.replace('ZoneAwareError', 'Error.ZoneAwareError');
zoneAwareFrame3WithoutNew = frame.replace(
'ZoneAwareError',
'Error.ZoneAwareError',
);
}
}
zoneJsInternalStackFrames[zoneAwareFrame2] = FrameType.zoneJsInternal;
@@ -305,25 +336,25 @@ export function patchError(Zone: ZoneType): void {
}
}
return false;
}
},
}) as Zone;
// carefully constructor a stack frame which contains all of the frames of interest which
// need to be detected and marked as an internal zoneJs frame.
const childDetectZone = detectZone.fork({
name: 'child',
onScheduleTask: function(delegate, curr, target, task) {
onScheduleTask: function (delegate, curr, target, task) {
return delegate.scheduleTask(target, task);
},
onInvokeTask: function(delegate, curr, target, task, applyThis, applyArgs) {
onInvokeTask: function (delegate, curr, target, task, applyThis, applyArgs) {
return delegate.invokeTask(target, task, applyThis, applyArgs);
},
onCancelTask: function(delegate, curr, target, task) {
onCancelTask: function (delegate, curr, target, task) {
return delegate.cancelTask(target, task);
},
onInvoke: function(delegate, curr, target, callback, applyThis, applyArgs, source) {
onInvoke: function (delegate, curr, target, callback, applyThis, applyArgs, source) {
return delegate.invoke(target, callback, applyThis, applyArgs, source);
}
},
});
// we need to detect all zone related frames, it will
@@ -339,45 +370,49 @@ export function patchError(Zone: ZoneType): void {
childDetectZone.runGuarded(() => {
const fakeTransitionTo = () => {};
childDetectZone.scheduleEventTask(
zoneJsInternalStackFramesSymbol,
() => {
childDetectZone.scheduleMacroTask(
zoneJsInternalStackFramesSymbol,
() => {
childDetectZone.scheduleMacroTask(
zoneJsInternalStackFramesSymbol,
() => {
childDetectZone.scheduleMicroTask(
zoneJsInternalStackFramesSymbol,
() => {
childDetectZone.scheduleMicroTask(
zoneJsInternalStackFramesSymbol,
() => {
throw new Error();
},
undefined,
(t: Task) => {
(t as any)._transitionTo = fakeTransitionTo;
t.invoke();
});
childDetectZone.scheduleMicroTask(
zoneJsInternalStackFramesSymbol,
() => {
throw Error();
},
undefined,
(t: Task) => {
(t as any)._transitionTo = fakeTransitionTo;
t.invoke();
});
throw new Error();
},
undefined,
(t) => {
(t: Task) => {
(t as any)._transitionTo = fakeTransitionTo;
t.invoke();
},
() => {});
},
undefined,
(t) => {
(t as any)._transitionTo = fakeTransitionTo;
t.invoke();
},
() => {});
);
childDetectZone.scheduleMicroTask(
zoneJsInternalStackFramesSymbol,
() => {
throw Error();
},
undefined,
(t: Task) => {
(t as any)._transitionTo = fakeTransitionTo;
t.invoke();
},
);
},
undefined,
(t) => {
(t as any)._transitionTo = fakeTransitionTo;
t.invoke();
},
() => {},
);
},
undefined,
(t) => {
(t as any)._transitionTo = fakeTransitionTo;
t.invoke();
},
() => {},
);
});
});
+131 -66
View File
@@ -10,8 +10,17 @@
* @suppress {missingRequire}
*/
import {ADD_EVENT_LISTENER_STR, attachOriginToPatched, FALSE_STR, isNode, ObjectGetPrototypeOf, REMOVE_EVENT_LISTENER_STR, TRUE_STR, ZONE_SYMBOL_PREFIX, zoneSymbol} from './utils';
import {
ADD_EVENT_LISTENER_STR,
attachOriginToPatched,
FALSE_STR,
isNode,
ObjectGetPrototypeOf,
REMOVE_EVENT_LISTENER_STR,
TRUE_STR,
ZONE_SYMBOL_PREFIX,
zoneSymbol,
} from './utils';
/** @internal **/
interface EventTaskData extends TaskData {
@@ -24,9 +33,9 @@ let passiveSupported = false;
if (typeof window !== 'undefined') {
try {
const options = Object.defineProperty({}, 'passive', {
get: function() {
get: function () {
passiveSupported = true;
}
},
});
// Note: We pass the `options` object as the event handler too. This is not compatible with the
// signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
@@ -40,7 +49,7 @@ if (typeof window !== 'undefined') {
// an identifier to tell ZoneTask do not create a new invoke closure
const OPTIMIZED_ZONE_EVENT_TASK_DATA: EventTaskData = {
useG: true
useG: true,
};
export const zoneSymbolEventNames: any = {};
@@ -89,13 +98,17 @@ export interface PatchEventTargetOptions {
}
export function patchEventTarget(
_global: any, api: _ZonePrivate, apis: any[], patchOptions?: PatchEventTargetOptions) {
_global: any,
api: _ZonePrivate,
apis: any[],
patchOptions?: PatchEventTargetOptions,
) {
const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
const REMOVE_ALL_LISTENERS_EVENT_LISTENER =
(patchOptions && patchOptions.rmAll) || 'removeAllListeners';
(patchOptions && patchOptions.rmAll) || 'removeAllListeners';
const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
@@ -104,7 +117,7 @@ export function patchEventTarget(
const PREPEND_EVENT_LISTENER = 'prependListener';
const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
const invokeTask = function(task: any, target: any, event: Event): Error|undefined {
const invokeTask = function (task: any, target: any, event: Event): Error | undefined {
// for better performance, check isRemoved which is set
// by removeEventListener
if (task.isRemoved) {
@@ -184,12 +197,12 @@ export function patchEventTarget(
}
// global shared zoneAwareCallback to handle all event callback with capture = false
const globalZoneAwareCallback = function(this: unknown, event: Event) {
const globalZoneAwareCallback = function (this: unknown, event: Event) {
return globalCallback(this, event, false);
};
// global shared zoneAwareCallback to handle all event callback with capture = true
const globalZoneAwareCaptureCallback = function(this: unknown, event: Event) {
const globalZoneAwareCaptureCallback = function (this: unknown, event: Event) {
return globalCallback(this, event, true);
};
@@ -236,19 +249,19 @@ export function patchEventTarget(
// so we do not need to create a new object just for pass some data
const taskData: any = {};
const nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
const nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
proto[REMOVE_EVENT_LISTENER];
const nativeAddEventListener = (proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER]);
const nativeRemoveEventListener = (proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
proto[REMOVE_EVENT_LISTENER]);
const nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
proto[LISTENERS_EVENT_LISTENER];
const nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
const nativeListeners = (proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
proto[LISTENERS_EVENT_LISTENER]);
const nativeRemoveAllListeners = (proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER]);
let nativePrependEventListener: any;
if (patchOptions && patchOptions.prepend) {
nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
proto[patchOptions.prepend];
proto[patchOptions.prepend];
}
/**
@@ -277,19 +290,21 @@ export function patchEventTarget(
return options;
}
const customScheduleGlobal = function(task: Task) {
const customScheduleGlobal = function (task: Task) {
// if there is already a task for the eventName + capture,
// just return, because we use the shared globalZoneAwareCallback here.
if (taskData.isExisting) {
return;
}
return nativeAddEventListener.call(
taskData.target, taskData.eventName,
taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback,
taskData.options);
taskData.target,
taskData.eventName,
taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback,
taskData.options,
);
};
const customCancelGlobal = function(task: any) {
const customCancelGlobal = function (task: any) {
// if task is not marked as isRemoved, this call is directly
// from Zone.prototype.cancelTask, we should remove the task
// from tasksList of target first
@@ -325,43 +340,61 @@ export function patchEventTarget(
return;
}
return nativeRemoveEventListener.call(
task.target, task.eventName,
task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
task.target,
task.eventName,
task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback,
task.options,
);
};
const customScheduleNonGlobal = function(task: Task) {
const customScheduleNonGlobal = function (task: Task) {
return nativeAddEventListener.call(
taskData.target, taskData.eventName, task.invoke, taskData.options);
taskData.target,
taskData.eventName,
task.invoke,
taskData.options,
);
};
const customSchedulePrepend = function(task: Task) {
const customSchedulePrepend = function (task: Task) {
return nativePrependEventListener.call(
taskData.target, taskData.eventName, task.invoke, taskData.options);
taskData.target,
taskData.eventName,
task.invoke,
taskData.options,
);
};
const customCancelNonGlobal = function(task: any) {
const customCancelNonGlobal = function (task: any) {
return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
};
const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
const compareTaskCallbackVsDelegate = function(task: any, delegate: any) {
const compareTaskCallbackVsDelegate = function (task: any, delegate: any) {
const typeOfDelegate = typeof delegate;
return (typeOfDelegate === 'function' && task.callback === delegate) ||
(typeOfDelegate === 'object' && task.originalDelegate === delegate);
return (
(typeOfDelegate === 'function' && task.callback === delegate) ||
(typeOfDelegate === 'object' && task.originalDelegate === delegate)
);
};
const compare =
(patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
patchOptions && patchOptions.diff ? patchOptions.diff : compareTaskCallbackVsDelegate;
const unpatchedEvents: string[] = (Zone as any)[zoneSymbol('UNPATCHED_EVENTS')];
const passiveEvents: string[] = _global[zoneSymbol('PASSIVE_EVENTS')];
const makeAddListener = function(
nativeListener: any, addSource: string, customScheduleFn: any, customCancelFn: any,
returnTarget = false, prepend = false) {
return function(this: unknown) {
const makeAddListener = function (
nativeListener: any,
addSource: string,
customScheduleFn: any,
customCancelFn: any,
returnTarget = false,
prepend = false,
) {
return function (this: unknown) {
const target = this || _global;
let eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
@@ -392,12 +425,15 @@ export function patchEventTarget(
}
const passive =
passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
const options = buildEventListenerOptions(arguments[2], passive);
const signal = options && typeof options === 'object' && options.signal &&
typeof options.signal === 'object' ?
options.signal :
undefined;
const signal =
options &&
typeof options === 'object' &&
options.signal &&
typeof options.signal === 'object'
? options.signal
: undefined;
if (signal?.aborted) {
// the signal is an aborted one, just return without attaching the event listener.
return;
@@ -449,8 +485,10 @@ export function patchEventTarget(
source = targetSource[eventName];
}
if (!source) {
source = constructorName + addSource +
(eventNameToString ? eventNameToString(eventName) : eventName);
source =
constructorName +
addSource +
(eventNameToString ? eventNameToString(eventName) : eventName);
}
// do not create a new object as task.data to pass those things
// just use the global shared one
@@ -479,15 +517,25 @@ export function patchEventTarget(
// and handle ourselves.
taskData.options.signal = undefined;
}
const task: any =
zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
const task: any = zone.scheduleEventTask(
source,
delegate,
data,
customScheduleFn,
customCancelFn,
);
if (signal) {
// after task is scheduled, we need to store the signal back to task.options
taskData.options.signal = signal;
nativeListener.call(signal, 'abort', () => {
task.zone.cancelTask(task);
}, {once: true});
nativeListener.call(
signal,
'abort',
() => {
task.zone.cancelTask(task);
},
{once: true},
);
}
// should clear taskData.target to avoid memory leak
@@ -529,15 +577,24 @@ export function patchEventTarget(
};
proto[ADD_EVENT_LISTENER] = makeAddListener(
nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel,
returnTarget);
nativeAddEventListener,
ADD_EVENT_LISTENER_SOURCE,
customSchedule,
customCancel,
returnTarget,
);
if (nativePrependEventListener) {
proto[PREPEND_EVENT_LISTENER] = makeAddListener(
nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend,
customCancel, returnTarget, true);
nativePrependEventListener,
PREPEND_EVENT_LISTENER_SOURCE,
customSchedulePrepend,
customCancel,
returnTarget,
true,
);
}
proto[REMOVE_EVENT_LISTENER] = function() {
proto[REMOVE_EVENT_LISTENER] = function () {
const target = this || _global;
let eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
@@ -551,8 +608,10 @@ export function patchEventTarget(
return nativeRemoveEventListener.apply(this, arguments);
}
if (validateHandler &&
!validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
if (
validateHandler &&
!validateHandler(nativeRemoveEventListener, delegate, target, arguments)
) {
return;
}
@@ -599,7 +658,7 @@ export function patchEventTarget(
return nativeRemoveEventListener.apply(this, arguments);
};
proto[LISTENERS_EVENT_LISTENER] = function() {
proto[LISTENERS_EVENT_LISTENER] = function () {
const target = this || _global;
let eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
@@ -607,8 +666,10 @@ export function patchEventTarget(
}
const listeners: any[] = [];
const tasks =
findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
const tasks = findEventTasks(
target,
eventNameToString ? eventNameToString(eventName) : eventName,
);
for (let i = 0; i < tasks.length; i++) {
const task: any = tasks[i];
@@ -618,7 +679,7 @@ export function patchEventTarget(
return listeners;
};
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function() {
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
const target = this || _global;
let eventName = arguments[0];
@@ -722,8 +783,9 @@ export function findEventTasks(target: any, eventName: string): Task[] {
if (!captureFalseTasks) {
return captureTrueTasks ? captureTrueTasks.slice() : [];
} else {
return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
captureFalseTasks.slice();
return captureTrueTasks
? captureFalseTasks.concat(captureTrueTasks)
: captureFalseTasks.slice();
}
}
@@ -731,13 +793,16 @@ export function patchEventPrototype(global: any, api: _ZonePrivate) {
const Event = global['Event'];
if (Event && Event.prototype) {
api.patchMethod(
Event.prototype, 'stopImmediatePropagation',
(delegate: Function) => function(self: any, args: any[]) {
Event.prototype,
'stopImmediatePropagation',
(delegate: Function) =>
function (self: any, args: any[]) {
self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
// we need to call the native stopImmediatePropagation
// in case in some hybrid application, some part of
// application will be controlled by zone, some are not
delegate && delegate.apply(self, args);
});
},
);
}
}
+77 -60
View File
@@ -30,60 +30,70 @@ export function patchFetch(Zone: ZoneType): void {
const symbolThenPatched = api.symbol('thenPatched');
const fetchTaskScheduling = api.symbol('fetchTaskScheduling');
const OriginalResponse = global.Response;
const placeholder = function() {};
const placeholder = function () {};
const createFetchTask =
(source: string, data: TaskData|undefined, originalImpl: any, self: any, args: any[],
ac?: AbortController) => new Promise((resolve, reject) => {
const task = Zone.current.scheduleMacroTask(
source, placeholder, data,
() => {
// The promise object returned by the original implementation passed into the
// function. This might be a `fetch` promise, `Response.prototype.json` promise,
// etc.
let implPromise;
let zone = Zone.current;
const createFetchTask = (
source: string,
data: TaskData | undefined,
originalImpl: any,
self: any,
args: any[],
ac?: AbortController,
) =>
new Promise((resolve, reject) => {
const task = Zone.current.scheduleMacroTask(
source,
placeholder,
data,
() => {
// The promise object returned by the original implementation passed into the
// function. This might be a `fetch` promise, `Response.prototype.json` promise,
// etc.
let implPromise;
let zone = Zone.current;
try {
(zone as any)[fetchTaskScheduling] = true;
implPromise = originalImpl.apply(self, args);
} catch (error) {
reject(error);
return;
} finally {
(zone as any)[fetchTaskScheduling] = false;
try {
(zone as any)[fetchTaskScheduling] = true;
implPromise = originalImpl.apply(self, args);
} catch (error) {
reject(error);
return;
} finally {
(zone as any)[fetchTaskScheduling] = false;
}
if (!(implPromise instanceof ZoneAwarePromise)) {
let ctor = implPromise.constructor;
if (!ctor[symbolThenPatched]) {
api.patchThen(ctor);
}
}
implPromise.then(
(resource: any) => {
if (task.state !== 'notScheduled') {
task.invoke();
}
if (!(implPromise instanceof ZoneAwarePromise)) {
let ctor = implPromise.constructor;
if (!ctor[symbolThenPatched]) {
api.patchThen(ctor);
}
}
implPromise.then(
(resource: any) => {
if (task.state !== 'notScheduled') {
task.invoke();
}
resolve(resource);
},
(error: any) => {
if (task.state !== 'notScheduled') {
task.invoke();
}
reject(error);
});
resolve(resource);
},
() => {
ac?.abort();
});
});
(error: any) => {
if (task.state !== 'notScheduled') {
task.invoke();
}
reject(error);
},
);
},
() => {
ac?.abort();
},
);
});
global['fetch'] = function() {
global['fetch'] = function () {
const args = Array.prototype.slice.call(arguments);
const options = args.length > 1 ? args[1] : {};
const signal: AbortSignal|undefined = options?.signal;
const signal: AbortSignal | undefined = options?.signal;
const ac = new AbortController();
const fetchSignal = ac.signal;
options.signal = fetchSignal;
@@ -91,12 +101,17 @@ export function patchFetch(Zone: ZoneType): void {
if (signal) {
const nativeAddEventListener =
signal[Zone.__symbol__('addEventListener') as 'addEventListener'] ||
signal.addEventListener;
signal[Zone.__symbol__('addEventListener') as 'addEventListener'] ||
signal.addEventListener;
nativeAddEventListener.call(signal, 'abort', function() {
ac!.abort();
}, {once: true});
nativeAddEventListener.call(
signal,
'abort',
function () {
ac!.abort();
},
{once: true},
);
}
return createFetchTask('fetch', {fetchArgs: args} as FetchTaskData, fetch, this, args, ac);
@@ -105,14 +120,16 @@ export function patchFetch(Zone: ZoneType): void {
if (OriginalResponse?.prototype) {
// https://fetch.spec.whatwg.org/#body-mixin
['arrayBuffer', 'blob', 'formData', 'json', 'text']
// Safely check whether the method exists on the `Response` prototype before patching.
.filter(method => typeof OriginalResponse.prototype[method] === 'function')
.forEach(method => {
api.patchMethod(
OriginalResponse.prototype, method,
(delegate: Function) => (self, args) => createFetchTask(
`Response.${method}`, undefined, delegate, self, args, undefined));
});
// Safely check whether the method exists on the `Response` prototype before patching.
.filter((method) => typeof OriginalResponse.prototype[method] === 'function')
.forEach((method) => {
api.patchMethod(
OriginalResponse.prototype,
method,
(delegate: Function) => (self, args) =>
createFetchTask(`Response.${method}`, undefined, delegate, self, args, undefined),
);
});
}
});
}
+155 -112
View File
@@ -26,7 +26,7 @@ export function patchPromise(Zone: ZoneType): void {
const __symbol__ = api.symbol;
const _uncaughtPromiseErrors: UncaughtPromiseError[] = [];
const isDisableWrappingUncaughtPromiseRejection =
global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] !== false;
global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] !== false;
const symbolPromise = __symbol__('Promise');
const symbolThen = __symbol__('then');
const creationTrace = '__creationTrace__';
@@ -36,10 +36,16 @@ export function patchPromise(Zone: ZoneType): void {
const rejection = e && e.rejection;
if (rejection) {
console.error(
'Unhandled Promise rejection:',
rejection instanceof Error ? rejection.message : rejection,
'; Zone:', (<Zone>e.zone).name, '; Task:', e.task && (<Task>e.task).source,
'; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
'Unhandled Promise rejection:',
rejection instanceof Error ? rejection.message : rejection,
'; Zone:',
(<Zone>e.zone).name,
'; Task:',
e.task && (<Task>e.task).source,
'; Value:',
rejection,
rejection instanceof Error ? rejection.stack : undefined,
);
} else {
console.error(e);
}
@@ -62,8 +68,9 @@ export function patchPromise(Zone: ZoneType): void {
}
};
const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL =
__symbol__('unhandledPromiseRejectionHandler');
const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__(
'unhandledPromiseRejectionHandler',
);
function handleUnhandledRejection(this: unknown, e: any) {
api.onUnhandledError(e);
@@ -72,8 +79,7 @@ export function patchPromise(Zone: ZoneType): void {
if (typeof handler === 'function') {
handler.call(this, e);
}
} catch (err) {
}
} catch (err) {}
}
function isThenable(value: any): boolean {
@@ -110,11 +116,11 @@ export function patchPromise(Zone: ZoneType): void {
};
}
const once = function() {
const once = function () {
let wasCalled = false;
return function wrapper(wrappedFunction: Function) {
return function() {
return function () {
if (wasCalled) {
return;
}
@@ -129,7 +135,10 @@ export function patchPromise(Zone: ZoneType): void {
// Promise Resolution
function resolvePromise(
promise: ZoneAwarePromise<any>, state: boolean, value: any): ZoneAwarePromise<any> {
promise: ZoneAwarePromise<any>,
state: boolean,
value: any,
): ZoneAwarePromise<any> {
const onceWrapper = once();
if (promise === value) {
throw new TypeError(TYPE_ERROR);
@@ -148,16 +157,22 @@ export function patchPromise(Zone: ZoneType): void {
return promise;
}
// if (value instanceof ZoneAwarePromise) {
if (state !== REJECTED && value instanceof ZoneAwarePromise &&
value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
(value as any)[symbolState] !== UNRESOLVED) {
if (
state !== REJECTED &&
value instanceof ZoneAwarePromise &&
value.hasOwnProperty(symbolState) &&
value.hasOwnProperty(symbolValue) &&
(value as any)[symbolState] !== UNRESOLVED
) {
clearRejectedNoCatch(value);
resolvePromise(promise, (value as any)[symbolState], (value as any)[symbolValue]);
} else if (state !== REJECTED && typeof then === 'function') {
try {
then.call(
value, onceWrapper(makeResolver(promise, state)),
onceWrapper(makeResolver(promise, false)));
value,
onceWrapper(makeResolver(promise, state)),
onceWrapper(makeResolver(promise, false)),
);
} catch (err) {
onceWrapper(() => {
resolvePromise(promise, false, err);
@@ -182,17 +197,22 @@ export function patchPromise(Zone: ZoneType): void {
// do some additional work such as render longStackTrace
if (state === REJECTED && value instanceof Error) {
// check if longStackTraceZone is here
const trace = Zone.currentTask && Zone.currentTask.data &&
(Zone.currentTask.data as any)[creationTrace];
const trace =
Zone.currentTask &&
Zone.currentTask.data &&
(Zone.currentTask.data as any)[creationTrace];
if (trace) {
// only keep the long stack trace into error when in longStackTraceZone
ObjectDefineProperty(
value, CURRENT_TASK_TRACE_SYMBOL,
{configurable: true, enumerable: false, writable: true, value: trace});
ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, {
configurable: true,
enumerable: false,
writable: true,
value: trace,
});
}
}
for (let i = 0; i < queue.length;) {
for (let i = 0; i < queue.length; ) {
scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
}
if (queue.length == 0 && state == REJECTED) {
@@ -203,8 +223,10 @@ export function patchPromise(Zone: ZoneType): void {
// and if the value is not an error, zone.js builds an `Error`
// Object here to attach the stack information.
throw new Error(
'Uncaught (in promise): ' + readableObjectToString(value) +
(value && value.stack ? '\n' + value.stack : ''));
'Uncaught (in promise): ' +
readableObjectToString(value) +
(value && value.stack ? '\n' + value.stack : ''),
);
} catch (err) {
uncaughtPromiseError = err;
}
@@ -218,7 +240,7 @@ export function patchPromise(Zone: ZoneType): void {
uncaughtPromiseError.zone = Zone.current;
uncaughtPromiseError.task = Zone.currentTask!;
_uncaughtPromiseErrors.push(uncaughtPromiseError);
api.scheduleMicroTask(); // to make sure that it is running
api.scheduleMicroTask(); // to make sure that it is running
}
}
}
@@ -239,8 +261,7 @@ export function patchPromise(Zone: ZoneType): void {
if (handler && typeof handler === 'function') {
handler.call(this, {rejection: (promise as any)[symbolValue], promise: promise});
}
} catch (err) {
}
} catch (err) {}
(promise as any)[symbolState] = REJECTED;
for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
if (promise === _uncaughtPromiseErrors[i].promise) {
@@ -251,42 +272,54 @@ export function patchPromise(Zone: ZoneType): void {
}
function scheduleResolveOrReject<R, U1, U2>(
promise: ZoneAwarePromise<any>, zone: Zone, chainPromise: ZoneAwarePromise<any>,
onFulfilled?: ((value: R) => U1)|null|undefined,
onRejected?: ((error: any) => U2)|null|undefined): void {
promise: ZoneAwarePromise<any>,
zone: Zone,
chainPromise: ZoneAwarePromise<any>,
onFulfilled?: ((value: R) => U1) | null | undefined,
onRejected?: ((error: any) => U2) | null | undefined,
): void {
clearRejectedNoCatch(promise);
const promiseState = (promise as any)[symbolState];
const delegate = promiseState ?
(typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
(typeof onRejected === 'function') ? onRejected :
forwardRejection;
zone.scheduleMicroTask(source, () => {
try {
const parentPromiseValue = (promise as any)[symbolValue];
const isFinallyPromise =
const delegate = promiseState
? typeof onFulfilled === 'function'
? onFulfilled
: forwardResolution
: typeof onRejected === 'function'
? onRejected
: forwardRejection;
zone.scheduleMicroTask(
source,
() => {
try {
const parentPromiseValue = (promise as any)[symbolValue];
const isFinallyPromise =
!!chainPromise && symbolFinally === (chainPromise as any)[symbolFinally];
if (isFinallyPromise) {
// if the promise is generated from finally call, keep parent promise's state and value
(chainPromise as any)[symbolParentPromiseValue] = parentPromiseValue;
(chainPromise as any)[symbolParentPromiseState] = promiseState;
if (isFinallyPromise) {
// if the promise is generated from finally call, keep parent promise's state and value
(chainPromise as any)[symbolParentPromiseValue] = parentPromiseValue;
(chainPromise as any)[symbolParentPromiseState] = promiseState;
}
// should not pass value to finally callback
const value = zone.run(
delegate,
undefined,
isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution
? []
: [parentPromiseValue],
);
resolvePromise(chainPromise, true, value);
} catch (error) {
// if error occurs, should always return this error
resolvePromise(chainPromise, false, error);
}
// should not pass value to finally callback
const value = zone.run(
delegate, undefined,
isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
[] :
[parentPromiseValue]);
resolvePromise(chainPromise, true, value);
} catch (error) {
// if error occurs, should always return this error
resolvePromise(chainPromise, false, error);
}
}, chainPromise as TaskData);
},
chainPromise as TaskData,
);
}
const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
const noop = function() {};
const noop = function () {};
const AggregateError = global.AggregateError;
@@ -307,9 +340,9 @@ export function patchPromise(Zone: ZoneType): void {
}
static withResolvers<T>(): {
promise: Promise<T>,
resolve: (value?: T|PromiseLike<T>) => void,
reject: (error?: any) => void
promise: Promise<T>;
resolve: (value?: T | PromiseLike<T>) => void;
reject: (error?: any) => void;
} {
const result: any = {};
result.promise = new ZoneAwarePromise((res, rej) => {
@@ -341,24 +374,25 @@ export function patchPromise(Zone: ZoneType): void {
return new ZoneAwarePromise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(
v => {
if (finished) {
return;
}
(v) => {
if (finished) {
return;
}
finished = true;
resolve(v);
},
(err) => {
errors.push(err);
count--;
if (count === 0) {
finished = true;
resolve(v);
},
err => {
errors.push(err);
count--;
if (count === 0) {
finished = true;
reject(new AggregateError(errors, 'All promises were rejected'));
}
});
reject(new AggregateError(errors, 'All promises were rejected'));
}
},
);
}
});
};
}
static race<R>(values: PromiseLike<any>[]): Promise<R> {
let resolve: (v: any) => void;
@@ -391,14 +425,17 @@ export function patchPromise(Zone: ZoneType): void {
const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
return P.allWithCallback(values, {
thenCallback: (value: any) => ({status: 'fulfilled', value}),
errorCallback: (err: any) => ({status: 'rejected', reason: err})
errorCallback: (err: any) => ({status: 'rejected', reason: err}),
});
}
static allWithCallback<R>(values: any, callback?: {
thenCallback: (value: any) => any,
errorCallback: (err: any) => any
}): Promise<R> {
static allWithCallback<R>(
values: any,
callback?: {
thenCallback: (value: any) => any;
errorCallback: (err: any) => any;
},
): Promise<R> {
let resolve: (v: any) => void;
let reject: (v: any) => void;
let promise = new this<R>((res, rej) => {
@@ -419,24 +456,25 @@ export function patchPromise(Zone: ZoneType): void {
const curValueIndex = valueIndex;
try {
value.then(
(value: any) => {
resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
(value: any) => {
resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
unresolvedCount--;
if (unresolvedCount === 0) {
resolve!(resolvedValues);
}
},
(err: any) => {
if (!callback) {
reject!(err);
} else {
resolvedValues[curValueIndex] = callback.errorCallback(err);
unresolvedCount--;
if (unresolvedCount === 0) {
resolve!(resolvedValues);
}
},
(err: any) => {
if (!callback) {
reject!(err);
} else {
resolvedValues[curValueIndex] = callback.errorCallback(err);
unresolvedCount--;
if (unresolvedCount === 0) {
resolve!(resolvedValues);
}
}
});
}
},
);
} catch (thenErr) {
reject!(thenErr);
}
@@ -456,37 +494,41 @@ export function patchPromise(Zone: ZoneType): void {
}
constructor(
executor: (resolve: (value?: R|PromiseLike<R>) => void, reject: (error?: any) => void) =>
void) {
executor: (
resolve: (value?: R | PromiseLike<R>) => void,
reject: (error?: any) => void,
) => void,
) {
const promise: ZoneAwarePromise<R> = this;
if (!(promise instanceof ZoneAwarePromise)) {
throw new Error('Must be an instanceof Promise.');
}
(promise as any)[symbolState] = UNRESOLVED;
(promise as any)[symbolValue] = []; // queue;
(promise as any)[symbolValue] = []; // queue;
try {
const onceWrapper = once();
executor &&
executor(
onceWrapper(makeResolver(promise, RESOLVED)),
onceWrapper(makeResolver(promise, REJECTED)));
executor(
onceWrapper(makeResolver(promise, RESOLVED)),
onceWrapper(makeResolver(promise, REJECTED)),
);
} catch (error) {
resolvePromise(promise, false, error);
}
}
get[Symbol.toStringTag]() {
get [Symbol.toStringTag]() {
return 'Promise' as any;
}
get[Symbol.species]() {
get [Symbol.species]() {
return ZoneAwarePromise;
}
then<TResult1 = R, TResult2 = never>(
onFulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>)|undefined|null,
onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>)|undefined|
null): Promise<TResult1|TResult2> {
onFulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>) | undefined | null,
onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,
): Promise<TResult1 | TResult2> {
// We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
// may be an object without a prototype (created through `Object.create(null)`); thus
// `this.constructor` will be undefined. One of the use cases is SystemJS creating
@@ -499,7 +541,7 @@ export function patchPromise(Zone: ZoneType): void {
if (!C || typeof C !== 'function') {
C = this.constructor || ZoneAwarePromise;
}
const chainPromise: Promise<TResult1|TResult2> = new (C as typeof ZoneAwarePromise)(noop);
const chainPromise: Promise<TResult1 | TResult2> = new (C as typeof ZoneAwarePromise)(noop);
const zone = Zone.current;
if ((this as any)[symbolState] == UNRESOLVED) {
(<any[]>(this as any)[symbolValue]).push(zone, chainPromise, onFulfilled, onRejected);
@@ -509,8 +551,9 @@ export function patchPromise(Zone: ZoneType): void {
return chainPromise;
}
catch<TResult = never>(onRejected?: ((reason: any) => TResult | PromiseLike<TResult>)|
undefined|null): Promise<R|TResult> {
catch<TResult = never>(
onRejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null,
): Promise<R | TResult> {
return this.then(null, onRejected);
}
@@ -520,7 +563,7 @@ export function patchPromise(Zone: ZoneType): void {
if (!C || typeof C !== 'function') {
C = ZoneAwarePromise;
}
const chainPromise: Promise<R|never> = new (C as typeof ZoneAwarePromise)(noop);
const chainPromise: Promise<R | never> = new (C as typeof ZoneAwarePromise)(noop);
(chainPromise as any)[symbolFinally] = symbolFinally;
const zone = Zone.current;
if ((this as any)[symbolState] == UNRESOLVED) {
@@ -538,7 +581,7 @@ export function patchPromise(Zone: ZoneType): void {
ZoneAwarePromise['race'] = ZoneAwarePromise.race;
ZoneAwarePromise['all'] = ZoneAwarePromise.all;
const NativePromise = global[symbolPromise] = global['Promise'];
const NativePromise = (global[symbolPromise] = global['Promise']);
global['Promise'] = ZoneAwarePromise;
const symbolThenPatched = __symbol__('thenPatched');
@@ -557,7 +600,7 @@ export function patchPromise(Zone: ZoneType): void {
// Keep a reference to the original method.
proto[symbolThen] = originalThen;
Ctor.prototype.then = function(onResolve: any, onReject: any) {
Ctor.prototype.then = function (onResolve: any, onReject: any) {
const wrapped = new ZoneAwarePromise((resolve, reject) => {
originalThen.call(this, resolve, reject);
});
@@ -569,7 +612,7 @@ export function patchPromise(Zone: ZoneType): void {
api.patchThen = patchThen;
function zoneify(fn: Function) {
return function(self: any, args: any[]) {
return function (self: any, args: any[]) {
let resultPromise = fn.apply(self, args);
if (resultPromise instanceof ZoneAwarePromise) {
return resultPromise;
@@ -584,7 +627,7 @@ export function patchPromise(Zone: ZoneType): void {
if (NativePromise) {
patchThen(NativePromise);
patchMethod(global, 'fetch', delegate => zoneify(delegate));
patchMethod(global, 'fetch', (delegate) => zoneify(delegate));
}
// This is not part of public API, but it is useful for tests, so we expose it.
@@ -12,7 +12,7 @@
export function patchQueueMicrotask(global: any, api: _ZonePrivate) {
api.patchMethod(global, 'queueMicrotask', (delegate) => {
return function(self: any, args: any[]) {
return function (self: any, args: any[]) {
Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
};
});
+38 -19
View File
@@ -20,8 +20,8 @@ interface TimerOptions extends TaskData {
}
export function patchTimer(window: any, setName: string, cancelName: string, nameSuffix: string) {
let setNative: Function|null = null;
let clearNative: Function|null = null;
let setNative: Function | null = null;
let clearNative: Function | null = null;
setName += nameSuffix;
cancelName += nameSuffix;
@@ -29,7 +29,7 @@ export function patchTimer(window: any, setName: string, cancelName: string, nam
function scheduleTask(task: Task) {
const data = <TimerOptions>task.data;
data.args[0] = function() {
data.args[0] = function () {
return task.invoke.apply(this, arguments);
};
data.handleId = setNative!.apply(window, data.args);
@@ -40,14 +40,16 @@ export function patchTimer(window: any, setName: string, cancelName: string, nam
return clearNative!.call(window, (<TimerOptions>task.data).handleId);
}
setNative =
patchMethod(window, setName, (delegate: Function) => function(self: any, args: any[]) {
setNative = patchMethod(
window,
setName,
(delegate: Function) =>
function (self: any, args: any[]) {
if (typeof args[0] === 'function') {
const options: TimerOptions = {
isPeriodic: nameSuffix === 'Interval',
delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
undefined,
args: args
delay: nameSuffix === 'Timeout' || nameSuffix === 'Interval' ? args[1] || 0 : undefined,
args: args,
};
const callback = args[0];
args[0] = function timer(this: unknown) {
@@ -62,7 +64,7 @@ export function patchTimer(window: any, setName: string, cancelName: string, nam
// Cleanup tasksByHandleId should be handled before scheduleTask
// Since some zoneSpec may intercept and doesn't trigger
// scheduleFn(scheduleTask) provided here.
if (!(options.isPeriodic)) {
if (!options.isPeriodic) {
if (typeof options.handleId === 'number') {
// in non-nodejs env, we remove timerId
// from local cache
@@ -75,8 +77,13 @@ export function patchTimer(window: any, setName: string, cancelName: string, nam
}
}
};
const task =
scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
const task = scheduleMacroTaskWithCurrentZone(
setName,
args[0],
options,
scheduleTask,
clearTask,
);
if (!task) {
return task;
}
@@ -94,8 +101,13 @@ export function patchTimer(window: any, setName: string, cancelName: string, nam
// check whether handle is null, because some polyfill or browser
// may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
typeof handle.unref === 'function') {
if (
handle &&
handle.ref &&
handle.unref &&
typeof handle.ref === 'function' &&
typeof handle.unref === 'function'
) {
(<any>task).ref = (<any>handle).ref.bind(handle);
(<any>task).unref = (<any>handle).unref.bind(handle);
}
@@ -107,10 +119,14 @@ export function patchTimer(window: any, setName: string, cancelName: string, nam
// cause an error by calling it directly.
return delegate.apply(window, args);
}
});
},
);
clearNative =
patchMethod(window, cancelName, (delegate: Function) => function(self: any, args: any[]) {
clearNative = patchMethod(
window,
cancelName,
(delegate: Function) =>
function (self: any, args: any[]) {
const id = args[0];
let task: Task;
if (typeof id === 'number') {
@@ -125,8 +141,10 @@ export function patchTimer(window: any, setName: string, cancelName: string, nam
}
}
if (task && typeof task.type === 'string') {
if (task.state !== 'notScheduled' &&
(task.cancelFn && task.data!.isPeriodic || task.runCount === 0)) {
if (
task.state !== 'notScheduled' &&
((task.cancelFn && task.data!.isPeriodic) || task.runCount === 0)
) {
if (typeof id === 'number') {
delete tasksByHandleId[id];
} else if (id) {
@@ -139,5 +157,6 @@ export function patchTimer(window: any, setName: string, cancelName: string, nam
// cause an error by calling it directly.
delegate.apply(window, args);
}
});
},
);
}
+1 -2
View File
@@ -47,11 +47,10 @@ export function patchToString(Zone: ZoneType): void {
(newFunctionToString as any)[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
Function.prototype.toString = newFunctionToString;
// patch Object.prototype.toString to let them look like native
const originalObjectToString = Object.prototype.toString;
const PROMISE_OBJECT_TO_STRING = '[object Promise]';
Object.prototype.toString = function() {
Object.prototype.toString = function () {
if (typeof Promise === 'function' && this instanceof Promise) {
return PROMISE_OBJECT_TO_STRING;
}
+95 -63
View File
@@ -46,8 +46,12 @@ export function wrapWithCurrentZone<T extends Function>(callback: T, source: str
}
export function scheduleMacroTaskWithCurrentZone(
source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void): MacroTask {
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void,
): MacroTask {
return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
}
@@ -57,7 +61,7 @@ declare const WorkerGlobalScope: any;
export const zoneSymbol = __symbol__;
const isWindowExists = typeof window !== 'undefined';
const internalWindow: any = isWindowExists ? window : undefined;
const _global: any = isWindowExists && internalWindow || globalThis;
const _global: any = (isWindowExists && internalWindow) || globalThis;
const REMOVE_ATTRIBUTE = 'removeAttribute';
@@ -81,7 +85,7 @@ export function patchPrototype(prototype: any, fnNames: string[]) {
continue;
}
prototype[name] = ((delegate: Function) => {
const patched: any = function(this: unknown) {
const patched: any = function (this: unknown) {
return delegate.apply(this, bindArguments(<any>arguments, source + '.' + name));
};
attachOriginToPatched(patched, delegate);
@@ -104,27 +108,30 @@ export function isPropertyWritable(propertyDesc: any) {
}
export const isWebWorker: boolean =
(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
// Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
// this code.
export const isNode: boolean =
(!('nw' in _global) && typeof _global.process !== 'undefined' &&
{}.toString.call(_global.process) === '[object process]');
!('nw' in _global) &&
typeof _global.process !== 'undefined' &&
{}.toString.call(_global.process) === '[object process]';
export const isBrowser: boolean =
!isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
!isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
// we are in electron of nw, so we are both browser and nodejs
// Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
// this code.
export const isMix: boolean = typeof _global.process !== 'undefined' &&
{}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
!!(isWindowExists && internalWindow['HTMLElement']);
export const isMix: boolean =
typeof _global.process !== 'undefined' &&
{}.toString.call(_global.process) === '[object process]' &&
!isWebWorker &&
!!(isWindowExists && internalWindow['HTMLElement']);
const zoneSymbolEventNames: {[eventName: string]: string} = {};
const wrapFn = function(this: unknown, event: Event) {
const wrapFn = function (this: unknown, event: Event) {
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
// event will be undefined, so we need to use window.event
event = event || _global.event;
@@ -143,10 +150,16 @@ const wrapFn = function(this: unknown, event: Event) {
// https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
// and onerror callback will prevent default when callback return true
const errorEvent: ErrorEvent = event as any;
result = listener &&
listener.call(
this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno,
errorEvent.error);
result =
listener &&
listener.call(
this,
errorEvent.message,
errorEvent.filename,
errorEvent.lineno,
errorEvent.colno,
errorEvent.error,
);
if (result === true) {
event.preventDefault();
}
@@ -198,7 +211,7 @@ export function patchProperty(obj: any, prop: string, prototype?: any) {
eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
}
desc.set = function(this: EventSource, newValue) {
desc.set = function (this: EventSource, newValue) {
// in some of windows's onproperty callback, this is undefined
// so we need to check it
let target = this;
@@ -225,7 +238,7 @@ export function patchProperty(obj: any, prop: string, prototype?: any) {
// The getter would return undefined for unassigned properties but the default value of an
// unassigned property is null
desc.get = function() {
desc.get = function () {
// in some of windows's onproperty callback, this is undefined
// so we need to check it
let target: any = this;
@@ -262,7 +275,7 @@ export function patchProperty(obj: any, prop: string, prototype?: any) {
obj[onPropPatchedSymbol] = true;
}
export function patchOnProperties(obj: any, properties: string[]|null, prototype?: any) {
export function patchOnProperties(obj: any, properties: string[] | null, prototype?: any) {
if (properties) {
for (let i = 0; i < properties.length; i++) {
patchProperty(obj, 'on' + properties[i], prototype);
@@ -289,7 +302,7 @@ export function patchClass(className: string) {
// keep original class in global
_global[zoneSymbol(className)] = OriginalClass;
_global[className] = function() {
_global[className] = function () {
const a = bindArguments(<any>arguments, className);
switch (a.length) {
case 0:
@@ -315,20 +328,20 @@ export function patchClass(className: string) {
// attach original delegate to patched function
attachOriginToPatched(_global[className], OriginalClass);
const instance = new OriginalClass(function() {});
const instance = new OriginalClass(function () {});
let prop;
for (prop in instance) {
// https://bugs.webkit.org/show_bug.cgi?id=44721
if (className === 'XMLHttpRequest' && prop === 'responseBlob') continue;
(function(prop) {
(function (prop) {
if (typeof instance[prop] === 'function') {
_global[className].prototype[prop] = function() {
_global[className].prototype[prop] = function () {
return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
};
} else {
ObjectDefineProperty(_global[className].prototype, prop, {
set: function(fn) {
set: function (fn) {
if (typeof fn === 'function') {
this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
// keep callback in wrapped function so we can
@@ -339,12 +352,12 @@ export function patchClass(className: string) {
this[originalInstanceKey][prop] = fn;
}
},
get: function() {
get: function () {
return this[originalInstanceKey][prop];
}
},
});
}
}(prop));
})(prop);
}
for (prop in OriginalClass) {
@@ -362,10 +375,10 @@ export function copySymbolProperties(src: any, dest: any) {
symbols.forEach((symbol: any) => {
const desc = Object.getOwnPropertyDescriptor(src, symbol);
Object.defineProperty(dest, symbol, {
get: function() {
get: function () {
return src[symbol];
},
set: function(value: any) {
set: function (value: any) {
if (desc && (!desc.writable || typeof desc.set !== 'function')) {
// if src[symbol] is not writable or not have a setter, just return
return;
@@ -373,7 +386,7 @@ export function copySymbolProperties(src: any, dest: any) {
src[symbol] = value;
},
enumerable: desc ? desc.enumerable : true,
configurable: desc ? desc.configurable : true
configurable: desc ? desc.configurable : true,
});
});
}
@@ -385,9 +398,14 @@ export function setShouldCopySymbolProperties(flag: boolean) {
}
export function patchMethod(
target: any, name: string,
patchFn: (delegate: Function, delegateName: string, name: string) => (self: any, args: any[]) =>
any): Function|null {
target: any,
name: string,
patchFn: (
delegate: Function,
delegateName: string,
name: string,
) => (self: any, args: any[]) => any,
): Function | null {
let proto = target;
while (proto && !proto.hasOwnProperty(name)) {
proto = ObjectGetPrototypeOf(proto);
@@ -398,7 +416,7 @@ export function patchMethod(
}
const delegateName = zoneSymbol(name);
let delegate: Function|null = null;
let delegate: Function | null = null;
if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
delegate = proto[delegateName] = proto[name];
// check whether proto[name] is writable
@@ -406,7 +424,7 @@ export function patchMethod(
const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
if (isPropertyWritable(desc)) {
const patchDelegate = patchFn(delegate!, delegateName, name);
proto[name] = function() {
proto[name] = function () {
return patchDelegate(this, arguments as any);
};
attachOriginToPatched(proto[name], delegate);
@@ -427,27 +445,35 @@ export interface MacroTaskMeta extends TaskData {
// TODO: @JiaLiPassion, support cancel task later if necessary
export function patchMacroTask(
obj: any, funcName: string, metaCreator: (self: any, args: any[]) => MacroTaskMeta) {
let setNative: Function|null = null;
obj: any,
funcName: string,
metaCreator: (self: any, args: any[]) => MacroTaskMeta,
) {
let setNative: Function | null = null;
function scheduleTask(task: Task) {
const data = <MacroTaskMeta>task.data;
data.args[data.cbIdx] = function() {
data.args[data.cbIdx] = function () {
task.invoke.apply(this, arguments);
};
setNative!.apply(data.target, data.args);
return task;
}
setNative = patchMethod(obj, funcName, (delegate: Function) => function(self: any, args: any[]) {
const meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
} else {
// cause an error by calling it directly.
return delegate.apply(self, args);
}
});
setNative = patchMethod(
obj,
funcName,
(delegate: Function) =>
function (self: any, args: any[]) {
const meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
} else {
// cause an error by calling it directly.
return delegate.apply(self, args);
}
},
);
}
export interface MicroTaskMeta extends TaskData {
@@ -458,27 +484,35 @@ export interface MicroTaskMeta extends TaskData {
}
export function patchMicroTask(
obj: any, funcName: string, metaCreator: (self: any, args: any[]) => MicroTaskMeta) {
let setNative: Function|null = null;
obj: any,
funcName: string,
metaCreator: (self: any, args: any[]) => MicroTaskMeta,
) {
let setNative: Function | null = null;
function scheduleTask(task: Task) {
const data = <MacroTaskMeta>task.data;
data.args[data.cbIdx] = function() {
data.args[data.cbIdx] = function () {
task.invoke.apply(this, arguments);
};
setNative!.apply(data.target, data.args);
return task;
}
setNative = patchMethod(obj, funcName, (delegate: Function) => function(self: any, args: any[]) {
const meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
} else {
// cause an error by calling it directly.
return delegate.apply(self, args);
}
});
setNative = patchMethod(
obj,
funcName,
(delegate: Function) =>
function (self: any, args: any[]) {
const meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
} else {
// cause an error by calling it directly.
return delegate.apply(self, args);
}
},
);
}
export function attachOriginToPatched(patched: Function, original: any) {
@@ -494,8 +528,7 @@ export function isIE() {
if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
return true;
}
} catch (error) {
}
} catch (error) {}
return false;
}
@@ -511,7 +544,6 @@ export function isIEOrEdge() {
if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
ieOrEdge = true;
}
} catch (error) {
}
} catch (error) {}
return ieOrEdge;
}
+28 -25
View File
@@ -19,34 +19,37 @@ export function patchBluebird(Zone: ZoneType): void {
(Zone as any)[Zone.__symbol__(BLUEBIRD)] = function patchBluebird(Bluebird: any) {
// patch method of Bluebird.prototype which not using `then` internally
const bluebirdApis: string[] = ['then', 'spread', 'finally'];
bluebirdApis.forEach(bapi => {
bluebirdApis.forEach((bapi) => {
api.patchMethod(
Bluebird.prototype, bapi, (delegate: Function) => (self: any, args: any[]) => {
const zone = Zone.current;
for (let i = 0; i < args.length; i++) {
const func = args[i];
if (typeof func === 'function') {
args[i] = function() {
const argSelf: any = this;
const argArgs: any = arguments;
return new Bluebird((res: any, rej: any) => {
zone.scheduleMicroTask('Promise.then', () => {
try {
res(func.apply(argSelf, argArgs));
} catch (error) {
rej(error);
}
});
Bluebird.prototype,
bapi,
(delegate: Function) => (self: any, args: any[]) => {
const zone = Zone.current;
for (let i = 0; i < args.length; i++) {
const func = args[i];
if (typeof func === 'function') {
args[i] = function () {
const argSelf: any = this;
const argArgs: any = arguments;
return new Bluebird((res: any, rej: any) => {
zone.scheduleMicroTask('Promise.then', () => {
try {
res(func.apply(argSelf, argArgs));
} catch (error) {
rej(error);
}
});
};
}
});
};
}
return delegate.apply(self, args);
});
}
return delegate.apply(self, args);
},
);
});
if (typeof window !== 'undefined') {
window.addEventListener('unhandledrejection', function(event: any) {
window.addEventListener('unhandledrejection', function (event: any) {
const error = event.detail && event.detail.reason;
if (error && error.isHandledByZone) {
event.preventDefault();
@@ -64,14 +67,14 @@ export function patchBluebird(Zone: ZoneType): void {
// will not be triggered.
process.removeAllListeners('unhandledRejection');
process.nextTick(() => {
listeners.forEach(listener => process.on('unhandledRejection', listener));
listeners.forEach((listener) => process.on('unhandledRejection', listener));
});
}
}
});
}
Bluebird.onPossiblyUnhandledRejection(function(e: any, promise: any) {
Bluebird.onPossiblyUnhandledRejection(function (e: any, promise: any) {
try {
Zone.current.runGuarded(() => {
e.isHandledByZone = true;
@@ -87,4 +90,4 @@ export function patchBluebird(Zone: ZoneType): void {
global.Promise = Bluebird;
};
});
}
}
+10 -6
View File
@@ -14,8 +14,11 @@ export function patchCordova(Zone: ZoneType): void {
const SUCCESS_SOURCE = 'cordova.exec.success';
const ERROR_SOURCE = 'cordova.exec.error';
const FUNCTION = 'function';
const nativeExec: Function|null =
api.patchMethod(global.cordova, 'exec', () => function(self: any, args: any[]) {
const nativeExec: Function | null = api.patchMethod(
global.cordova,
'exec',
() =>
function (self: any, args: any[]) {
if (args.length > 0 && typeof args[0] === FUNCTION) {
args[0] = Zone.current.wrap(args[0], SUCCESS_SOURCE);
}
@@ -23,7 +26,8 @@ export function patchCordova(Zone: ZoneType): void {
args[1] = Zone.current.wrap(args[1], ERROR_SOURCE);
}
return nativeExec!.apply(self, args);
});
},
);
}
});
@@ -31,13 +35,13 @@ export function patchCordova(Zone: ZoneType): void {
if (global.cordova && typeof global['FileReader'] !== 'undefined') {
document.addEventListener('deviceReady', () => {
const FileReader = global['FileReader'];
['abort', 'error', 'load', 'loadstart', 'loadend', 'progress'].forEach(prop => {
['abort', 'error', 'load', 'loadstart', 'loadend', 'progress'].forEach((prop) => {
const eventNameSymbol = Zone.__symbol__('ON_PROPERTY' + prop);
Object.defineProperty(FileReader.prototype, eventNameSymbol, {
configurable: true,
get: function() {
get: function () {
return this._realReader && this._realReader[eventNameSymbol];
}
},
});
});
});
+3 -4
View File
@@ -10,7 +10,7 @@ import {ZoneType} from '../zone-impl';
export function patchElectron(Zone: ZoneType): void {
Zone.__load_patch('electron', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
function patchArguments(target: any, name: string, source: string): Function|null {
function patchArguments(target: any, name: string, source: string): Function | null {
return api.patchMethod(target, name, (delegate: Function) => (self: any, args: any[]) => {
return delegate && delegate.apply(self, api.bindArguments(args, source));
});
@@ -22,9 +22,8 @@ export function patchElectron(Zone: ZoneType): void {
// since from electron 14+, the CallbacksRegistry is moved to @electron/remote
// package and not exported to outside, so this is a hack to patch CallbacksRegistry.
CallbacksRegistry =
require('@electron/remote/dist/src/renderer/callbacks-registry').CallbacksRegistry;
} catch (err) {
}
require('@electron/remote/dist/src/renderer/callbacks-registry').CallbacksRegistry;
} catch (err) {}
}
// patch api in renderer process directly
// desktopCapturer
+21 -13
View File
@@ -10,7 +10,7 @@ import {ZoneType} from '../zone-impl';
export function patchJsonp(Zone: ZoneType): void {
Zone.__load_patch('jsonp', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
const noop = function() {};
const noop = function () {};
// because jsonp is not a standard api, there are a lot of
// implementations, so zone.js just provide a helper util to
// patch the jsonp send and onSuccess/onError callback
@@ -23,9 +23,9 @@ export function patchJsonp(Zone: ZoneType): void {
if (!options || !options.jsonp || !options.sendFuncName) {
return;
}
const noop = function() {};
const noop = function () {};
[options.successFuncName, options.failedFuncName].forEach(methodName => {
[options.successFuncName, options.failedFuncName].forEach((methodName) => {
if (!methodName) {
return;
}
@@ -45,8 +45,8 @@ export function patchJsonp(Zone: ZoneType): void {
Object.defineProperty(global, methodName, {
configurable: true,
enumerable: true,
get: function() {
return function(this: unknown) {
get: function () {
return function (this: unknown) {
const task = global[api.symbol('jsonpTask')];
const target = this ? this : global;
const delegate = global[api.symbol(`jsonp${methodName}callback`)];
@@ -65,20 +65,28 @@ export function patchJsonp(Zone: ZoneType): void {
return null;
};
},
set: function(callback: Function) {
set: function (callback: Function) {
this[api.symbol(`jsonp${methodName}callback`)] = callback;
}
},
});
}
});
api.patchMethod(
options.jsonp, options.sendFuncName, (delegate: Function) => (self: any, args: any[]) => {
global[api.symbol('jsonpTask')] =
Zone.current.scheduleMacroTask('jsonp', noop, {}, (task: Task) => {
return delegate.apply(self, args);
}, noop);
});
options.jsonp,
options.sendFuncName,
(delegate: Function) => (self: any, args: any[]) => {
global[api.symbol('jsonpTask')] = Zone.current.scheduleMacroTask(
'jsonp',
noop,
{},
(task: Task) => {
return delegate.apply(self, args);
},
noop,
);
},
);
};
});
}
+5 -3
View File
@@ -18,12 +18,14 @@ export function patchSocketIo(Zone: ZoneType): void {
rt: true,
diff: (task: any, delegate: any) => {
return task.callback === delegate;
}
},
});
// also patch io.Socket.prototype.on/off/removeListener/removeAllListeners
io.Socket.prototype.on = io.Socket.prototype.addEventListener;
io.Socket.prototype.off = io.Socket.prototype.removeListener =
io.Socket.prototype.removeAllListeners = io.Socket.prototype.removeEventListener;
io.Socket.prototype.off =
io.Socket.prototype.removeListener =
io.Socket.prototype.removeAllListeners =
io.Socket.prototype.removeEventListener;
};
});
}
+81 -58
View File
@@ -10,19 +10,18 @@
import {ZoneType} from '../zone-impl';
'use strict';
('use strict');
declare let jest: any;
export function patchJasmine(Zone: ZoneType): void {
Zone.__load_patch('jasmine', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
const __extends = function(d: any, b: any) {
for (const p in b)
if (b.hasOwnProperty(p)) d[p] = b[p];
const __extends = function (d: any, b: any) {
for (const p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __(this: Object) {
this.constructor = d;
}
d.prototype =
b === null ? Object.create(b) : ((__.prototype = b.prototype), new (__ as any)());
b === null ? Object.create(b) : ((__.prototype = b.prototype), new (__ as any)());
};
// Patch jasmine's describe/it/beforeEach/afterEach functions so test code always runs
// in a testZone (ProxyZone). (See: angular/zone.js#91 & angular/angular#10503)
@@ -51,9 +50,10 @@ export function patchJasmine(Zone: ZoneType): void {
// the original variable name fakeAsyncPatchLock is not accurate, so the name will be
// fakeAsyncAutoFakeAsyncWhenClockPatched and if this enablePatchingJasmineClock is false, we
// also automatically disable the auto jump into fakeAsync feature
const enableAutoFakeAsyncWhenClockPatched = !disablePatchingJasmineClock &&
((global[symbol('fakeAsyncPatchLock')] === true) ||
(global[symbol('fakeAsyncAutoFakeAsyncWhenClockPatched')] === true));
const enableAutoFakeAsyncWhenClockPatched =
!disablePatchingJasmineClock &&
(global[symbol('fakeAsyncPatchLock')] === true ||
global[symbol('fakeAsyncAutoFakeAsyncWhenClockPatched')] === true);
const ignoreUnhandledRejection = global[symbol('ignoreUnhandledRejection')] === true;
@@ -61,12 +61,12 @@ export function patchJasmine(Zone: ZoneType): void {
const globalErrors = (jasmine as any).GlobalErrors;
if (globalErrors && !(jasmine as any)[symbol('GlobalErrors')]) {
(jasmine as any)[symbol('GlobalErrors')] = globalErrors;
(jasmine as any).GlobalErrors = function() {
(jasmine as any).GlobalErrors = function () {
const instance = new globalErrors();
const originalInstall = instance.install;
if (originalInstall && !instance[symbol('install')]) {
instance[symbol('install')] = originalInstall;
instance.install = function() {
instance.install = function () {
const isNode = typeof process !== 'undefined' && !!process.on;
// Note: Jasmine checks internally if `process` and `process.on` is defined.
// Otherwise, it installs the browser rejection handler through the
@@ -74,13 +74,15 @@ export function patchJasmine(Zone: ZoneType): void {
// `process` is not defined, and this will lead to a runtime exception since Webpack 5
// removed automatic Node.js polyfills. Note, that events are named differently, it's
// `unhandledRejection` in Node.js and `unhandledrejection` in the browser.
const originalHandlers: any[] = isNode ? process.listeners('unhandledRejection') :
global.eventListeners('unhandledrejection');
const originalHandlers: any[] = isNode
? process.listeners('unhandledRejection')
: global.eventListeners('unhandledrejection');
const result = originalInstall.apply(this, arguments);
isNode ? process.removeAllListeners('unhandledRejection') :
global.removeAllListeners('unhandledrejection');
isNode
? process.removeAllListeners('unhandledRejection')
: global.removeAllListeners('unhandledrejection');
if (originalHandlers) {
originalHandlers.forEach(handler => {
originalHandlers.forEach((handler) => {
if (isNode) {
process.on('unhandledRejection', handler);
} else {
@@ -98,26 +100,32 @@ export function patchJasmine(Zone: ZoneType): void {
// Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
const jasmineEnv: any = jasmine.getEnv();
['describe', 'xdescribe', 'fdescribe'].forEach(methodName => {
['describe', 'xdescribe', 'fdescribe'].forEach((methodName) => {
let originalJasmineFn: Function = jasmineEnv[methodName];
jasmineEnv[methodName] = function(description: string, specDefinitions: Function) {
jasmineEnv[methodName] = function (description: string, specDefinitions: Function) {
return originalJasmineFn.call(
this, description, wrapDescribeInZone(description, specDefinitions));
this,
description,
wrapDescribeInZone(description, specDefinitions),
);
};
});
['it', 'xit', 'fit'].forEach(methodName => {
['it', 'xit', 'fit'].forEach((methodName) => {
let originalJasmineFn: Function = jasmineEnv[methodName];
jasmineEnv[symbol(methodName)] = originalJasmineFn;
jasmineEnv[methodName] = function(
description: string, specDefinitions: Function, timeout: number) {
jasmineEnv[methodName] = function (
description: string,
specDefinitions: Function,
timeout: number,
) {
arguments[1] = wrapTestInZone(specDefinitions);
return originalJasmineFn.apply(this, arguments);
};
});
['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(methodName => {
['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach((methodName) => {
let originalJasmineFn: Function = jasmineEnv[methodName];
jasmineEnv[symbol(methodName)] = originalJasmineFn;
jasmineEnv[methodName] = function(specDefinitions: Function, timeout: number) {
jasmineEnv[methodName] = function (specDefinitions: Function, timeout: number) {
arguments[0] = wrapTestInZone(specDefinitions);
return originalJasmineFn.apply(this, arguments);
};
@@ -127,12 +135,12 @@ export function patchJasmine(Zone: ZoneType): void {
// need to patch jasmine.clock().mockDate and jasmine.clock().tick() so
// they can work properly in FakeAsyncTest
const originalClockFn: Function = ((jasmine as any)[symbol('clock')] = jasmine['clock']);
(jasmine as any)['clock'] = function() {
(jasmine as any)['clock'] = function () {
const clock = originalClockFn.apply(this, arguments);
if (!clock[symbol('patched')]) {
clock[symbol('patched')] = symbol('patched');
const originalTick = (clock[symbol('tick')] = clock.tick);
clock.tick = function() {
clock.tick = function () {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
return fakeAsyncZoneSpec.tick.apply(fakeAsyncZoneSpec, arguments);
@@ -140,22 +148,24 @@ export function patchJasmine(Zone: ZoneType): void {
return originalTick.apply(this, arguments);
};
const originalMockDate = (clock[symbol('mockDate')] = clock.mockDate);
clock.mockDate = function() {
clock.mockDate = function () {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
const dateTime = arguments.length > 0 ? arguments[0] : new Date();
return fakeAsyncZoneSpec.setFakeBaseSystemTime.apply(
fakeAsyncZoneSpec,
dateTime && typeof dateTime.getTime === 'function' ? [dateTime.getTime()] :
arguments);
fakeAsyncZoneSpec,
dateTime && typeof dateTime.getTime === 'function'
? [dateTime.getTime()]
: arguments,
);
}
return originalMockDate.apply(this, arguments);
};
// for auto go into fakeAsync feature, we need the flag to enable it
if (enableAutoFakeAsyncWhenClockPatched) {
['install', 'uninstall'].forEach(methodName => {
['install', 'uninstall'].forEach((methodName) => {
const originalClockFn: Function = (clock[symbol(methodName)] = clock[methodName]);
clock[methodName] = function() {
clock[methodName] = function () {
const FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec'];
if (FakeAsyncTestZoneSpec) {
(jasmine as any)[symbol('clockInstalled')] = 'install' === methodName;
@@ -174,15 +184,18 @@ export function patchJasmine(Zone: ZoneType): void {
if (!(jasmine as any)[Zone.__symbol__('createSpyObj')]) {
const originalCreateSpyObj = jasmine.createSpyObj;
(jasmine as any)[Zone.__symbol__('createSpyObj')] = originalCreateSpyObj;
jasmine.createSpyObj = function() {
jasmine.createSpyObj = function () {
const args: any = Array.prototype.slice.call(arguments);
const propertyNames = args.length >= 3 ? args[2] : null;
let spyObj: any;
if (propertyNames) {
const defineProperty = Object.defineProperty;
Object.defineProperty = function<T>(obj: T, p: PropertyKey, attributes: any) {
return defineProperty.call(
this, obj, p, {...attributes, configurable: true, enumerable: true}) as T;
Object.defineProperty = function <T>(obj: T, p: PropertyKey, attributes: any) {
return defineProperty.call(this, obj, p, {
...attributes,
configurable: true,
enumerable: true,
}) as T;
};
try {
spyObj = originalCreateSpyObj.apply(this, args);
@@ -201,16 +214,20 @@ export function patchJasmine(Zone: ZoneType): void {
* synchronous-only zone.
*/
function wrapDescribeInZone(description: string, describeBody: Function): Function {
return function(this: unknown) {
return function (this: unknown) {
// Create a synchronous-only zone in which to run `describe` blocks in order to raise an
// error if any asynchronous operations are attempted inside of a `describe`.
const syncZone = ambientZone.fork(new SyncTestZoneSpec(`jasmine.describe#${description}`));
return syncZone.run(describeBody, this, (arguments as any) as any[]);
return syncZone.run(describeBody, this, arguments as any as any[]);
};
}
function runInTestZone(
testBody: Function, applyThis: any, queueRunner: QueueRunner, done?: Function) {
testBody: Function,
applyThis: any,
queueRunner: QueueRunner,
done?: Function,
) {
const isClockInstalled = !!(jasmine as any)[symbol('clockInstalled')];
const testProxyZoneSpec = queueRunner.testProxyZoneSpec!;
const testProxyZone = queueRunner.testProxyZone!;
@@ -239,16 +256,20 @@ export function patchJasmine(Zone: ZoneType): void {
// Note we have to make a function with correct number of arguments, otherwise jasmine will
// think that all functions are sync or async.
return (
testBody && (testBody.length ? function(this: QueueRunnerUserContext, done: Function) {
return runInTestZone(testBody, this, this.queueRunner!, done);
} : function(this: QueueRunnerUserContext) {
return runInTestZone(testBody, this, this.queueRunner!);
}));
testBody &&
(testBody.length
? function (this: QueueRunnerUserContext, done: Function) {
return runInTestZone(testBody, this, this.queueRunner!, done);
}
: function (this: QueueRunnerUserContext) {
return runInTestZone(testBody, this, this.queueRunner!);
})
);
}
interface QueueRunner {
execute(): void;
testProxyZoneSpec: ZoneSpec|null;
testProxyZone: Zone|null;
testProxyZoneSpec: ZoneSpec | null;
testProxyZone: Zone | null;
}
interface QueueRunnerAttrs {
queueableFns: {fn: Function}[];
@@ -264,11 +285,11 @@ export function patchJasmine(Zone: ZoneType): void {
const QueueRunner = (jasmine as any).QueueRunner as {
new (attrs: QueueRunnerAttrs): QueueRunner;
};
(jasmine as any).QueueRunner = (function(_super) {
(jasmine as any).QueueRunner = (function (_super) {
__extends(ZoneQueueRunner, _super);
function ZoneQueueRunner(this: QueueRunner, attrs: QueueRunnerAttrs) {
if (attrs.onComplete) {
attrs.onComplete = (fn => () => {
attrs.onComplete = ((fn) => () => {
// All functions are done, clear the test zone.
this.testProxyZone = null;
this.testProxyZoneSpec = null;
@@ -282,7 +303,7 @@ export function patchJasmine(Zone: ZoneType): void {
// should run setTimeout inside jasmine outside of zone
attrs.timeout = {
setTimeout: nativeSetTimeout ? nativeSetTimeout : global.setTimeout,
clearTimeout: nativeClearTimeout ? nativeClearTimeout : global.clearTimeout
clearTimeout: nativeClearTimeout ? nativeClearTimeout : global.clearTimeout,
};
}
@@ -302,10 +323,12 @@ export function patchJasmine(Zone: ZoneType): void {
// patch attrs.onException
const onException = attrs.onException;
attrs.onException = function(this: undefined|QueueRunner, error: any) {
if (error &&
error.message ===
'Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.') {
attrs.onException = function (this: undefined | QueueRunner, error: any) {
if (
error &&
error.message ===
'Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.'
) {
// jasmine timeout, we can make the error message more
// reasonable to tell what tasks are pending
const proxyZoneSpec: any = this && this.testProxyZoneSpec;
@@ -314,8 +337,7 @@ export function patchJasmine(Zone: ZoneType): void {
try {
// try catch here in case error.message is not writable
error.message += pendingTasksInfo;
} catch (err) {
}
} catch (err) {}
}
}
if (onException) {
@@ -325,8 +347,8 @@ export function patchJasmine(Zone: ZoneType): void {
_super.call(this, attrs);
}
ZoneQueueRunner.prototype.execute = function() {
let zone: Zone|null = Zone.current;
ZoneQueueRunner.prototype.execute = function () {
let zone: Zone | null = Zone.current;
let isChildOfAmbientZone = false;
while (zone) {
if (zone === ambientZone) {
@@ -356,8 +378,9 @@ export function patchJasmine(Zone: ZoneType): void {
// addEventListener callback would think that it is the top most task and would
// drain the microtask queue on element.click() which would be incorrect.
// For this reason we always force a task when running jasmine tests.
Zone.current.scheduleMicroTask(
'jasmine.execute().forceTask', () => QueueRunner.prototype.execute.call(this));
Zone.current.scheduleMicroTask('jasmine.execute().forceTask', () =>
QueueRunner.prototype.execute.call(this),
);
} else {
_super.prototype.execute.call(this);
}
+60 -55
View File
@@ -8,7 +8,7 @@
import {ZoneType} from '../zone-impl';
'use strict';
('use strict');
declare let jest: any;
export function patchJest(Zone: ZoneType): void {
@@ -17,7 +17,6 @@ export function patchJest(Zone: ZoneType): void {
return;
}
// From jest 29 and jest-preset-angular v13, the module transform logic
// changed, and now jest-preset-angular use the use the tsconfig target
// other than the hardcoded one, https://github.com/thymikee/jest-preset-angular/issues/2010
@@ -42,9 +41,9 @@ export function patchJest(Zone: ZoneType): void {
const proxyZone = rootZone.fork(proxyZoneSpec);
function wrapDescribeFactoryInZone(originalJestFn: Function) {
return function(this: unknown, ...tableArgs: any[]) {
return function (this: unknown, ...tableArgs: any[]) {
const originalDescribeFn = originalJestFn.apply(this, tableArgs);
return function(this: unknown, ...args: any[]) {
return function (this: unknown, ...args: any[]) {
args[1] = wrapDescribeInZone(args[1]);
return originalDescribeFn.apply(this, args);
};
@@ -52,8 +51,8 @@ export function patchJest(Zone: ZoneType): void {
}
function wrapTestFactoryInZone(originalJestFn: Function) {
return function(this: unknown, ...tableArgs: any[]) {
return function(this: unknown, ...args: any[]) {
return function (this: unknown, ...tableArgs: any[]) {
return function (this: unknown, ...args: any[]) {
args[1] = wrapTestInZone(args[1]);
return originalJestFn.apply(this, tableArgs).apply(this, args);
};
@@ -65,7 +64,7 @@ export function patchJest(Zone: ZoneType): void {
* synchronous-only zone.
*/
function wrapDescribeInZone(describeBody: Function): Function {
return function(this: unknown, ...args: any[]) {
return function (this: unknown, ...args: any[]) {
return syncZone.run(describeBody, this, args);
};
}
@@ -79,9 +78,12 @@ export function patchJest(Zone: ZoneType): void {
if (typeof testBody !== 'function') {
return testBody;
}
const wrappedFunc = function() {
if ((Zone as any)[api.symbol('useFakeTimersCalled')] === true && testBody &&
!(testBody as any).isFakeAsync) {
const wrappedFunc = function () {
if (
(Zone as any)[api.symbol('useFakeTimersCalled')] === true &&
testBody &&
!(testBody as any).isFakeAsync
) {
// jest.useFakeTimers is called, run into fakeAsyncTest automatically.
const fakeAsyncModule = (Zone as any)[Zone.__symbol__('fakeAsyncTest')];
if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
@@ -93,19 +95,22 @@ export function patchJest(Zone: ZoneType): void {
};
// Update the length of wrappedFunc to be the same as the length of the testBody
// So jest core can handle whether the test function has `done()` or not correctly
Object.defineProperty(
wrappedFunc, 'length', {configurable: true, writable: true, enumerable: false});
Object.defineProperty(wrappedFunc, 'length', {
configurable: true,
writable: true,
enumerable: false,
});
wrappedFunc.length = testBody.length;
return wrappedFunc;
}
['describe', 'xdescribe', 'fdescribe'].forEach(methodName => {
['describe', 'xdescribe', 'fdescribe'].forEach((methodName) => {
let originalJestFn: Function = context[methodName];
if (context[Zone.__symbol__(methodName)]) {
return;
}
context[Zone.__symbol__(methodName)] = originalJestFn;
context[methodName] = function(this: unknown, ...args: any[]) {
context[methodName] = function (this: unknown, ...args: any[]) {
args[1] = wrapDescribeInZone(args[1]);
return originalJestFn.apply(this, args);
};
@@ -114,13 +119,13 @@ export function patchJest(Zone: ZoneType): void {
context.describe.only = context.fdescribe;
context.describe.skip = context.xdescribe;
['it', 'xit', 'fit', 'test', 'xtest'].forEach(methodName => {
['it', 'xit', 'fit', 'test', 'xtest'].forEach((methodName) => {
let originalJestFn: Function = context[methodName];
if (context[Zone.__symbol__(methodName)]) {
return;
}
context[Zone.__symbol__(methodName)] = originalJestFn;
context[methodName] = function(this: unknown, ...args: any[]) {
context[methodName] = function (this: unknown, ...args: any[]) {
args[1] = wrapTestInZone(args[1], true);
return originalJestFn.apply(this, args);
};
@@ -133,13 +138,13 @@ export function patchJest(Zone: ZoneType): void {
context.test.only = context.fit;
context.test.skip = context.xit;
['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(methodName => {
['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach((methodName) => {
let originalJestFn: Function = context[methodName];
if (context[Zone.__symbol__(methodName)]) {
return;
}
context[Zone.__symbol__(methodName)] = originalJestFn;
context[methodName] = function(this: unknown, ...args: any[]) {
context[methodName] = function (this: unknown, ...args: any[]) {
args[0] = wrapTestInZone(args[0]);
return originalJestFn.apply(this, args);
};
@@ -165,145 +170,145 @@ export function patchJest(Zone: ZoneType): void {
Timer[api.symbol('fakeTimers')] = true;
// patch jest fakeTimer internal method to make sure no console.warn print out
api.patchMethod(Timer, '_checkFakeTimers', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, '_checkFakeTimers', (delegate) => {
return function (self: any, args: any[]) {
if (isPatchingFakeTimer()) {
return true;
} else {
return delegate.apply(self, args);
}
}
};
});
// patch useFakeTimers(), set useFakeTimersCalled flag, and make test auto run into fakeAsync
api.patchMethod(Timer, 'useFakeTimers', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'useFakeTimers', (delegate) => {
return function (self: any, args: any[]) {
(Zone as any)[api.symbol('useFakeTimersCalled')] = true;
if (isModern || isInTestFunc()) {
return delegate.apply(self, args);
}
return self;
}
};
});
// patch useRealTimers(), unset useFakeTimers flag
api.patchMethod(Timer, 'useRealTimers', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'useRealTimers', (delegate) => {
return function (self: any, args: any[]) {
(Zone as any)[api.symbol('useFakeTimersCalled')] = false;
if (isModern || isInTestFunc()) {
return delegate.apply(self, args);
}
return self;
}
};
});
// patch setSystemTime(), call setCurrentRealTime() in the fakeAsyncTest
api.patchMethod(Timer, 'setSystemTime', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'setSystemTime', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
fakeAsyncZoneSpec.setFakeBaseSystemTime(args[0]);
} else {
return delegate.apply(self, args);
}
}
};
});
// patch getSystemTime(), call getCurrentRealTime() in the fakeAsyncTest
api.patchMethod(Timer, 'getRealSystemTime', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'getRealSystemTime', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
return fakeAsyncZoneSpec.getRealSystemTime();
} else {
return delegate.apply(self, args);
}
}
};
});
// patch runAllTicks(), run all microTasks inside fakeAsync
api.patchMethod(Timer, 'runAllTicks', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'runAllTicks', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.flushMicrotasks();
} else {
return delegate.apply(self, args);
}
}
};
});
// patch runAllTimers(), run all macroTasks inside fakeAsync
api.patchMethod(Timer, 'runAllTimers', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'runAllTimers', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.flush(100, true);
} else {
return delegate.apply(self, args);
}
}
};
});
// patch advanceTimersByTime(), call tick() in the fakeAsyncTest
api.patchMethod(Timer, 'advanceTimersByTime', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'advanceTimersByTime', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.tick(args[0]);
} else {
return delegate.apply(self, args);
}
}
};
});
// patch runOnlyPendingTimers(), call flushOnlyPendingTimers() in the fakeAsyncTest
api.patchMethod(Timer, 'runOnlyPendingTimers', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'runOnlyPendingTimers', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.flushOnlyPendingTimers();
} else {
return delegate.apply(self, args);
}
}
};
});
// patch advanceTimersToNextTimer(), call tickToNext() in the fakeAsyncTest
api.patchMethod(Timer, 'advanceTimersToNextTimer', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'advanceTimersToNextTimer', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.tickToNext(args[0]);
} else {
return delegate.apply(self, args);
}
}
};
});
// patch clearAllTimers(), call removeAllTimers() in the fakeAsyncTest
api.patchMethod(Timer, 'clearAllTimers', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'clearAllTimers', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.removeAllTimers();
} else {
return delegate.apply(self, args);
}
}
};
});
// patch getTimerCount(), call getTimerCount() in the fakeAsyncTest
api.patchMethod(Timer, 'getTimerCount', delegate => {
return function(self: any, args: any[]) {
api.patchMethod(Timer, 'getTimerCount', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
return fakeAsyncZoneSpec.getTimerCount();
} else {
return delegate.apply(self, args);
}
}
};
});
}
};
});
}
+43 -35
View File
@@ -8,7 +8,7 @@
import {ZoneType} from '../zone-impl';
'use strict';
('use strict');
export function patchMocha(Zone: ZoneType): void {
Zone.__load_patch('mocha', (global: any, Zone: ZoneType) => {
@@ -39,7 +39,7 @@ export function patchMocha(Zone: ZoneType): void {
const rootZone = Zone.current;
const syncZone = rootZone.fork(new SyncTestZoneSpec('Mocha.describe'));
let testZone: Zone|null = null;
let testZone: Zone | null = null;
const suiteZone = rootZone.fork(new ProxyZoneSpec());
const mochaOriginal = {
@@ -48,7 +48,7 @@ export function patchMocha(Zone: ZoneType): void {
before: global.before,
beforeEach: global.beforeEach,
describe: global.describe,
it: global.it
it: global.it,
};
function modifyArguments(args: IArguments, syncTest: Function, asyncTest?: Function): any[] {
@@ -60,10 +60,10 @@ export function patchMocha(Zone: ZoneType): void {
// Note we have to make a function with correct number of arguments,
// otherwise mocha will
// think that all functions are sync or async.
args[i] = (arg.length === 0) ? syncTest(arg) : asyncTest!(arg);
args[i] = arg.length === 0 ? syncTest(arg) : asyncTest!(arg);
// Mocha uses toString to view the test body in the result list, make sure we return the
// correct function body
args[i].toString = function() {
args[i].toString = function () {
return arg.toString();
};
}
@@ -73,8 +73,8 @@ export function patchMocha(Zone: ZoneType): void {
}
function wrapDescribeInZone(args: IArguments): any[] {
const syncTest: any = function(fn: Function) {
return function(this: unknown) {
const syncTest: any = function (fn: Function) {
return function (this: unknown) {
return syncZone.run(fn, this, arguments as any as any[]);
};
};
@@ -83,14 +83,14 @@ export function patchMocha(Zone: ZoneType): void {
}
function wrapTestInZone(args: IArguments): any[] {
const asyncTest = function(fn: Function) {
return function(this: unknown, done: Function) {
const asyncTest = function (fn: Function) {
return function (this: unknown, done: Function) {
return testZone!.run(fn, this, [done]);
};
};
const syncTest: any = function(fn: Function) {
return function(this: unknown) {
const syncTest: any = function (fn: Function) {
return function (this: unknown) {
return testZone!.run(fn, this);
};
};
@@ -99,14 +99,14 @@ export function patchMocha(Zone: ZoneType): void {
}
function wrapSuiteInZone(args: IArguments): any[] {
const asyncTest = function(fn: Function) {
return function(this: unknown, done: Function) {
const asyncTest = function (fn: Function) {
return function (this: unknown, done: Function) {
return suiteZone.run(fn, this, [done]);
};
};
const syncTest: any = function(fn: Function) {
return function(this: unknown) {
const syncTest: any = function (fn: Function) {
return function (this: unknown) {
return suiteZone.run(fn, this);
};
};
@@ -114,54 +114,63 @@ export function patchMocha(Zone: ZoneType): void {
return modifyArguments(args, syncTest, asyncTest);
}
global.describe = global.suite = function() {
global.describe = global.suite = function () {
return mochaOriginal.describe.apply(this, wrapDescribeInZone(arguments));
};
global.xdescribe = global.suite.skip = global.describe.skip = function() {
return mochaOriginal.describe.skip.apply(this, wrapDescribeInZone(arguments));
};
global.xdescribe =
global.suite.skip =
global.describe.skip =
function () {
return mochaOriginal.describe.skip.apply(this, wrapDescribeInZone(arguments));
};
global.describe.only = global.suite.only = function() {
global.describe.only = global.suite.only = function () {
return mochaOriginal.describe.only.apply(this, wrapDescribeInZone(arguments));
};
global.it = global.specify = global.test = function() {
return mochaOriginal.it.apply(this, wrapTestInZone(arguments));
};
global.it =
global.specify =
global.test =
function () {
return mochaOriginal.it.apply(this, wrapTestInZone(arguments));
};
global.xit = global.xspecify = global.it.skip = function() {
return mochaOriginal.it.skip.apply(this, wrapTestInZone(arguments));
};
global.xit =
global.xspecify =
global.it.skip =
function () {
return mochaOriginal.it.skip.apply(this, wrapTestInZone(arguments));
};
global.it.only = global.test.only = function() {
global.it.only = global.test.only = function () {
return mochaOriginal.it.only.apply(this, wrapTestInZone(arguments));
};
global.after = global.suiteTeardown = function() {
global.after = global.suiteTeardown = function () {
return mochaOriginal.after.apply(this, wrapSuiteInZone(arguments));
};
global.afterEach = global.teardown = function() {
global.afterEach = global.teardown = function () {
return mochaOriginal.afterEach.apply(this, wrapTestInZone(arguments));
};
global.before = global.suiteSetup = function() {
global.before = global.suiteSetup = function () {
return mochaOriginal.before.apply(this, wrapSuiteInZone(arguments));
};
global.beforeEach = global.setup = function() {
global.beforeEach = global.setup = function () {
return mochaOriginal.beforeEach.apply(this, wrapTestInZone(arguments));
};
((originalRunTest, originalRun) => {
Mocha.Runner.prototype.runTest = function(fn: Function) {
Mocha.Runner.prototype.runTest = function (fn: Function) {
Zone.current.scheduleMicroTask('mocha.forceTask', () => {
originalRunTest.call(this, fn);
});
};
Mocha.Runner.prototype.run = function(fn: Function) {
Mocha.Runner.prototype.run = function (fn: Function) {
this.on('test', (e: any) => {
testZone = rootZone.fork(new ProxyZoneSpec());
});
@@ -172,8 +181,7 @@ export function patchMocha(Zone: ZoneType): void {
try {
// try catch here in case err.message is not writable
err.message += proxyZoneSpec.getAndClearPendingTasksInfo();
} catch (error) {
}
} catch (error) {}
}
});
+4 -5
View File
@@ -20,12 +20,12 @@ export function patchEvents(Zone: ZoneType): void {
const EE_ON = 'on';
const EE_OFF = 'off';
const compareTaskCallbackVsDelegate = function(task: any, delegate: any) {
const compareTaskCallbackVsDelegate = function (task: any, delegate: any) {
// same callback, same capture, same event name, just return
return task.callback === delegate || task.callback.listener === delegate;
};
const eventNameToString = function(eventName: string|Symbol) {
const eventNameToString = function (eventName: string | Symbol) {
if (typeof eventName === 'string') {
return eventName;
}
@@ -46,7 +46,7 @@ export function patchEvents(Zone: ZoneType): void {
chkDup: false,
rt: true,
diff: compareTaskCallbackVsDelegate,
eventNameToString: eventNameToString
eventNameToString: eventNameToString,
});
if (result && result[0]) {
obj[EE_ON] = obj[EE_ADD_LISTENER];
@@ -58,8 +58,7 @@ export function patchEvents(Zone: ZoneType): void {
let events;
try {
events = require('events');
} catch (err) {
}
} catch (err) {}
if (events && events.EventEmitter) {
patchEventEmitterMethods(events.EventEmitter.prototype);
+52 -23
View File
@@ -14,32 +14,61 @@ export function patchFs(Zone: ZoneType): void {
let fs: any;
try {
fs = require('fs');
} catch (err) {
}
} catch (err) {}
if (!fs) return;
// watch, watchFile, unwatchFile has been patched
// because EventEmitter has been patched
const TO_PATCH_MACROTASK_METHODS = [
'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod',
'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod',
'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read',
'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat',
'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile',
'access',
'appendFile',
'chmod',
'chown',
'close',
'exists',
'fchmod',
'fchown',
'fdatasync',
'fstat',
'fsync',
'ftruncate',
'futimes',
'lchmod',
'lchown',
'link',
'lstat',
'mkdir',
'mkdtemp',
'open',
'read',
'readdir',
'readFile',
'readlink',
'realpath',
'rename',
'rmdir',
'stat',
'symlink',
'truncate',
'unlink',
'utimes',
'write',
'writeFile',
];
TO_PATCH_MACROTASK_METHODS.filter(name => !!fs[name] && typeof fs[name] === 'function')
.forEach(name => {
patchMacroTask(fs, name, (self: any, args: any[]) => {
return {
name: 'fs.' + name,
args: args,
cbIdx: args.length > 0 ? args.length - 1 : -1,
target: self
};
});
});
TO_PATCH_MACROTASK_METHODS.filter(
(name) => !!fs[name] && typeof fs[name] === 'function',
).forEach((name) => {
patchMacroTask(fs, name, (self: any, args: any[]) => {
return {
name: 'fs.' + name,
args: args,
cbIdx: args.length > 0 ? args.length - 1 : -1,
target: self,
};
});
});
const realpathOriginalDelegate = fs.realpath?.[api.symbol('OriginalDelegate')];
// This is the only specific method that should be additionally patched because the previous
@@ -47,11 +76,11 @@ export function patchFs(Zone: ZoneType): void {
if (realpathOriginalDelegate?.native) {
fs.realpath.native = realpathOriginalDelegate.native;
patchMacroTask(fs.realpath, 'native', (self, args) => ({
args,
target: self,
cbIdx: args.length > 0 ? args.length - 1 : -1,
name: 'fs.realpath.native',
}));
args,
target: self,
cbIdx: args.length > 0 ? args.length - 1 : -1,
name: 'fs.realpath.native',
}));
}
});
}
+1 -1
View File
@@ -16,7 +16,7 @@ import {patchNode} from './node';
export function rollupMain(): ZoneType {
const Zone = loadZone();
patchNode(Zone); // Node needs to come first.
patchNode(Zone); // Node needs to come first.
patchPromise(Zone);
patchToString(Zone);
+44 -36
View File
@@ -37,7 +37,7 @@ export function patchNode(Zone: ZoneType): void {
// 2. if global.setTimeout not equal timers.setTimeout, check
// whether global.setTimeout use timers.setTimeout or not
const originSetTimeout = timers.setTimeout;
timers.setTimeout = function() {
timers.setTimeout = function () {
globalUseTimeoutFromTimer = true;
return originSetTimeout.apply(this, arguments);
};
@@ -84,58 +84,57 @@ export function patchNode(Zone: ZoneType): void {
return {
name: 'process.nextTick',
args: args,
cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1,
target: process
cbIdx: args.length > 0 && typeof args[0] === 'function' ? 0 : -1,
target: process,
};
});
});
Zone.__load_patch(
'handleUnhandledPromiseRejection', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
(Zone as any)[api.symbol('unhandledPromiseRejectionHandler')] =
findProcessPromiseRejectionHandler('unhandledRejection');
'handleUnhandledPromiseRejection',
(global: any, Zone: ZoneType, api: _ZonePrivate) => {
(Zone as any)[api.symbol('unhandledPromiseRejectionHandler')] =
findProcessPromiseRejectionHandler('unhandledRejection');
(Zone as any)[api.symbol('rejectionHandledHandler')] =
findProcessPromiseRejectionHandler('rejectionHandled');
// handle unhandled promise rejection
function findProcessPromiseRejectionHandler(evtName: string) {
return function(e: any) {
const eventTasks = findEventTasks(process, evtName);
eventTasks.forEach(eventTask => {
// process has added unhandledrejection event listener
// trigger the event listener
if (evtName === 'unhandledRejection') {
eventTask.invoke(e.rejection, e.promise);
} else if (evtName === 'rejectionHandled') {
eventTask.invoke(e.promise);
}
});
};
}
});
(Zone as any)[api.symbol('rejectionHandledHandler')] =
findProcessPromiseRejectionHandler('rejectionHandled');
// handle unhandled promise rejection
function findProcessPromiseRejectionHandler(evtName: string) {
return function (e: any) {
const eventTasks = findEventTasks(process, evtName);
eventTasks.forEach((eventTask) => {
// process has added unhandledrejection event listener
// trigger the event listener
if (evtName === 'unhandledRejection') {
eventTask.invoke(e.rejection, e.promise);
} else if (evtName === 'rejectionHandled') {
eventTask.invoke(e.promise);
}
});
};
}
},
);
// Crypto
Zone.__load_patch('crypto', () => {
let crypto: any;
try {
crypto = require('crypto');
} catch (err) {
}
} catch (err) {}
// use the generic patchMacroTask to patch crypto
if (crypto) {
const methodNames = ['randomBytes', 'pbkdf2'];
methodNames.forEach(name => {
methodNames.forEach((name) => {
patchMacroTask(crypto, name, (self: any, args: any[]) => {
return {
name: 'crypto.' + name,
args: args,
cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ?
args.length - 1 :
-1,
target: crypto
cbIdx:
args.length > 0 && typeof args[args.length - 1] === 'function' ? args.length - 1 : -1,
target: crypto,
};
});
});
@@ -143,12 +142,21 @@ export function patchNode(Zone: ZoneType): void {
});
Zone.__load_patch('console', (global: any, Zone: ZoneType) => {
const consoleMethods =
['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace'];
const consoleMethods = [
'dir',
'log',
'info',
'error',
'warn',
'assert',
'debug',
'timeEnd',
'trace',
];
consoleMethods.forEach((m: string) => {
const originalMethod = (console as any)[Zone.__symbol__(m)] = (console as any)[m];
const originalMethod = ((console as any)[Zone.__symbol__(m)] = (console as any)[m]);
if (originalMethod) {
(console as any)[m] = function() {
(console as any)[m] = function () {
const args = ArraySlice.call(arguments);
if (Zone.current === Zone.root) {
return originalMethod.apply(this, args);
+7 -1
View File
@@ -6,7 +6,13 @@
* found in the LICENSE file at https://angular.io/license
*/
import {bindArguments, patchMacroTask, patchMethod, patchOnProperties, setShouldCopySymbolProperties} from '../common/utils';
import {
bindArguments,
patchMacroTask,
patchMethod,
patchOnProperties,
setShouldCopySymbolProperties,
} from '../common/utils';
import {ZoneType} from '../zone-impl';
export function patchNodeUtil(Zone: ZoneType): void {
+39 -37
View File
@@ -11,8 +11,8 @@ import {Observable, Subscriber, Subscription} from 'rxjs';
import {ZoneType} from '../zone-impl';
type ZoneSubscriberContext = {
_zone: Zone
}&Subscriber<any>;
_zone: Zone;
} & Subscriber<any>;
export function patchRxJs(Zone: ZoneType): void {
(Zone as any).__load_patch('rxjs', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
@@ -23,10 +23,10 @@ export function patchRxJs(Zone: ZoneType): void {
const ObjectDefineProperties = Object.defineProperties;
const patchObservable = function() {
const patchObservable = function () {
const ObservablePrototype: any = Observable.prototype;
const _symbolSubscribe = symbol('_subscribe');
const _subscribe = ObservablePrototype[_symbolSubscribe] = ObservablePrototype._subscribe;
const _subscribe = (ObservablePrototype[_symbolSubscribe] = ObservablePrototype._subscribe);
ObjectDefineProperties(Observable.prototype, {
_zone: {value: null, writable: true, configurable: true},
@@ -34,17 +34,17 @@ export function patchRxJs(Zone: ZoneType): void {
_zoneSubscribe: {value: null, writable: true, configurable: true},
source: {
configurable: true,
get: function(this: Observable<any>) {
get: function (this: Observable<any>) {
return (this as any)._zoneSource;
},
set: function(this: Observable<any>, source: any) {
set: function (this: Observable<any>, source: any) {
(this as any)._zone = Zone.current;
(this as any)._zoneSource = source;
}
},
},
_subscribe: {
configurable: true,
get: function(this: Observable<any>) {
get: function (this: Observable<any>) {
if ((this as any)._zoneSubscribe) {
return (this as any)._zoneSubscribe;
} else if (this.constructor === Observable) {
@@ -53,17 +53,17 @@ export function patchRxJs(Zone: ZoneType): void {
const proto = Object.getPrototypeOf(this);
return proto && proto._subscribe;
},
set: function(this: Observable<any>, subscribe: any) {
set: function (this: Observable<any>, subscribe: any) {
(this as any)._zone = Zone.current;
if (!subscribe) {
(this as any)._zoneSubscribe = subscribe;
} else {
(this as any)._zoneSubscribe = function(this: ZoneSubscriberContext) {
(this as any)._zoneSubscribe = function (this: ZoneSubscriberContext) {
if (this._zone && this._zone !== Zone.current) {
const tearDown = this._zone.run(subscribe, this, arguments as any);
if (typeof tearDown === 'function') {
const zone = this._zone;
return function(this: ZoneSubscriberContext) {
return function (this: ZoneSubscriberContext) {
if (zone !== Zone.current) {
return zone.run(tearDown, this, arguments as any);
}
@@ -77,22 +77,22 @@ export function patchRxJs(Zone: ZoneType): void {
}
};
}
}
},
},
subjectFactory: {
get: function() {
get: function () {
return (this as any)._zoneSubjectFactory;
},
set: function(factory: any) {
set: function (factory: any) {
const zone = this._zone;
this._zoneSubjectFactory = function() {
this._zoneSubjectFactory = function () {
if (zone && zone !== Zone.current) {
return zone.run(factory, this, arguments);
}
return factory.apply(this, arguments);
};
}
}
},
},
});
};
@@ -101,30 +101,32 @@ export function patchRxJs(Zone: ZoneType): void {
if (observable.operator) {
observable.operator._zone = Zone.current;
api.patchMethod(
observable.operator, 'call',
(operatorDelegate: any) => (operatorSelf: any, operatorArgs: any[]) => {
if (operatorSelf._zone && operatorSelf._zone !== Zone.current) {
return operatorSelf._zone.run(operatorDelegate, operatorSelf, operatorArgs);
}
return operatorDelegate.apply(operatorSelf, operatorArgs);
});
observable.operator,
'call',
(operatorDelegate: any) => (operatorSelf: any, operatorArgs: any[]) => {
if (operatorSelf._zone && operatorSelf._zone !== Zone.current) {
return operatorSelf._zone.run(operatorDelegate, operatorSelf, operatorArgs);
}
return operatorDelegate.apply(operatorSelf, operatorArgs);
},
);
}
return observable;
});
const patchSubscription = function() {
const patchSubscription = function () {
ObjectDefineProperties(Subscription.prototype, {
_zone: {value: null, writable: true, configurable: true},
_zoneUnsubscribe: {value: null, writable: true, configurable: true},
_unsubscribe: {
get: function(this: Subscription) {
get: function (this: Subscription) {
if ((this as any)._zoneUnsubscribe || (this as any)._zoneUnsubscribeCleared) {
return (this as any)._zoneUnsubscribe;
}
const proto = Object.getPrototypeOf(this);
return proto && proto._unsubscribe;
},
set: function(this: Subscription, unsubscribe: any) {
set: function (this: Subscription, unsubscribe: any) {
(this as any)._zone = Zone.current;
if (!unsubscribe) {
(this as any)._zoneUnsubscribe = unsubscribe;
@@ -135,7 +137,7 @@ export function patchRxJs(Zone: ZoneType): void {
(this as any)._zoneUnsubscribeCleared = true;
} else {
(this as any)._zoneUnsubscribeCleared = false;
(this as any)._zoneUnsubscribe = function() {
(this as any)._zoneUnsubscribe = function () {
if (this._zone && this._zone !== Zone.current) {
return this._zone.run(unsubscribe, this, arguments);
} else {
@@ -143,30 +145,30 @@ export function patchRxJs(Zone: ZoneType): void {
}
};
}
}
}
},
},
});
};
const patchSubscriber = function() {
const patchSubscriber = function () {
const next = Subscriber.prototype.next;
const error = Subscriber.prototype.error;
const complete = Subscriber.prototype.complete;
Object.defineProperty(Subscriber.prototype, 'destination', {
configurable: true,
get: function(this: Subscriber<any>) {
get: function (this: Subscriber<any>) {
return (this as any)._zoneDestination;
},
set: function(this: Subscriber<any>, destination: any) {
set: function (this: Subscriber<any>, destination: any) {
(this as any)._zone = Zone.current;
(this as any)._zoneDestination = destination;
}
},
});
// patch Subscriber.next to make sure it run
// into SubscriptionZone
Subscriber.prototype.next = function(this: ZoneSubscriberContext) {
Subscriber.prototype.next = function (this: ZoneSubscriberContext) {
const currentZone = Zone.current;
const subscriptionZone = this._zone;
@@ -179,7 +181,7 @@ export function patchRxJs(Zone: ZoneType): void {
}
};
Subscriber.prototype.error = function(this: ZoneSubscriberContext) {
Subscriber.prototype.error = function (this: ZoneSubscriberContext) {
const currentZone = Zone.current;
const subscriptionZone = this._zone;
@@ -192,7 +194,7 @@ export function patchRxJs(Zone: ZoneType): void {
}
};
Subscriber.prototype.complete = function(this: ZoneSubscriberContext) {
Subscriber.prototype.complete = function (this: ZoneSubscriberContext) {
const currentZone = Zone.current;
const subscriptionZone = this._zone;
@@ -46,7 +46,7 @@ export function patchPromiseTesting(Zone: ZoneType): void {
return;
}
oriThen = (Promise as any)[Zone.__symbol__('ZonePromiseThen')] = Promise.prototype.then;
Promise.prototype.then = function() {
Promise.prototype.then = function () {
const chained = oriThen.apply(this, arguments);
if ((this as any)[symbolState] === UNRESOLVED) {
// parent promise is unresolved.
@@ -69,4 +69,4 @@ export function patchPromiseTesting(Zone: ZoneType): void {
}
};
});
}
}
+374 -202
View File
@@ -138,7 +138,7 @@ export declare interface Zone {
*
* @returns {Zone} The parent Zone.
*/
parent: Zone|null;
parent: Zone | null;
/**
* @returns {string} The Zone name (useful for debugging)
*/
@@ -163,7 +163,7 @@ export declare interface Zone {
* @param key The key to use for identification of the returned zone.
* @returns {Zone} The Zone which defines the `key`, `null` if not found.
*/
getZoneWith(key: string): Zone|null;
getZoneWith(key: string): Zone | null;
/**
* Used to create a child zone.
@@ -237,8 +237,11 @@ export declare interface Zone {
* @param customSchedule
*/
scheduleMicroTask(
source: string, callback: Function, data?: TaskData,
customSchedule?: (task: Task) => void): MicroTask;
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
): MicroTask;
/**
* Schedule a MacroTask.
@@ -250,8 +253,12 @@ export declare interface Zone {
* @param customCancel
*/
scheduleMacroTask(
source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void): MacroTask;
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void,
): MacroTask;
/**
* Schedule an EventTask.
@@ -263,8 +270,12 @@ export declare interface Zone {
* @param customCancel
*/
scheduleEventTask(
source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void): EventTask;
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void,
): EventTask;
/**
* Schedule an existing Task.
@@ -298,7 +309,7 @@ export declare interface ZoneType {
/**
* @returns {Task} The task associated with the current execution.
*/
currentTask: Task|null;
currentTask: Task | null;
/**
* Verify that Zone has been correctly patched. Specifically that Promise is zone aware.
@@ -339,21 +350,32 @@ export declare interface ZonePrivate {
microtaskDrainDone: () => void;
showUncaughtError: () => boolean;
patchEventTarget: (global: any, api: ZonePrivate, apis: any[], options?: any) => boolean[];
patchOnProperties: (obj: any, properties: string[]|null, prototype?: any) => void;
patchOnProperties: (obj: any, properties: string[] | null, prototype?: any) => void;
patchThen: (ctro: Function) => void;
patchMethod:
(target: any, name: string,
patchFn: (delegate: Function, delegateName: string, name: string) =>
(self: any, args: any[]) => any) => Function | null;
patchMethod: (
target: any,
name: string,
patchFn: (
delegate: Function,
delegateName: string,
name: string,
) => (self: any, args: any[]) => any,
) => Function | null;
bindArguments: (args: any[], source: string) => any[];
patchMacroTask:
(obj: any, funcName: string, metaCreator: (self: any, args: any[]) => any) => void;
patchMacroTask: (
obj: any,
funcName: string,
metaCreator: (self: any, args: any[]) => any,
) => void;
patchEventPrototype: (_global: any, api: ZonePrivate) => void;
isIEOrEdge: () => boolean;
ObjectDefineProperty:
(o: any, p: PropertyKey, attributes: PropertyDescriptor&ThisType<any>) => any;
ObjectDefineProperty: (
o: any,
p: PropertyKey,
attributes: PropertyDescriptor & ThisType<any>,
) => any;
ObjectGetOwnPropertyDescriptor: (o: any, p: PropertyKey) => PropertyDescriptor | undefined;
ObjectCreate(o: object|null, properties?: PropertyDescriptorMap&ThisType<any>): any;
ObjectCreate(o: object | null, properties?: PropertyDescriptorMap & ThisType<any>): any;
ArraySlice(start?: number, end?: number): any[];
patchClass: (className: string) => void;
wrapWithCurrentZone: (callback: any, source: string) => any;
@@ -361,22 +383,35 @@ export declare interface ZonePrivate {
attachOriginToPatched: (target: any, origin: any) => void;
_redefineProperty: (target: any, callback: string, desc: any) => void;
nativeScheduleMicroTask: (func: Function) => void;
patchCallbacks:
(api: ZonePrivate, target: any, targetName: string, method: string,
callbacks: string[]) => void;
getGlobalObjects: () => {
globalSources: any, zoneSymbolEventNames: any, eventNames: string[], isBrowser: boolean,
isMix: boolean, isNode: boolean, TRUE_STR: string, FALSE_STR: string,
ZONE_SYMBOL_PREFIX: string, ADD_EVENT_LISTENER_STR: string,
REMOVE_EVENT_LISTENER_STR: string
} | undefined;
patchCallbacks: (
api: ZonePrivate,
target: any,
targetName: string,
method: string,
callbacks: string[],
) => void;
getGlobalObjects: () =>
| {
globalSources: any;
zoneSymbolEventNames: any;
eventNames: string[];
isBrowser: boolean;
isMix: boolean;
isNode: boolean;
TRUE_STR: string;
FALSE_STR: string;
ZONE_SYMBOL_PREFIX: string;
ADD_EVENT_LISTENER_STR: string;
REMOVE_EVENT_LISTENER_STR: string;
}
| undefined;
}
/**
* ZoneFrame represents zone stack frame information
*/
export declare interface ZoneFrame {
parent: ZoneFrame|null;
parent: ZoneFrame | null;
zone: Zone;
}
@@ -414,9 +449,12 @@ export declare interface ZoneSpec {
* @param targetZone The [Zone] which originally received the request.
* @param zoneSpec The argument passed into the `fork` method.
*/
onFork?:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
zoneSpec: ZoneSpec) => Zone;
onFork?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
zoneSpec: ZoneSpec,
) => Zone;
/**
* Allows interception of the wrapping of the callback.
@@ -427,9 +465,13 @@ export declare interface ZoneSpec {
* @param delegate The argument passed into the `wrap` method.
* @param source The argument passed into the `wrap` method.
*/
onIntercept?:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
source: string) => Function;
onIntercept?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
source: string,
) => Function;
/**
* Allows interception of the callback invocation.
@@ -442,9 +484,15 @@ export declare interface ZoneSpec {
* @param applyArgs The argument passed into the `run` method.
* @param source The argument passed into the `run` method.
*/
onInvoke?:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
applyThis: any, applyArgs?: any[], source?: string) => any;
onInvoke?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
applyThis: any,
applyArgs?: any[],
source?: string,
) => any;
/**
* Allows interception of the error handling.
@@ -454,9 +502,12 @@ export declare interface ZoneSpec {
* @param targetZone The [Zone] which originally received the request.
* @param error The argument passed into the `handleError` method.
*/
onHandleError?:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
error: any) => boolean;
onHandleError?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
) => boolean;
/**
* Allows interception of task scheduling.
@@ -466,12 +517,21 @@ export declare interface ZoneSpec {
* @param targetZone The [Zone] which originally received the request.
* @param task The argument passed into the `scheduleTask` method.
*/
onScheduleTask?:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) => Task;
onScheduleTask?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
) => Task;
onInvokeTask?:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
applyThis: any, applyArgs?: any[]) => any;
onInvokeTask?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
applyThis: any,
applyArgs?: any[],
) => any;
/**
* Allows interception of task cancellation.
@@ -481,8 +541,12 @@ export declare interface ZoneSpec {
* @param targetZone The [Zone] which originally received the request.
* @param task The argument passed into the `cancelTask` method.
*/
onCancelTask?:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) => any;
onCancelTask?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
) => any;
/**
* Notifies of changes to the task queue empty status.
@@ -492,12 +556,14 @@ export declare interface ZoneSpec {
* @param targetZone The [Zone] which originally received the request.
* @param hasTaskState
*/
onHasTask?:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
hasTaskState: HasTaskState) => void;
onHasTask?: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
hasTaskState: HasTaskState,
) => void;
}
/**
* A delegate when intercepting zone operations.
*
@@ -533,8 +599,13 @@ export declare interface ZoneDelegate {
zone: Zone;
fork(targetZone: Zone, zoneSpec: ZoneSpec): Zone;
intercept(targetZone: Zone, callback: Function, source: string): Function;
invoke(targetZone: Zone, callback: Function, applyThis?: any, applyArgs?: any[], source?: string):
any;
invoke(
targetZone: Zone,
callback: Function,
applyThis?: any,
applyArgs?: any[],
source?: string,
): any;
handleError(targetZone: Zone, error: any): boolean;
scheduleTask(targetZone: Zone, task: Task): Task;
invokeTask(targetZone: Zone, task: Task, applyThis?: any, applyArgs?: any[]): any;
@@ -543,19 +614,27 @@ export declare interface ZoneDelegate {
}
export type HasTaskState = {
microTask: boolean; macroTask: boolean; eventTask: boolean; change: TaskType;
microTask: boolean;
macroTask: boolean;
eventTask: boolean;
change: TaskType;
};
/**
* Task type: `microTask`, `macroTask`, `eventTask`.
*/
export type TaskType = 'microTask'|'macroTask'|'eventTask';
export type TaskType = 'microTask' | 'macroTask' | 'eventTask';
/**
* Task type: `notScheduled`, `scheduling`, `scheduled`, `running`, `canceling`, 'unknown'.
*/
export type TaskState = 'notScheduled'|'scheduling'|'scheduled'|'running'|'canceling'|'unknown';
export type TaskState =
| 'notScheduled'
| 'scheduling'
| 'scheduled'
| 'running'
| 'canceling'
| 'unknown';
/**
*/
@@ -684,8 +763,8 @@ export function __symbol__(name: string) {
}
export function initZone(): ZoneType {
const performance: {mark(name: string): void; measure(name: string, label: string): void;} =
global['performance'];
const performance: {mark(name: string): void; measure(name: string, label: string): void} =
global['performance'];
function mark(name: string) {
performance && performance['mark'] && performance['mark'](name);
}
@@ -701,11 +780,12 @@ export function initZone(): ZoneType {
static assertZonePatched() {
if (global['Promise'] !== patches['ZoneAwarePromise']) {
throw new Error(
'Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
'Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
'has been overwritten.\n' +
'Most likely cause is that a Promise polyfill has been loaded ' +
'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
'If you must load one, do so before loading zone.js.)');
'If you must load one, do so before loading zone.js.)',
);
}
}
@@ -721,7 +801,7 @@ export function initZone(): ZoneType {
return _currentZoneFrame.zone;
}
static get currentTask(): Task|null {
static get currentTask(): Task | null {
return _currentTask;
}
@@ -743,7 +823,7 @@ export function initZone(): ZoneType {
}
}
public get parent(): AmbientZone|null {
public get parent(): AmbientZone | null {
return this._parent;
}
@@ -751,18 +831,20 @@ export function initZone(): ZoneType {
return this._name;
}
private _parent: ZoneImpl|null;
private _parent: ZoneImpl | null;
private _name: string;
private _properties: {[key: string]: any};
private _zoneDelegate: _ZoneDelegate;
constructor(parent: ZoneImpl|null, zoneSpec: ZoneSpec|null) {
constructor(parent: ZoneImpl | null, zoneSpec: ZoneSpec | null) {
this._parent = parent as ZoneImpl;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
this._properties = zoneSpec && zoneSpec.properties || {};
this._zoneDelegate =
new _ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
this._properties = (zoneSpec && zoneSpec.properties) || {};
this._zoneDelegate = new _ZoneDelegate(
this,
this._parent && this._parent._zoneDelegate,
zoneSpec,
);
}
public get(key: string): any {
@@ -770,8 +852,8 @@ export function initZone(): ZoneType {
if (zone) return zone._properties[key];
}
public getZoneWith(key: string): AmbientZone|null {
let current: ZoneImpl|null = this;
public getZoneWith(key: string): AmbientZone | null {
let current: ZoneImpl | null = this;
while (current) {
if (current._properties.hasOwnProperty(key)) {
return current;
@@ -792,14 +874,18 @@ export function initZone(): ZoneType {
}
const _callback = this._zoneDelegate.intercept(this, callback, source);
const zone: ZoneImpl = this;
return function(this: unknown) {
return function (this: unknown) {
return zone.runGuarded(_callback, this, <any>arguments, source);
} as any as T;
}
public run(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;
public run<T>(
callback: (...args: any[]) => T, applyThis?: any, applyArgs?: any[], source?: string): T {
callback: (...args: any[]) => T,
applyThis?: any,
applyArgs?: any[],
source?: string,
): T {
_currentZoneFrame = {parent: _currentZoneFrame, zone: this};
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
@@ -810,8 +896,11 @@ export function initZone(): ZoneType {
public runGuarded(callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;
public runGuarded<T>(
callback: (...args: any[]) => T, applyThis: any = null, applyArgs?: any[],
source?: string) {
callback: (...args: any[]) => T,
applyThis: any = null,
applyArgs?: any[],
source?: string,
) {
_currentZoneFrame = {parent: _currentZoneFrame, zone: this};
try {
try {
@@ -826,12 +915,15 @@ export function initZone(): ZoneType {
}
}
runTask(task: Task, applyThis?: any, applyArgs?: any): any {
if (task.zone != this) {
throw new Error(
'A task can only be run in the zone of creation! (Creation: ' +
(task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
'A task can only be run in the zone of creation! (Creation: ' +
(task.zone || NO_ZONE).name +
'; Execution: ' +
this.name +
')',
);
}
// https://github.com/angular/zone.js/issues/778, sometimes eventTask
// will run in notScheduled(canceled) state, we should not try to
@@ -868,7 +960,7 @@ export function initZone(): ZoneType {
task.runCount = 0;
this._updateTaskCount(task as ZoneTask<any>, -1);
reEntryGuard &&
(task as ZoneTask<any>)._transitionTo(notScheduled, running, notScheduled);
(task as ZoneTask<any>)._transitionTo(notScheduled, running, notScheduled);
}
}
_currentZoneFrame = _currentZoneFrame.parent!;
@@ -883,8 +975,9 @@ export function initZone(): ZoneType {
let newZone: any = this;
while (newZone) {
if (newZone === task.zone) {
throw Error(`can not reschedule task to ${
this.name} which is descendants of the original zone ${task.zone.name}`);
throw Error(
`can not reschedule task to ${this.name} which is descendants of the original zone ${task.zone.name}`,
);
}
newZone = newZone.parent;
}
@@ -914,31 +1007,49 @@ export function initZone(): ZoneType {
}
scheduleMicroTask(
source: string, callback: Function, data?: TaskData,
customSchedule?: (task: Task) => void): MicroTask {
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
): MicroTask {
return this.scheduleTask(
new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
new ZoneTask(microTask, source, callback, data, customSchedule, undefined),
);
}
scheduleMacroTask(
source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void): MacroTask {
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void,
): MacroTask {
return this.scheduleTask(
new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel),
);
}
scheduleEventTask(
source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void): EventTask {
source: string,
callback: Function,
data?: TaskData,
customSchedule?: (task: Task) => void,
customCancel?: (task: Task) => void,
): EventTask {
return this.scheduleTask(
new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel),
);
}
cancelTask(task: Task): any {
if (task.zone != this)
throw new Error(
'A task can only be cancelled in the zone of creation! (Creation: ' +
(task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
'A task can only be cancelled in the zone of creation! (Creation: ' +
(task.zone || NO_ZONE).name +
'; Execution: ' +
this.name +
')',
);
if (task.state !== scheduled && task.state !== running) {
return;
@@ -972,16 +1083,28 @@ export function initZone(): ZoneType {
const DELEGATE_ZS: ZoneSpec = {
name: '',
onHasTask:
(delegate: ZoneDelegate, _: AmbientZone, target: AmbientZone, hasTaskState: HasTaskState):
void => delegate.hasTask(target, hasTaskState),
onScheduleTask: (delegate: ZoneDelegate, _: AmbientZone, target: AmbientZone, task: Task):
Task => delegate.scheduleTask(target, task),
onInvokeTask:
(delegate: ZoneDelegate, _: AmbientZone, target: AmbientZone, task: Task, applyThis: any,
applyArgs: any): any => delegate.invokeTask(target, task, applyThis, applyArgs),
onHasTask: (
delegate: ZoneDelegate,
_: AmbientZone,
target: AmbientZone,
hasTaskState: HasTaskState,
): void => delegate.hasTask(target, hasTaskState),
onScheduleTask: (
delegate: ZoneDelegate,
_: AmbientZone,
target: AmbientZone,
task: Task,
): Task => delegate.scheduleTask(target, task),
onInvokeTask: (
delegate: ZoneDelegate,
_: AmbientZone,
target: AmbientZone,
task: Task,
applyThis: any,
applyArgs: any,
): any => delegate.invokeTask(target, task, applyThis, applyArgs),
onCancelTask: (delegate: ZoneDelegate, _: AmbientZone, target: AmbientZone, task: Task): any =>
delegate.cancelTask(target, task)
delegate.cancelTask(target, task),
};
class _ZoneDelegate implements ZoneDelegate {
@@ -990,95 +1113,96 @@ export function initZone(): ZoneType {
}
private _zone: ZoneImpl;
private _taskCounts:
{microTask: number,
macroTask: number,
eventTask: number} = {'microTask': 0, 'macroTask': 0, 'eventTask': 0};
private _taskCounts: {microTask: number; macroTask: number; eventTask: number} = {
'microTask': 0,
'macroTask': 0,
'eventTask': 0,
};
private _parentDelegate: _ZoneDelegate|null;
private _parentDelegate: _ZoneDelegate | null;
private _forkDlgt: _ZoneDelegate|null;
private _forkZS: ZoneSpec|null;
private _forkCurrZone: Zone|null;
private _forkDlgt: _ZoneDelegate | null;
private _forkZS: ZoneSpec | null;
private _forkCurrZone: Zone | null;
private _interceptDlgt: _ZoneDelegate|null;
private _interceptZS: ZoneSpec|null;
private _interceptCurrZone: Zone|null;
private _interceptDlgt: _ZoneDelegate | null;
private _interceptZS: ZoneSpec | null;
private _interceptCurrZone: Zone | null;
private _invokeDlgt: _ZoneDelegate|null;
private _invokeZS: ZoneSpec|null;
private _invokeCurrZone: ZoneImpl|null;
private _invokeDlgt: _ZoneDelegate | null;
private _invokeZS: ZoneSpec | null;
private _invokeCurrZone: ZoneImpl | null;
private _handleErrorDlgt: _ZoneDelegate|null;
private _handleErrorZS: ZoneSpec|null;
private _handleErrorCurrZone: ZoneImpl|null;
private _handleErrorDlgt: _ZoneDelegate | null;
private _handleErrorZS: ZoneSpec | null;
private _handleErrorCurrZone: ZoneImpl | null;
private _scheduleTaskDlgt: _ZoneDelegate|null;
private _scheduleTaskZS: ZoneSpec|null;
private _scheduleTaskCurrZone: ZoneImpl|null;
private _scheduleTaskDlgt: _ZoneDelegate | null;
private _scheduleTaskZS: ZoneSpec | null;
private _scheduleTaskCurrZone: ZoneImpl | null;
private _invokeTaskDlgt: _ZoneDelegate|null;
private _invokeTaskZS: ZoneSpec|null;
private _invokeTaskCurrZone: ZoneImpl|null;
private _invokeTaskDlgt: _ZoneDelegate | null;
private _invokeTaskZS: ZoneSpec | null;
private _invokeTaskCurrZone: ZoneImpl | null;
private _cancelTaskDlgt: _ZoneDelegate|null;
private _cancelTaskZS: ZoneSpec|null;
private _cancelTaskCurrZone: ZoneImpl|null;
private _cancelTaskDlgt: _ZoneDelegate | null;
private _cancelTaskZS: ZoneSpec | null;
private _cancelTaskCurrZone: ZoneImpl | null;
private _hasTaskDlgt: _ZoneDelegate|null;
private _hasTaskDlgtOwner: _ZoneDelegate|null;
private _hasTaskZS: ZoneSpec|null;
private _hasTaskCurrZone: ZoneImpl|null;
private _hasTaskDlgt: _ZoneDelegate | null;
private _hasTaskDlgtOwner: _ZoneDelegate | null;
private _hasTaskZS: ZoneSpec | null;
private _hasTaskCurrZone: ZoneImpl | null;
constructor(zone: Zone, parentDelegate: _ZoneDelegate|null, zoneSpec: ZoneSpec|null) {
constructor(zone: Zone, parentDelegate: _ZoneDelegate | null, zoneSpec: ZoneSpec | null) {
this._zone = zone as ZoneImpl;
this._parentDelegate = parentDelegate;
this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate!._forkZS);
this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate!._forkDlgt);
this._forkCurrZone =
zoneSpec && (zoneSpec.onFork ? this._zone : parentDelegate!._forkCurrZone);
zoneSpec && (zoneSpec.onFork ? this._zone : parentDelegate!._forkCurrZone);
this._interceptZS =
zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate!._interceptZS);
zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate!._interceptZS);
this._interceptDlgt =
zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate!._interceptDlgt);
zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate!._interceptDlgt);
this._interceptCurrZone =
zoneSpec && (zoneSpec.onIntercept ? this._zone : parentDelegate!._interceptCurrZone);
zoneSpec && (zoneSpec.onIntercept ? this._zone : parentDelegate!._interceptCurrZone);
this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate!._invokeZS);
this._invokeDlgt =
zoneSpec && (zoneSpec.onInvoke ? parentDelegate! : parentDelegate!._invokeDlgt);
zoneSpec && (zoneSpec.onInvoke ? parentDelegate! : parentDelegate!._invokeDlgt);
this._invokeCurrZone =
zoneSpec && (zoneSpec.onInvoke ? this._zone : parentDelegate!._invokeCurrZone);
zoneSpec && (zoneSpec.onInvoke ? this._zone : parentDelegate!._invokeCurrZone);
this._handleErrorZS =
zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate!._handleErrorZS);
zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate!._handleErrorZS);
this._handleErrorDlgt =
zoneSpec && (zoneSpec.onHandleError ? parentDelegate! : parentDelegate!._handleErrorDlgt);
zoneSpec && (zoneSpec.onHandleError ? parentDelegate! : parentDelegate!._handleErrorDlgt);
this._handleErrorCurrZone =
zoneSpec && (zoneSpec.onHandleError ? this._zone : parentDelegate!._handleErrorCurrZone);
zoneSpec && (zoneSpec.onHandleError ? this._zone : parentDelegate!._handleErrorCurrZone);
this._scheduleTaskZS =
zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate!._scheduleTaskZS);
this._scheduleTaskDlgt = zoneSpec &&
(zoneSpec.onScheduleTask ? parentDelegate! : parentDelegate!._scheduleTaskDlgt);
this._scheduleTaskCurrZone = zoneSpec &&
(zoneSpec.onScheduleTask ? this._zone : parentDelegate!._scheduleTaskCurrZone);
zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate!._scheduleTaskZS);
this._scheduleTaskDlgt =
zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate! : parentDelegate!._scheduleTaskDlgt);
this._scheduleTaskCurrZone =
zoneSpec && (zoneSpec.onScheduleTask ? this._zone : parentDelegate!._scheduleTaskCurrZone);
this._invokeTaskZS =
zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate!._invokeTaskZS);
zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate!._invokeTaskZS);
this._invokeTaskDlgt =
zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate! : parentDelegate!._invokeTaskDlgt);
zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate! : parentDelegate!._invokeTaskDlgt);
this._invokeTaskCurrZone =
zoneSpec && (zoneSpec.onInvokeTask ? this._zone : parentDelegate!._invokeTaskCurrZone);
zoneSpec && (zoneSpec.onInvokeTask ? this._zone : parentDelegate!._invokeTaskCurrZone);
this._cancelTaskZS =
zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate!._cancelTaskZS);
zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate!._cancelTaskZS);
this._cancelTaskDlgt =
zoneSpec && (zoneSpec.onCancelTask ? parentDelegate! : parentDelegate!._cancelTaskDlgt);
zoneSpec && (zoneSpec.onCancelTask ? parentDelegate! : parentDelegate!._cancelTaskDlgt);
this._cancelTaskCurrZone =
zoneSpec && (zoneSpec.onCancelTask ? this._zone : parentDelegate!._cancelTaskCurrZone);
zoneSpec && (zoneSpec.onCancelTask ? this._zone : parentDelegate!._cancelTaskCurrZone);
this._hasTaskZS = null;
this._hasTaskDlgt = null;
@@ -1113,31 +1237,52 @@ export function initZone(): ZoneType {
}
fork(targetZone: ZoneImpl, zoneSpec: ZoneSpec): AmbientZone {
return this._forkZS ? this._forkZS.onFork!(this._forkDlgt!, this.zone, targetZone, zoneSpec) :
new ZoneImpl(targetZone, zoneSpec);
return this._forkZS
? this._forkZS.onFork!(this._forkDlgt!, this.zone, targetZone, zoneSpec)
: new ZoneImpl(targetZone, zoneSpec);
}
intercept(targetZone: ZoneImpl, callback: Function, source: string): Function {
return this._interceptZS ?
this._interceptZS.onIntercept!
(this._interceptDlgt!, this._interceptCurrZone!, targetZone, callback, source) :
callback;
return this._interceptZS
? this._interceptZS.onIntercept!(
this._interceptDlgt!,
this._interceptCurrZone!,
targetZone,
callback,
source,
)
: callback;
}
invoke(
targetZone: ZoneImpl, callback: Function, applyThis: any, applyArgs?: any[],
source?: string): any {
return this._invokeZS ? this._invokeZS.onInvoke!
(this._invokeDlgt!, this._invokeCurrZone!, targetZone, callback,
applyThis, applyArgs, source) :
callback.apply(applyThis, applyArgs);
targetZone: ZoneImpl,
callback: Function,
applyThis: any,
applyArgs?: any[],
source?: string,
): any {
return this._invokeZS
? this._invokeZS.onInvoke!(
this._invokeDlgt!,
this._invokeCurrZone!,
targetZone,
callback,
applyThis,
applyArgs,
source,
)
: callback.apply(applyThis, applyArgs);
}
handleError(targetZone: ZoneImpl, error: any): boolean {
return this._handleErrorZS ?
this._handleErrorZS.onHandleError!
(this._handleErrorDlgt!, this._handleErrorCurrZone!, targetZone, error) :
true;
return this._handleErrorZS
? this._handleErrorZS.onHandleError!(
this._handleErrorDlgt!,
this._handleErrorCurrZone!,
targetZone,
error,
)
: true;
}
scheduleTask(targetZone: ZoneImpl, task: Task): Task {
@@ -1147,8 +1292,12 @@ export function initZone(): ZoneType {
returnTask._zoneDelegates!.push(this._hasTaskDlgtOwner!);
}
// clang-format off
returnTask = this._scheduleTaskZS.onScheduleTask !(
this._scheduleTaskDlgt !, this._scheduleTaskCurrZone !, targetZone, task) as ZoneTask<any>;
returnTask = this._scheduleTaskZS.onScheduleTask!(
this._scheduleTaskDlgt!,
this._scheduleTaskCurrZone!,
targetZone,
task,
) as ZoneTask<any>;
// clang-format on
if (!returnTask) returnTask = task as ZoneTask<any>;
} else {
@@ -1164,17 +1313,27 @@ export function initZone(): ZoneType {
}
invokeTask(targetZone: ZoneImpl, task: Task, applyThis: any, applyArgs?: any[]): any {
return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask!
(this._invokeTaskDlgt!, this._invokeTaskCurrZone!, targetZone,
task, applyThis, applyArgs) :
task.callback.apply(applyThis, applyArgs);
return this._invokeTaskZS
? this._invokeTaskZS.onInvokeTask!(
this._invokeTaskDlgt!,
this._invokeTaskCurrZone!,
targetZone,
task,
applyThis,
applyArgs,
)
: task.callback.apply(applyThis, applyArgs);
}
cancelTask(targetZone: ZoneImpl, task: Task): any {
let value: any;
if (this._cancelTaskZS) {
value = this._cancelTaskZS.onCancelTask!
(this._cancelTaskDlgt!, this._cancelTaskCurrZone!, targetZone, task);
value = this._cancelTaskZS.onCancelTask!(
this._cancelTaskDlgt!,
this._cancelTaskCurrZone!,
targetZone,
task,
);
} else {
if (!task.cancelFn) {
throw Error('Task is not cancelable');
@@ -1189,8 +1348,12 @@ export function initZone(): ZoneType {
// can still trigger hasTask callback
try {
this._hasTaskZS &&
this._hasTaskZS.onHasTask!
(this._hasTaskDlgt!, this._hasTaskCurrZone!, targetZone, isEmpty);
this._hasTaskZS.onHasTask!(
this._hasTaskDlgt!,
this._hasTaskCurrZone!,
targetZone,
isEmpty,
);
} catch (err) {
this.handleError(targetZone, err);
}
@@ -1200,7 +1363,7 @@ export function initZone(): ZoneType {
_updateTaskCount(type: TaskType, count: number) {
const counts = this._taskCounts;
const prev = counts[type];
const next = counts[type] = prev + count;
const next = (counts[type] = prev + count);
if (next < 0) {
throw new Error('More tasks executed then were scheduled.');
}
@@ -1209,7 +1372,7 @@ export function initZone(): ZoneType {
microTask: counts['microTask'] > 0,
macroTask: counts['macroTask'] > 0,
eventTask: counts['eventTask'] > 0,
change: type
change: type,
};
this.hasTask(this._zone, isEmpty);
}
@@ -1221,20 +1384,25 @@ export function initZone(): ZoneType {
public source: string;
public invoke: Function;
public callback: Function;
public data: TaskData|undefined;
public scheduleFn: ((task: Task) => void)|undefined;
public cancelFn: ((task: Task) => void)|undefined;
public data: TaskData | undefined;
public scheduleFn: ((task: Task) => void) | undefined;
public cancelFn: ((task: Task) => void) | undefined;
// tslint:disable-next-line:require-internal-with-underscore
_zone: ZoneImpl|null = null;
_zone: ZoneImpl | null = null;
public runCount: number = 0;
// tslint:disable-next-line:require-internal-with-underscore
_zoneDelegates: _ZoneDelegate[]|null = null;
_zoneDelegates: _ZoneDelegate[] | null = null;
// tslint:disable-next-line:require-internal-with-underscore
_state: TaskState = 'notScheduled';
constructor(
type: T, source: string, callback: Function, options: TaskData|undefined,
scheduleFn: ((task: Task) => void)|undefined, cancelFn: ((task: Task) => void)|undefined) {
type: T,
source: string,
callback: Function,
options: TaskData | undefined,
scheduleFn: ((task: Task) => void) | undefined,
cancelFn: ((task: Task) => void) | undefined,
) {
this.type = type;
this.source = source;
this.data = options;
@@ -1249,7 +1417,7 @@ export function initZone(): ZoneType {
if (type === eventTask && options && (options as any).useG) {
this.invoke = ZoneTask.invokeTask;
} else {
this.invoke = function() {
this.invoke = function () {
return ZoneTask.invokeTask.call(global, self, this, <any>arguments);
};
}
@@ -1291,9 +1459,11 @@ export function initZone(): ZoneType {
this._zoneDelegates = null;
}
} else {
throw new Error(`${this.type} '${this.source}': can not transition to '${
toState}', expecting state '${fromState1}'${
fromState2 ? ' or \'' + fromState2 + '\'' : ''}, was '${this._state}'.`);
throw new Error(
`${this.type} '${this.source}': can not transition to '${toState}', expecting state '${fromState1}'${
fromState2 ? " or '" + fromState2 + "'" : ''
}, was '${this._state}'.`,
);
}
}
@@ -1313,12 +1483,11 @@ export function initZone(): ZoneType {
state: this.state,
source: this.source,
zone: this.zone.name,
runCount: this.runCount
runCount: this.runCount,
};
}
}
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
/// MICROTASK QUEUE
@@ -1386,13 +1555,16 @@ export function initZone(): ZoneType {
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
const NO_ZONE = {name: 'NO ZONE'};
const notScheduled: 'notScheduled' = 'notScheduled', scheduling: 'scheduling' = 'scheduling',
scheduled: 'scheduled' = 'scheduled', running: 'running' = 'running',
canceling: 'canceling' = 'canceling', unknown: 'unknown' = 'unknown';
const microTask: 'microTask' = 'microTask', macroTask: 'macroTask' = 'macroTask',
eventTask: 'eventTask' = 'eventTask';
const notScheduled: 'notScheduled' = 'notScheduled',
scheduling: 'scheduling' = 'scheduling',
scheduled: 'scheduled' = 'scheduled',
running: 'running' = 'running',
canceling: 'canceling' = 'canceling',
unknown: 'unknown' = 'unknown';
const microTask: 'microTask' = 'microTask',
macroTask: 'macroTask' = 'macroTask',
eventTask: 'eventTask' = 'eventTask';
const patches: {[key: string]: any} = {};
const _api: ZonePrivate = {
@@ -1421,10 +1593,10 @@ export function initZone(): ZoneType {
attachOriginToPatched: () => noop,
_redefineProperty: () => noop,
patchCallbacks: () => noop,
nativeScheduleMicroTask: nativeScheduleMicroTask
nativeScheduleMicroTask: nativeScheduleMicroTask,
};
let _currentZoneFrame: ZoneFrame = {parent: null, zone: new ZoneImpl(null, null)};
let _currentTask: Task|null = null;
let _currentTask: Task | null = null;
let _numberOfNestedTaskFrames = 0;
function noop() {}
+78 -48
View File
@@ -9,7 +9,7 @@
import {__symbol__, ZoneType} from '../zone-impl';
const __global: any =
typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global;
(typeof window !== 'undefined' && window) || (typeof self !== 'undefined' && self) || global;
class AsyncTestZoneSpec implements ZoneSpec {
// Needs to be a getter and not a plain property in order run this just-in-time. Otherwise
// `__symbol__` would be evaluated during top-level execution prior to the Zone prefix being
@@ -22,20 +22,23 @@ class AsyncTestZoneSpec implements ZoneSpec {
_pendingMacroTasks: boolean = false;
_alreadyErrored: boolean = false;
_isSync: boolean = false;
_existingFinishTimer: ReturnType<typeof setTimeout>|null = null;
_existingFinishTimer: ReturnType<typeof setTimeout> | null = null;
entryFunction: Function|null = null;
entryFunction: Function | null = null;
runZone = Zone.current;
unresolvedChainedPromiseCount = 0;
supportWaitUnresolvedChainedPromise = false;
constructor(
private finishCallback: Function, private failCallback: Function, namePrefix: string) {
private finishCallback: Function,
private failCallback: Function,
namePrefix: string,
) {
this.name = 'asyncTestZone for ' + namePrefix;
this.properties = {'AsyncTestZoneSpec': this};
this.supportWaitUnresolvedChainedPromise =
__global[__symbol__('supportWaitUnResolvedChainedPromise')] === true;
__global[__symbol__('supportWaitUnResolvedChainedPromise')] === true;
}
isUnresolvedChainedPromisePending() {
@@ -62,8 +65,13 @@ class AsyncTestZoneSpec implements ZoneSpec {
this._existingFinishTimer = null;
}
if (!(this._pendingMicroTasks || this._pendingMacroTasks ||
(this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending()))) {
if (
!(
this._pendingMicroTasks ||
this._pendingMacroTasks ||
(this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending())
)
) {
// We wait until the next tick because we would like to catch unhandled promises which could
// cause test logic to be executed. In such cases we cannot finish with tasks pending then.
this.runZone.run(() => {
@@ -117,8 +125,13 @@ class AsyncTestZoneSpec implements ZoneSpec {
}
onInvokeTask(
delegate: ZoneDelegate, current: Zone, target: Zone, task: Task, applyThis: any,
applyArgs: any) {
delegate: ZoneDelegate,
current: Zone,
target: Zone,
task: Task,
applyThis: any,
applyArgs: any,
) {
if (task.type !== 'eventTask') {
this._isSync = false;
}
@@ -138,8 +151,14 @@ class AsyncTestZoneSpec implements ZoneSpec {
// updated by(JiaLiPassion), only call finish callback when no task
// was scheduled/invoked/canceled.
onInvoke(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
applyThis: any, applyArgs?: any[], source?: string): any {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
applyThis: any,
applyArgs?: any[],
source?: string,
): any {
if (!this.entryFunction) {
this.entryFunction = delegate;
}
@@ -163,8 +182,12 @@ class AsyncTestZoneSpec implements ZoneSpec {
}
}
onHandleError(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any):
boolean {
onHandleError(
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
): boolean {
// Let the parent try to handle the error.
const result = parentZoneDelegate.handleError(targetZone, error);
if (result) {
@@ -216,12 +239,12 @@ export function patchAsyncTest(Zone: ZoneType): void {
// function when asynchronous activity is finished.
if (global.jasmine) {
// Not using an arrow function to preserve context passed from call site
return function(this: unknown, done: any) {
return function (this: unknown, done: any) {
if (!done) {
// if we run beforeEach in @angular/core/testing/testing_internal then we get no done
// fake it here and assume sync.
done = function() {};
done.fail = function(e: any) {
done = function () {};
done.fail = function (e: any) {
throw e;
};
}
@@ -238,7 +261,7 @@ export function patchAsyncTest(Zone: ZoneType): void {
// is finished. This will be correctly consumed by the Mocha framework with
// it('...', async(myFn)); or can be used in a custom framework.
// Not using an arrow function to preserve context passed from call site
return function(this: unknown) {
return function (this: unknown) {
return new Promise<void>((finishCallback, failCallback) => {
runInTestZone(fn, this, finishCallback, failCallback);
});
@@ -246,22 +269,28 @@ export function patchAsyncTest(Zone: ZoneType): void {
};
function runInTestZone(
fn: Function, context: any, finishCallback: Function, failCallback: Function) {
fn: Function,
context: any,
finishCallback: Function,
failCallback: Function,
) {
const currentZone = Zone.current;
const AsyncTestZoneSpec = (Zone as any)['AsyncTestZoneSpec'];
if (AsyncTestZoneSpec === undefined) {
throw new Error(
'AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/plugins/async-test');
'AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/plugins/async-test',
);
}
const ProxyZoneSpec = (Zone as any)['ProxyZoneSpec'] as {
get(): {setDelegate(spec: ZoneSpec): void; getDelegate(): ZoneSpec;};
get(): {setDelegate(spec: ZoneSpec): void; getDelegate(): ZoneSpec};
assertPresent: () => void;
};
if (!ProxyZoneSpec) {
throw new Error(
'ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/plugins/proxy');
'ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/plugins/proxy',
);
}
const proxyZoneSpec = ProxyZoneSpec.get();
ProxyZoneSpec.assertPresent();
@@ -271,31 +300,32 @@ export function patchAsyncTest(Zone: ZoneType): void {
const previousDelegate = proxyZoneSpec.getDelegate();
proxyZone!.parent!.run(() => {
const testZoneSpec: ZoneSpec = new AsyncTestZoneSpec(
() => {
// Need to restore the original zone.
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
// Only reset the zone spec if it's
// still this one. Otherwise, assume
// it's OK.
proxyZoneSpec.setDelegate(previousDelegate);
}
(testZoneSpec as any).unPatchPromiseForTest();
currentZone.run(() => {
finishCallback();
});
},
(error: any) => {
// Need to restore the original zone.
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
// Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
proxyZoneSpec.setDelegate(previousDelegate);
}
(testZoneSpec as any).unPatchPromiseForTest();
currentZone.run(() => {
failCallback(error);
});
},
'test');
() => {
// Need to restore the original zone.
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
// Only reset the zone spec if it's
// still this one. Otherwise, assume
// it's OK.
proxyZoneSpec.setDelegate(previousDelegate);
}
(testZoneSpec as any).unPatchPromiseForTest();
currentZone.run(() => {
finishCallback();
});
},
(error: any) => {
// Need to restore the original zone.
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
// Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
proxyZoneSpec.setDelegate(previousDelegate);
}
(testZoneSpec as any).unPatchPromiseForTest();
currentZone.run(() => {
failCallback(error);
});
},
'test',
);
proxyZoneSpec.setDelegate(testZoneSpec);
(testZoneSpec as any).patchPromiseForTest();
});
+158 -82
View File
@@ -9,7 +9,7 @@
import {ZoneType} from '../zone-impl';
const global: any =
typeof window === 'object' && window || typeof self === 'object' && self || globalThis.global;
(typeof window === 'object' && window) || (typeof self === 'object' && self) || globalThis.global;
interface ScheduledFunction {
endTime: number;
@@ -49,7 +49,7 @@ function FakeDate() {
}
}
FakeDate.now = function(this: unknown) {
FakeDate.now = function (this: unknown) {
const fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncTestZoneSpec) {
return fakeAsyncTestZoneSpec.getFakeSystemTime();
@@ -61,16 +61,18 @@ FakeDate.UTC = OriginalDate.UTC;
FakeDate.parse = OriginalDate.parse;
// keep a reference for zone patched timer function
let patchedTimers: {
setTimeout: typeof setTimeout,
setInterval: typeof setInterval,
clearTimeout: typeof clearTimeout,
clearInterval: typeof clearInterval,
nativeSetTimeout: typeof setTimeout,
nativeClearTimeout: typeof clearTimeout,
}|undefined;
let patchedTimers:
| {
setTimeout: typeof setTimeout;
setInterval: typeof setInterval;
clearTimeout: typeof clearTimeout;
clearInterval: typeof clearInterval;
nativeSetTimeout: typeof setTimeout;
nativeClearTimeout: typeof clearTimeout;
}
| undefined;
const timeoutCallback = function() {};
const timeoutCallback = function () {};
class Scheduler {
// Next scheduler id.
@@ -115,22 +117,26 @@ class Scheduler {
return OriginalDate.now();
}
scheduleFunction(cb: Function, delay: number, options?: {
args?: any[],
isPeriodic?: boolean,
isRequestAnimationFrame?: boolean,
id?: number,
isRequeuePeriodic?: boolean
}): number {
scheduleFunction(
cb: Function,
delay: number,
options?: {
args?: any[];
isPeriodic?: boolean;
isRequestAnimationFrame?: boolean;
id?: number;
isRequeuePeriodic?: boolean;
},
): number {
options = {
...{
args: [],
isPeriodic: false,
isRequestAnimationFrame: false,
id: -1,
isRequeuePeriodic: false
isRequeuePeriodic: false,
},
...options
...options,
};
let currentId = options.id! < 0 ? Scheduler.nextId : options.id!;
Scheduler.nextId = Scheduler.getNextId();
@@ -144,7 +150,7 @@ class Scheduler {
args: options.args!,
delay: delay,
isPeriodic: options.isPeriodic!,
isRequestAnimationFrame: options.isRequestAnimationFrame!
isRequestAnimationFrame: options.isRequestAnimationFrame!,
};
if (options.isRequeuePeriodic!) {
this._currentTickRequeuePeriodicEntries.push(newEntry);
@@ -177,9 +183,13 @@ class Scheduler {
return this._schedulerQueue.length;
}
tickToNext(step: number = 1, doTick?: (elapsed: number) => void, tickOptions?: {
processNewMacroTasksSynchronously: boolean
}) {
tickToNext(
step: number = 1,
doTick?: (elapsed: number) => void,
tickOptions?: {
processNewMacroTasksSynchronously: boolean;
},
) {
if (this._schedulerQueue.length < step) {
return;
}
@@ -190,18 +200,22 @@ class Scheduler {
this.tick(targetTask.endTime - startTime, doTick, tickOptions);
}
tick(millis: number = 0, doTick?: (elapsed: number) => void, tickOptions?: {
processNewMacroTasksSynchronously: boolean
}): void {
tick(
millis: number = 0,
doTick?: (elapsed: number) => void,
tickOptions?: {
processNewMacroTasksSynchronously: boolean;
},
): void {
let finalTime = this._currentTickTime + millis;
let lastCurrentTime = 0;
tickOptions = Object.assign({processNewMacroTasksSynchronously: true}, tickOptions);
// we need to copy the schedulerQueue so nested timeout
// will not be wrongly called in the current tick
// https://github.com/angular/angular/issues/33799
const schedulerQueue = tickOptions.processNewMacroTasksSynchronously ?
this._schedulerQueue :
this._schedulerQueue.slice();
const schedulerQueue = tickOptions.processNewMacroTasksSynchronously
? this._schedulerQueue
: this._schedulerQueue.slice();
if (schedulerQueue.length === 0 && doTick) {
doTick(millis);
return;
@@ -228,7 +242,9 @@ class Scheduler {
doTick(this._currentTickTime - lastCurrentTime);
}
let retval = current.func.apply(
global, current.isRequestAnimationFrame ? [this._currentTickTime] : current.args);
global,
current.isRequestAnimationFrame ? [this._currentTickTime] : current.args,
);
if (!retval) {
// Uncaught exception in the current scheduled function. Stop processing the queue.
break;
@@ -237,7 +253,7 @@ class Scheduler {
// check is there any requeue periodic entry is added in
// current loop, if there is, we need to add to current loop
if (!tickOptions.processNewMacroTasksSynchronously) {
this._currentTickRequeuePeriodicEntries.forEach(newEntry => {
this._currentTickRequeuePeriodicEntries.forEach((newEntry) => {
let i = 0;
for (; i < schedulerQueue.length; i++) {
const currentEntry = schedulerQueue[i];
@@ -297,14 +313,18 @@ class Scheduler {
count++;
if (count > limit) {
throw new Error(
'flush failed after reaching the limit of ' + limit +
' tasks. Does your code use a polling timeout?');
'flush failed after reaching the limit of ' +
limit +
' tasks. Does your code use a polling timeout?',
);
}
// flush only non-periodic timers.
// If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
if (this._schedulerQueue.filter(task => !task.isPeriodic && !task.isRequestAnimationFrame)
.length === 0) {
if (
this._schedulerQueue.filter((task) => !task.isPeriodic && !task.isRequestAnimationFrame)
.length === 0
) {
break;
}
@@ -334,9 +354,10 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
private _scheduler: Scheduler = new Scheduler();
private _microtasks: MicroTaskScheduledFunction[] = [];
private _lastError: Error|null = null;
private _uncaughtPromiseErrors: {rejection: any}[] =
(Promise as any)[(Zone as any).__symbol__('uncaughtPromiseErrors')];
private _lastError: Error | null = null;
private _uncaughtPromiseErrors: {rejection: any}[] = (Promise as any)[
(Zone as any).__symbol__('uncaughtPromiseErrors')
];
pendingPeriodicTimers: number[] = [];
pendingTimers: number[] = [];
@@ -344,8 +365,10 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
private patchDateLocked = false;
constructor(
namePrefix: string, private trackPendingRequestAnimationFrame = false,
private macroTaskOptions?: MacroTaskOptions[]) {
namePrefix: string,
private trackPendingRequestAnimationFrame = false,
private macroTaskOptions?: MacroTaskOptions[],
) {
this.name = 'fakeAsyncTestZone for ' + namePrefix;
// in case user can't access the construction of FakeAsyncTestSpec
// user can also define macroTaskOptions by define a global variable.
@@ -354,18 +377,22 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
}
}
private _fnAndFlush(fn: Function, completers: {onSuccess?: Function, onError?: Function}):
Function {
private _fnAndFlush(
fn: Function,
completers: {onSuccess?: Function; onError?: Function},
): Function {
return (...args: any[]): boolean => {
fn.apply(global, args);
if (this._lastError === null) { // Success
if (this._lastError === null) {
// Success
if (completers.onSuccess != null) {
completers.onSuccess.apply(global);
}
// Flush microtasks only on success.
this.flushMicrotasks();
} else { // Failure
} else {
// Failure
if (completers.onError != null) {
completers.onError.apply(global);
}
@@ -392,8 +419,12 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
return () => {
// Requeue the timer callback if it's not been canceled.
if (this.pendingPeriodicTimers.indexOf(id) !== -1) {
this._scheduler.scheduleFunction(
fn, interval, {args, isPeriodic: true, id, isRequeuePeriodic: true});
this._scheduler.scheduleFunction(fn, interval, {
args,
isPeriodic: true,
id,
isRequeuePeriodic: true,
});
}
};
}
@@ -515,9 +546,13 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
FakeAsyncTestZoneSpec.resetDate();
}
tickToNext(steps: number = 1, doTick?: (elapsed: number) => void, tickOptions: {
processNewMacroTasksSynchronously: boolean
} = {processNewMacroTasksSynchronously: true}): void {
tickToNext(
steps: number = 1,
doTick?: (elapsed: number) => void,
tickOptions: {
processNewMacroTasksSynchronously: boolean;
} = {processNewMacroTasksSynchronously: true},
): void {
if (steps <= 0) {
return;
}
@@ -529,9 +564,13 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
}
}
tick(millis: number = 0, doTick?: (elapsed: number) => void, tickOptions: {
processNewMacroTasksSynchronously: boolean
} = {processNewMacroTasksSynchronously: true}): void {
tick(
millis: number = 0,
doTick?: (elapsed: number) => void,
tickOptions: {
processNewMacroTasksSynchronously: boolean;
} = {processNewMacroTasksSynchronously: true},
): void {
FakeAsyncTestZoneSpec.assertInZone();
this.flushMicrotasks();
this._scheduler.tick(millis, doTick, tickOptions);
@@ -599,7 +638,7 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
// should pass additional arguments to callback if have any
// currently we know process.nextTick will have such additional
// arguments
let additionalArgs: any[]|undefined;
let additionalArgs: any[] | undefined;
if (args) {
let callbackIndex = (task.data as any).cbIdx;
if (typeof args.length === 'number' && args.length > callbackIndex + 1) {
@@ -609,37 +648,48 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
this._microtasks.push({
func: task.invoke,
args: additionalArgs,
target: task.data && (task.data as any).target
target: task.data && (task.data as any).target,
});
break;
case 'macroTask':
switch (task.source) {
case 'setTimeout':
task.data!['handleId'] = this._setTimeout(
task.invoke, task.data!['delay']!,
Array.prototype.slice.call((task.data as any)['args'], 2));
task.invoke,
task.data!['delay']!,
Array.prototype.slice.call((task.data as any)['args'], 2),
);
break;
case 'setImmediate':
task.data!['handleId'] = this._setTimeout(
task.invoke, 0, Array.prototype.slice.call((task.data as any)['args'], 1));
task.invoke,
0,
Array.prototype.slice.call((task.data as any)['args'], 1),
);
break;
case 'setInterval':
task.data!['handleId'] = this._setInterval(
task.invoke, task.data!['delay']!,
Array.prototype.slice.call((task.data as any)['args'], 2));
task.invoke,
task.data!['delay']!,
Array.prototype.slice.call((task.data as any)['args'], 2),
);
break;
case 'XMLHttpRequest.send':
throw new Error(
'Cannot make XHRs from within a fake async test. Request URL: ' +
(task.data as any)['url']);
'Cannot make XHRs from within a fake async test. Request URL: ' +
(task.data as any)['url'],
);
case 'requestAnimationFrame':
case 'webkitRequestAnimationFrame':
case 'mozRequestAnimationFrame':
// Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
// (60 frames per second)
task.data!['handleId'] = this._setTimeout(
task.invoke, 16, (task.data as any)['args'],
this.trackPendingRequestAnimationFrame);
task.invoke,
16,
(task.data as any)['args'],
this.trackPendingRequestAnimationFrame,
);
break;
default:
// user can define which macroTask they want to support by passing
@@ -684,16 +734,23 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
const macroTaskOption = this.findMacroTaskOption(task);
if (macroTaskOption) {
const handleId: number = <number>task.data!['handleId'];
return macroTaskOption.isPeriodic ? this._clearInterval(handleId) :
this._clearTimeout(handleId);
return macroTaskOption.isPeriodic
? this._clearInterval(handleId)
: this._clearTimeout(handleId);
}
return delegate.cancelTask(target, task);
}
}
onInvoke(
delegate: ZoneDelegate, current: Zone, target: Zone, callback: Function, applyThis: any,
applyArgs?: any[], source?: string): any {
delegate: ZoneDelegate,
current: Zone,
target: Zone,
callback: Function,
applyThis: any,
applyArgs?: any[],
source?: string,
): any {
try {
FakeAsyncTestZoneSpec.patchDate();
return delegate.invoke(target, callback, applyThis, applyArgs, source);
@@ -717,17 +774,23 @@ class FakeAsyncTestZoneSpec implements ZoneSpec {
return null;
}
onHandleError(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any):
boolean {
onHandleError(
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
): boolean {
this._lastError = error;
return false; // Don't propagate error to parent zone.
return false; // Don't propagate error to parent zone.
}
}
let _fakeAsyncTestZoneSpec: any = null;
type ProxyZoneSpecType = {
setDelegate(delegateSpec: ZoneSpec): void; getDelegate(): ZoneSpec; resetDelegate(): void;
setDelegate(delegateSpec: ZoneSpec): void;
getDelegate(): ZoneSpec;
resetDelegate(): void;
};
function getProxyZoneSpec(): {get(): ProxyZoneSpecType; assertPresent: () => ProxyZoneSpecType} {
return Zone && (Zone as any)['ProxyZoneSpec'];
@@ -768,12 +831,13 @@ export function resetFakeAsyncZone() {
*/
export function fakeAsync(fn: Function): (...args: any[]) => any {
// Not using an arrow function to preserve context passed from call site
const fakeAsyncFn: any = function(this: unknown, ...args: any[]) {
const fakeAsyncFn: any = function (this: unknown, ...args: any[]) {
const ProxyZoneSpec = getProxyZoneSpec();
if (!ProxyZoneSpec) {
throw new Error(
'ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/plugins/proxy');
'ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/plugins/proxy',
);
}
const proxyZoneSpec = ProxyZoneSpec.assertPresent();
if (Zone.current.get('FakeAsyncTestZoneSpec')) {
@@ -803,13 +867,15 @@ export function fakeAsync(fn: Function): (...args: any[]) => any {
if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
throw new Error(
`${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` +
`periodic timer(s) still in the queue.`);
`${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` +
`periodic timer(s) still in the queue.`,
);
}
if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
throw new Error(
`${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`);
`${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`,
);
}
return res;
} finally {
@@ -885,10 +951,20 @@ export function patchFakeAsyncTest(Zone: ZoneType): void {
// constructor params.
(Zone as any)['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
Zone.__load_patch('fakeasync', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
(Zone as any)[api.symbol('fakeAsyncTest')] =
{resetFakeAsyncZone, flushMicrotasks, discardPeriodicTasks, tick, flush, fakeAsync};
}, true);
Zone.__load_patch(
'fakeasync',
(global: any, Zone: ZoneType, api: _ZonePrivate) => {
(Zone as any)[api.symbol('fakeAsyncTest')] = {
resetFakeAsyncZone,
flushMicrotasks,
discardPeriodicTasks,
tick,
flush,
fakeAsync,
};
},
true,
);
patchedTimers = {
setTimeout: global.setTimeout,
@@ -41,9 +41,11 @@ export function patchLongStackTrace(Zone: ZoneType): void {
// isn't thrown, however it's faster not to actually throw the exception.
const error = getStacktraceWithUncaughtError();
const caughtError = getStacktraceWithCaughtError();
const getStacktrace = error.stack ?
getStacktraceWithUncaughtError :
(caughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError);
const getStacktrace = error.stack
? getStacktraceWithUncaughtError
: caughtError.stack
? getStacktraceWithCaughtError
: getStacktraceWithUncaughtError;
function getFrames(error: Error): string[] {
return error.stack ? error.stack.split(NEWLINE) : [];
@@ -68,8 +70,7 @@ export function patchLongStackTrace(Zone: ZoneType): void {
for (let i = 0; i < frames.length; i++) {
const traceFrames: LongStackTrace = frames[i];
const lastTime = traceFrames.timestamp;
let separator =
`____________________Elapsed ${timestamp - lastTime.getTime()} ms; At: ${lastTime}`;
let separator = `____________________Elapsed ${timestamp - lastTime.getTime()} ms; At: ${lastTime}`;
separator = separator.replace(/[^\w\d]/g, '_');
longTrace.push(sepTemplate.replace(SEP_TAG, separator));
addErrorStack(longTrace, traceFrames.error);
@@ -91,31 +92,34 @@ export function patchLongStackTrace(Zone: ZoneType): void {
return (Error as any).stackTraceLimit > 0;
}
type LongStackTraceZoneSpec = ZoneSpec&{longStackTraceLimit: number};
type LongStackTraceZoneSpec = ZoneSpec & {longStackTraceLimit: number};
(Zone as any)['longStackTraceZoneSpec'] = <LongStackTraceZoneSpec>{
name: 'long-stack-trace',
longStackTraceLimit: 10, // Max number of task to keep the stack trace for.
longStackTraceLimit: 10, // Max number of task to keep the stack trace for.
// add a getLongStackTrace method in spec to
// handle handled reject promise error.
getLongStackTrace: function(error: Error): string |
undefined {
if (!error) {
return undefined;
}
const trace = (error as any)[(Zone as any).__symbol__('currentTaskTrace')];
if (!trace) {
return error.stack;
}
return renderLongStackTrace(trace, error.stack);
},
getLongStackTrace: function (error: Error): string | undefined {
if (!error) {
return undefined;
}
const trace = (error as any)[(Zone as any).__symbol__('currentTaskTrace')];
if (!trace) {
return error.stack;
}
return renderLongStackTrace(trace, error.stack);
},
onScheduleTask: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any {
onScheduleTask: function (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): any {
if (stackTracesEnabled()) {
const currentTask = Zone.currentTask;
let trace =
currentTask && currentTask.data && (currentTask.data as any)[creationTrace] || [];
(currentTask && currentTask.data && (currentTask.data as any)[creationTrace]) || [];
trace = [new LongStackTrace()].concat(trace);
if (trace.length > this.longStackTraceLimit) {
trace.length = this.longStackTraceLimit;
@@ -135,27 +139,31 @@ export function patchLongStackTrace(Zone: ZoneType): void {
return parentZoneDelegate.scheduleTask(targetZone, task);
},
onHandleError: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
error: any): boolean {
onHandleError: function (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
): boolean {
if (stackTracesEnabled()) {
const parentTask = Zone.currentTask || error.task;
if (error instanceof Error && parentTask) {
const longStack =
renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack);
const longStack = renderLongStackTrace(
parentTask.data && parentTask.data[creationTrace],
error.stack,
);
try {
error.stack = (error as any).longStack = longStack;
} catch (err) {
}
} catch (err) {}
}
}
return parentZoneDelegate.handleError(targetZone, error);
}
},
};
function captureStackTraces(stackTraces: string[][], count: number): void {
if (count > 0) {
stackTraces.push(getFrames((new LongStackTrace()).error));
stackTraces.push(getFrames(new LongStackTrace().error));
captureStackTraces(stackTraces, count - 1);
}
}
+84 -34
View File
@@ -11,12 +11,12 @@ import {ZoneType} from '../zone-impl';
export class ProxyZoneSpec implements ZoneSpec {
name: string = 'ProxyZone';
private _delegateSpec: ZoneSpec|null = null;
private _delegateSpec: ZoneSpec | null = null;
properties: {[k: string]: any} = {'ProxyZoneSpec': this};
propertyKeys: string[]|null = null;
propertyKeys: string[] | null = null;
lastTaskState: HasTaskState|null = null;
lastTaskState: HasTaskState | null = null;
isNeedToTriggerHasTask = false;
private tasks: Task[] = [];
@@ -36,22 +36,25 @@ export class ProxyZoneSpec implements ZoneSpec {
return ProxyZoneSpec.get();
}
constructor(private defaultSpecDelegate: ZoneSpec|null = null) {
constructor(private defaultSpecDelegate: ZoneSpec | null = null) {
this.setDelegate(defaultSpecDelegate);
}
setDelegate(delegateSpec: ZoneSpec|null) {
setDelegate(delegateSpec: ZoneSpec | null) {
const isNewDelegate = this._delegateSpec !== delegateSpec;
this._delegateSpec = delegateSpec;
this.propertyKeys && this.propertyKeys.forEach((key) => delete this.properties[key]);
this.propertyKeys = null;
if (delegateSpec && delegateSpec.properties) {
this.propertyKeys = Object.keys(delegateSpec.properties);
this.propertyKeys.forEach((k) => this.properties[k] = delegateSpec.properties![k]);
this.propertyKeys.forEach((k) => (this.properties[k] = delegateSpec.properties![k]));
}
// if a new delegateSpec was set, check if we need to trigger hasTask
if (isNewDelegate && this.lastTaskState &&
(this.lastTaskState.macroTask || this.lastTaskState.microTask)) {
if (
isNewDelegate &&
this.lastTaskState &&
(this.lastTaskState.macroTask || this.lastTaskState.microTask)
) {
this.isNeedToTriggerHasTask = true;
}
}
@@ -60,7 +63,6 @@ export class ProxyZoneSpec implements ZoneSpec {
return this._delegateSpec;
}
resetDelegate() {
const delegateSpec = this.getDelegate();
this.setDelegate(this.defaultSpecDelegate);
@@ -92,12 +94,13 @@ export class ProxyZoneSpec implements ZoneSpec {
return '';
}
const taskInfo = this.tasks.map((task: Task) => {
const dataInfo = task.data &&
Object.keys(task.data)
.map((key: string) => {
return key + ':' + (task.data as any)[key];
})
.join(',');
const dataInfo =
task.data &&
Object.keys(task.data)
.map((key: string) => {
return key + ':' + (task.data as any)[key];
})
.join(',');
return `type: ${task.type}, source: ${task.source}, args: {${dataInfo}}`;
});
const pendingTasksInfo = '--Pending async tasks are: [' + taskInfo + ']';
@@ -107,8 +110,12 @@ export class ProxyZoneSpec implements ZoneSpec {
return pendingTasksInfo;
}
onFork(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, zoneSpec: ZoneSpec):
Zone {
onFork(
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
zoneSpec: ZoneSpec,
): Zone {
if (this._delegateSpec && this._delegateSpec.onFork) {
return this._delegateSpec.onFork(parentZoneDelegate, currentZone, targetZone, zoneSpec);
} else {
@@ -116,33 +123,57 @@ export class ProxyZoneSpec implements ZoneSpec {
}
}
onIntercept(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
source: string): Function {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
source: string,
): Function {
if (this._delegateSpec && this._delegateSpec.onIntercept) {
return this._delegateSpec.onIntercept(
parentZoneDelegate, currentZone, targetZone, delegate, source);
parentZoneDelegate,
currentZone,
targetZone,
delegate,
source,
);
} else {
return parentZoneDelegate.intercept(targetZone, delegate, source);
}
}
onInvoke(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
applyThis: any, applyArgs?: any[], source?: string): any {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
applyThis: any,
applyArgs?: any[],
source?: string,
): any {
this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
if (this._delegateSpec && this._delegateSpec.onInvoke) {
return this._delegateSpec.onInvoke(
parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source);
parentZoneDelegate,
currentZone,
targetZone,
delegate,
applyThis,
applyArgs,
source,
);
} else {
return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
}
}
onHandleError(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any):
boolean {
onHandleError(
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
): boolean {
if (this._delegateSpec && this._delegateSpec.onHandleError) {
return this._delegateSpec.onHandleError(parentZoneDelegate, currentZone, targetZone, error);
} else {
@@ -150,8 +181,12 @@ export class ProxyZoneSpec implements ZoneSpec {
}
}
onScheduleTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
Task {
onScheduleTask(
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task {
if (task.type !== 'eventTask') {
this.tasks.push(task);
}
@@ -163,22 +198,37 @@ export class ProxyZoneSpec implements ZoneSpec {
}
onInvokeTask(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
applyThis: any, applyArgs: any): any {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
applyThis: any,
applyArgs: any,
): any {
if (task.type !== 'eventTask') {
this.removeFromTasks(task);
}
this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
if (this._delegateSpec && this._delegateSpec.onInvokeTask) {
return this._delegateSpec.onInvokeTask(
parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs);
parentZoneDelegate,
currentZone,
targetZone,
task,
applyThis,
applyArgs,
);
} else {
return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
}
}
onCancelTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
any {
onCancelTask(
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): any {
if (task.type !== 'eventTask') {
this.removeFromTasks(task);
}
@@ -37,16 +37,24 @@ export class TaskTrackingZoneSpec implements ZoneSpec {
throw new Error('Unknown task format: ' + type);
}
onScheduleTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
Task {
onScheduleTask(
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): Task {
(task as any)['creationLocation'] = new Error(`Task '${task.type}' from '${task.source}'.`);
const tasks = this.getTasksFor(task.type);
tasks.push(task);
return parentZoneDelegate.scheduleTask(targetZone, task);
}
onCancelTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
any {
onCancelTask(
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): any {
const tasks = this.getTasksFor(task.type);
for (let i = 0; i < tasks.length; i++) {
if (tasks[i] == task) {
@@ -58,8 +66,13 @@ export class TaskTrackingZoneSpec implements ZoneSpec {
}
onInvokeTask(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
applyThis: any, applyArgs: any): any {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
applyThis: any,
applyArgs: any,
): any {
if (task.type === 'eventTask' || task.data?.isPeriodic)
return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
const tasks = this.getTasksFor(task.type);
+62 -32
View File
@@ -13,7 +13,7 @@
import {ZoneType} from '../zone-impl';
const _global: any =
typeof window === 'object' && window || typeof self === 'object' && self || global;
(typeof window === 'object' && window) || (typeof self === 'object' && self) || global;
export function patchWtf(Zone: ZoneType): void {
interface Wtf {
@@ -36,9 +36,9 @@ export function patchWtf(Zone: ZoneType): void {
type WtfEventFn = (...args: any[]) => any;
// Detect and setup WTF.
let wtfTrace: WtfTrace|null = null;
let wtfEvents: WtfEvents|null = null;
const wtfEnabled: boolean = (function(): boolean {
let wtfTrace: WtfTrace | null = null;
let wtfEvents: WtfEvents | null = null;
const wtfEnabled: boolean = (function (): boolean {
const wtf: Wtf = _global['wtf'];
if (wtf) {
wtfTrace = wtf.trace;
@@ -53,77 +53,107 @@ export function patchWtf(Zone: ZoneType): void {
class WtfZoneSpec implements ZoneSpec {
name: string = 'WTF';
static forkInstance =
wtfEnabled ? wtfEvents!.createInstance('Zone:fork(ascii zone, ascii newZone)') : null;
static forkInstance = wtfEnabled
? wtfEvents!.createInstance('Zone:fork(ascii zone, ascii newZone)')
: null;
static scheduleInstance: {[key: string]: WtfEventFn} = {};
static cancelInstance: {[key: string]: WtfEventFn} = {};
static invokeScope: {[key: string]: WtfEventFn} = {};
static invokeTaskScope: {[key: string]: WtfEventFn} = {};
onFork(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
zoneSpec: ZoneSpec): Zone {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
zoneSpec: ZoneSpec,
): Zone {
const retValue = parentZoneDelegate.fork(targetZone, zoneSpec);
WtfZoneSpec.forkInstance!(zonePathName(targetZone), retValue.name);
return retValue;
}
onInvoke(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
applyThis: any, applyArgs?: any[], source?: string): any {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
applyThis: any,
applyArgs?: any[],
source?: string,
): any {
const src = source || 'unknown';
let scope = WtfZoneSpec.invokeScope[src];
if (!scope) {
scope = WtfZoneSpec.invokeScope[src] =
wtfEvents!.createScope(`Zone:invoke:${source}(ascii zone)`);
scope = WtfZoneSpec.invokeScope[src] = wtfEvents!.createScope(
`Zone:invoke:${source}(ascii zone)`,
);
}
return wtfTrace!.leaveScope(
scope(zonePathName(targetZone)),
parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source));
scope(zonePathName(targetZone)),
parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source),
);
}
onHandleError(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
error: any): boolean {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
): boolean {
return parentZoneDelegate.handleError(targetZone, error);
}
onScheduleTask(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): any {
const key = task.type + ':' + task.source;
let instance = WtfZoneSpec.scheduleInstance[key];
if (!instance) {
instance = WtfZoneSpec.scheduleInstance[key] =
wtfEvents!.createInstance(`Zone:schedule:${key}(ascii zone, any data)`);
instance = WtfZoneSpec.scheduleInstance[key] = wtfEvents!.createInstance(
`Zone:schedule:${key}(ascii zone, any data)`,
);
}
const retValue = parentZoneDelegate.scheduleTask(targetZone, task);
instance(zonePathName(targetZone), shallowObj(task.data, 2));
return retValue;
}
onInvokeTask(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
applyThis?: any, applyArgs?: any[]): any {
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
applyThis?: any,
applyArgs?: any[],
): any {
const source = task.source;
let scope = WtfZoneSpec.invokeTaskScope[source];
if (!scope) {
scope = WtfZoneSpec.invokeTaskScope[source] =
wtfEvents!.createScope(`Zone:invokeTask:${source}(ascii zone)`);
scope = WtfZoneSpec.invokeTaskScope[source] = wtfEvents!.createScope(
`Zone:invokeTask:${source}(ascii zone)`,
);
}
return wtfTrace!.leaveScope(
scope(zonePathName(targetZone)),
parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs));
scope(zonePathName(targetZone)),
parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs),
);
}
onCancelTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
any {
onCancelTask(
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
): any {
const key = task.source;
let instance = WtfZoneSpec.cancelInstance[key];
if (!instance) {
instance = WtfZoneSpec.cancelInstance[key] =
wtfEvents!.createInstance(`Zone:cancel:${key}(ascii zone, any options)`);
instance = WtfZoneSpec.cancelInstance[key] = wtfEvents!.createInstance(
`Zone:cancel:${key}(ascii zone, any options)`,
);
}
const retValue = parentZoneDelegate.cancelTask(targetZone, task);
instance(zonePathName(targetZone), shallowObj(task.data, 2));
@@ -131,7 +161,7 @@ export function patchWtf(Zone: ZoneType): void {
}
}
function shallowObj(obj: {[k: string]: any}|undefined, depth: number): any {
function shallowObj(obj: {[k: string]: any} | undefined, depth: number): any {
if (!obj || !depth) return null;
const out: {[k: string]: any} = {};
for (const key in obj) {
@@ -607,7 +607,7 @@ declare global {
* previously. When `__Zone_ignore_on_properties` is setup, we should not see those properties
* on targets.
*/
__Zone_ignore_on_properties?: {target: any; ignoreProperties: string[];}[];
__Zone_ignore_on_properties?: {target: any; ignoreProperties: string[]}[];
/**
* Define the event names of the passive listeners.
+20 -1
View File
@@ -6,7 +6,26 @@
* found in the LICENSE file at https://angular.io/license
*/
import {__symbol__, EventTask as _EventTask, HasTaskState as _HasTaskState, initZone, MacroTask as _MacroTask, MicroTask as _MicroTask, PatchFn, Task as _Task, TaskData as _TaskData, TaskState as _TaskState, TaskType as _TaskType, UncaughtPromiseError as _UncaughtPromiseError, Zone as _Zone, ZoneDelegate as _ZoneDelegate, ZoneFrame, ZonePrivate, ZoneSpec as _ZoneSpec, ZoneType as _ZoneType} from './zone-impl';
import {
__symbol__,
EventTask as _EventTask,
HasTaskState as _HasTaskState,
initZone,
MacroTask as _MacroTask,
MicroTask as _MicroTask,
PatchFn,
Task as _Task,
TaskData as _TaskData,
TaskState as _TaskState,
TaskType as _TaskType,
UncaughtPromiseError as _UncaughtPromiseError,
Zone as _Zone,
ZoneDelegate as _ZoneDelegate,
ZoneFrame,
ZonePrivate,
ZoneSpec as _ZoneSpec,
ZoneType as _ZoneType,
} from './zone-impl';
declare global {
const Zone: ZoneType;
+3 -3
View File
@@ -6,9 +6,9 @@ const MagicString = require('magic-string');
let version = '<unknown>';
if (bazel_version_file) {
const versionTag = require('fs')
.readFileSync(bazel_version_file, {encoding: 'utf-8'})
.split('\n')
.find((s) => s.startsWith('STABLE_PROJECT_VERSION'));
.readFileSync(bazel_version_file, {encoding: 'utf-8'})
.split('\n')
.find((s) => s.startsWith('STABLE_PROJECT_VERSION'));
// Don't assume STABLE_PROJECT_VERSION exists
if (versionTag) {
version = versionTag.split(' ')[1].trim();
+13 -13
View File
@@ -1,6 +1,6 @@
// Sauce configuration
module.exports = function(config, ignoredLaunchers) {
module.exports = function (config, ignoredLaunchers) {
// The WS server is not available with Sauce
config.files.unshift('test/saucelabs.js');
@@ -13,20 +13,20 @@ module.exports = function(config, ignoredLaunchers) {
appiumVersion: '1.9.1',
platformName: 'Android',
deviceName: 'Android GoogleAPI Emulator',
platformVersion: '8.0'
}
platformVersion: '8.0',
},
};
var customLaunchers = {};
if (!ignoredLaunchers) {
customLaunchers = basicLaunchers;
} else {
Object.keys(basicLaunchers).forEach(function(key) {
if (ignoredLaunchers
.filter(function(ignore) {
return ignore === key;
})
.length === 0) {
Object.keys(basicLaunchers).forEach(function (key) {
if (
ignoredLaunchers.filter(function (ignore) {
return ignore === key;
}).length === 0
) {
customLaunchers[key] = basicLaunchers[key];
}
});
@@ -45,8 +45,8 @@ module.exports = function(config, ignoredLaunchers) {
'selenium-version': '3.4.0',
'command-timeout': 600,
'idle-timeout': 600,
'max-duration': 5400
}
'max-duration': 5400,
},
},
customLaunchers: customLaunchers,
@@ -57,12 +57,12 @@ module.exports = function(config, ignoredLaunchers) {
singleRun: true,
plugins: ['karma-*']
plugins: ['karma-*'],
});
if (process.env.TRAVIS) {
config.sauceLabs.build =
'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
process.env.SAUCE_ACCESS_KEY = process.env.SAUCE_ACCESS_KEY.split('').reverse().join('');
+17 -9
View File
@@ -1,14 +1,22 @@
// Sauce configuration with Welenium drivers 3+
module.exports = function(config) {
module.exports = function (config) {
// The WS server is not available with Sauce
config.files.unshift('test/saucelabs.js');
var customLaunchers = {
'SL_CHROME60':
{base: 'SauceLabs', browserName: 'Chrome', platform: 'Windows 10', version: '60.0'},
'SL_SAFARI11':
{base: 'SauceLabs', browserName: 'safari', platform: 'macOS 10.13', version: '11.1'},
'SL_CHROME60': {
base: 'SauceLabs',
browserName: 'Chrome',
platform: 'Windows 10',
version: '60.0',
},
'SL_SAFARI11': {
base: 'SauceLabs',
browserName: 'safari',
platform: 'macOS 10.13',
version: '11.1',
},
};
config.set({
@@ -24,8 +32,8 @@ module.exports = function(config) {
'selenium-version': '3.5.0',
'command-timeout': 600,
'idle-timeout': 600,
'max-duration': 5400
}
'max-duration': 5400,
},
},
customLaunchers: customLaunchers,
@@ -36,12 +44,12 @@ module.exports = function(config) {
singleRun: true,
plugins: ['karma-*']
plugins: ['karma-*'],
});
if (process.env.TRAVIS) {
config.sauceLabs.build =
'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
process.env.SAUCE_ACCESS_KEY = process.env.SAUCE_ACCESS_KEY.split('').reverse().join('');
+27 -19
View File
@@ -1,6 +1,6 @@
// Sauce configuration
module.exports = function(config, ignoredLaunchers) {
module.exports = function (config, ignoredLaunchers) {
// The WS server is not available with Sauce
config.files.unshift('test/saucelabs.js');
@@ -17,10 +17,18 @@ module.exports = function(config, ignoredLaunchers) {
},*/
//'SL_SAFARI8':
// {base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.10', version: '8.0'},
'SL_SAFARI9':
{base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.11', version: '9.0'},
'SL_SAFARI10':
{base: 'SauceLabs', browserName: 'safari', platform: 'OS X 10.11', version: '10.0'},
'SL_SAFARI9': {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.11',
version: '9.0',
},
'SL_SAFARI10': {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.11',
version: '10.0',
},
/*
no longer supported in SauceLabs
'SL_IOS7': {
@@ -42,13 +50,13 @@ module.exports = function(config, ignoredLaunchers) {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
platform: 'Windows 10',
version: '14.14393'
version: '14.14393',
},
'SL_MSEDGE15': {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
platform: 'Windows 10',
version: '15.15063'
version: '15.15063',
},
/*
fix issue #584, Android 4.1~4.3 are not supported
@@ -80,20 +88,20 @@ module.exports = function(config, ignoredLaunchers) {
appiumVersion: '1.12.1',
platformName: 'Android',
deviceName: 'Android GoogleAPI Emulator',
platformVersion: '8.0'
}
platformVersion: '8.0',
},
};
var customLaunchers = {};
if (!ignoredLaunchers) {
customLaunchers = basicLaunchers;
} else {
Object.keys(basicLaunchers).forEach(function(key) {
if (ignoredLaunchers
.filter(function(ignore) {
return ignore === key;
})
.length === 0) {
Object.keys(basicLaunchers).forEach(function (key) {
if (
ignoredLaunchers.filter(function (ignore) {
return ignore === key;
}).length === 0
) {
customLaunchers[key] = basicLaunchers[key];
}
});
@@ -112,8 +120,8 @@ module.exports = function(config, ignoredLaunchers) {
'selenium-version': '2.53.0',
'command-timeout': 600,
'idle-timeout': 600,
'max-duration': 5400
}
'max-duration': 5400,
},
},
customLaunchers: customLaunchers,
@@ -124,12 +132,12 @@ module.exports = function(config, ignoredLaunchers) {
singleRun: true,
plugins: ['karma-*']
plugins: ['karma-*'],
});
if (process.env.TRAVIS) {
config.sauceLabs.build =
'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
process.env.SAUCE_ACCESS_KEY = process.env.SAUCE_ACCESS_KEY.split('').reverse().join('');
+11 -11
View File
@@ -1,6 +1,6 @@
// Sauce configuration
module.exports = function(config, ignoredLaunchers) {
module.exports = function (config, ignoredLaunchers) {
// The WS server is not available with Sauce
config.files.unshift('test/saucelabs.js');
@@ -12,12 +12,12 @@ module.exports = function(config, ignoredLaunchers) {
if (!ignoredLaunchers) {
customLaunchers = basicLaunchers;
} else {
Object.keys(basicLaunchers).forEach(function(key) {
if (ignoredLaunchers
.filter(function(ignore) {
return ignore === key;
})
.length === 0) {
Object.keys(basicLaunchers).forEach(function (key) {
if (
ignoredLaunchers.filter(function (ignore) {
return ignore === key;
}).length === 0
) {
customLaunchers[key] = basicLaunchers[key];
}
});
@@ -36,8 +36,8 @@ module.exports = function(config, ignoredLaunchers) {
'selenium-version': '2.53.0',
'command-timeout': 600,
'idle-timeout': 600,
'max-duration': 5400
}
'max-duration': 5400,
},
},
customLaunchers: customLaunchers,
@@ -48,12 +48,12 @@ module.exports = function(config, ignoredLaunchers) {
singleRun: true,
plugins: ['karma-*']
plugins: ['karma-*'],
});
if (process.env.TRAVIS) {
config.sauceLabs.build =
'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
process.env.SAUCE_ACCESS_KEY = process.env.SAUCE_ACCESS_KEY.split('').reverse().join('');
+4 -4
View File
@@ -31,15 +31,15 @@ function requestHandler(req, res) {
return;
}
fs.readFile(file, function(err, contents) {
fs.readFile(file, function (err, contents) {
if (!err) {
res.end(contents);
} else {
writeNotFound(res);
return;
};
}
});
};
};
}
}
server = http.createServer(requestHandler).listen(8080);
@@ -9,101 +9,106 @@
import {ifEnvSupports} from '../test-util';
declare const global: any;
describe('FileReader', ifEnvSupports('FileReader', function() {
let fileReader: FileReader;
let blob: Blob;
const data = 'Hello, World!';
describe(
'FileReader',
ifEnvSupports('FileReader', function () {
let fileReader: FileReader;
let blob: Blob;
const data = 'Hello, World!';
// Android 4.3's native browser doesn't implement add/RemoveEventListener for FileReader
function supportsEventTargetFns() {
return !!FileReader.prototype.addEventListener &&
!!FileReader.prototype.removeEventListener;
}
(<any>supportsEventTargetFns).message =
'FileReader#addEventListener and FileReader#removeEventListener';
// Android 4.3's native browser doesn't implement add/RemoveEventListener for FileReader
function supportsEventTargetFns() {
return !!FileReader.prototype.addEventListener && !!FileReader.prototype.removeEventListener;
}
(<any>supportsEventTargetFns).message =
'FileReader#addEventListener and FileReader#removeEventListener';
beforeEach(function() {
fileReader = new FileReader();
beforeEach(function () {
fileReader = new FileReader();
try {
blob = new Blob([data]);
} catch (e) {
// For hosts that don't support the Blob ctor (e.g. Android 4.3's native browser)
const blobBuilder = new global['WebKitBlobBuilder']();
blobBuilder.append(data);
try {
blob = new Blob([data]);
} catch (e) {
// For hosts that don't support the Blob ctor (e.g. Android 4.3's native browser)
const blobBuilder = new global['WebKitBlobBuilder']();
blobBuilder.append(data);
blob = blobBuilder.getBlob();
}
});
blob = blobBuilder.getBlob();
}
});
describe('EventTarget methods', ifEnvSupports(supportsEventTargetFns, function() {
it('should bind addEventListener listeners', function(done) {
const testZone = Zone.current.fork({name: 'TestZone'});
describe(
'EventTarget methods',
ifEnvSupports(supportsEventTargetFns, function () {
it('should bind addEventListener listeners', function (done) {
const testZone = Zone.current.fork({name: 'TestZone'});
testZone.run(function() {
fileReader.addEventListener('load', function() {
expect(Zone.current).toBe(testZone);
expect(fileReader.result).toEqual(data);
done();
});
});
testZone.run(function () {
fileReader.addEventListener('load', function () {
expect(Zone.current).toBe(testZone);
expect(fileReader.result).toEqual(data);
done();
});
});
fileReader.readAsText(blob);
});
fileReader.readAsText(blob);
});
it('should remove listeners via removeEventListener', function(done) {
const testZone = Zone.current.fork({name: 'TestZone'});
const listenerSpy = jasmine.createSpy('listener');
it('should remove listeners via removeEventListener', function (done) {
const testZone = Zone.current.fork({name: 'TestZone'});
const listenerSpy = jasmine.createSpy('listener');
testZone.run(function() {
fileReader.addEventListener('loadstart', listenerSpy);
fileReader.addEventListener('loadend', function() {
expect(listenerSpy).not.toHaveBeenCalled();
done();
});
});
testZone.run(function () {
fileReader.addEventListener('loadstart', listenerSpy);
fileReader.addEventListener('loadend', function () {
expect(listenerSpy).not.toHaveBeenCalled();
done();
});
});
fileReader.removeEventListener('loadstart', listenerSpy);
fileReader.readAsText(blob);
});
}));
fileReader.removeEventListener('loadstart', listenerSpy);
fileReader.readAsText(blob);
});
}),
);
it('should bind onEventType listeners', function(done) {
const testZone = Zone.current.fork({name: 'TestZone'});
let listenersCalled = 0;
it('should bind onEventType listeners', function (done) {
const testZone = Zone.current.fork({name: 'TestZone'});
let listenersCalled = 0;
testZone.run(function() {
fileReader.onloadstart = function() {
listenersCalled++;
expect(Zone.current).toBe(testZone);
};
testZone.run(function () {
fileReader.onloadstart = function () {
listenersCalled++;
expect(Zone.current).toBe(testZone);
};
fileReader.onload = function() {
listenersCalled++;
expect(Zone.current).toBe(testZone);
};
fileReader.onload = function () {
listenersCalled++;
expect(Zone.current).toBe(testZone);
};
fileReader.onloadend = function() {
listenersCalled++;
fileReader.onloadend = function () {
listenersCalled++;
expect(Zone.current).toBe(testZone);
expect(fileReader.result).toEqual(data);
expect(listenersCalled).toBe(3);
done();
};
});
expect(Zone.current).toBe(testZone);
expect(fileReader.result).toEqual(data);
expect(listenersCalled).toBe(3);
done();
};
});
fileReader.readAsText(blob);
});
fileReader.readAsText(blob);
});
it('should have correct readyState', function(done) {
fileReader.onloadend = function() {
expect(fileReader.readyState).toBe((<any>FileReader).DONE);
done();
};
it('should have correct readyState', function (done) {
fileReader.onloadend = function () {
expect(fileReader.readyState).toBe((<any>FileReader).DONE);
done();
};
expect(fileReader.readyState).toBe((<any>FileReader).EMPTY);
expect(fileReader.readyState).toBe((<any>FileReader).EMPTY);
fileReader.readAsText(blob);
});
}));
fileReader.readAsText(blob);
});
}),
);
@@ -13,17 +13,17 @@ function supportsImports() {
}
if (supportsImports()) {
describe('HTML Imports', function() {
describe('HTML Imports', function () {
const testZone = Zone.current.fork({name: 'test'});
it('should work with addEventListener', function(done) {
it('should work with addEventListener', function (done) {
let link: HTMLLinkElement;
testZone.run(function() {
testZone.run(function () {
link = document.createElement('link');
link.rel = 'import';
link.href = 'someUrl';
link.addEventListener('error', function() {
link.addEventListener('error', function () {
expect(Zone.current).toBe(testZone);
document.head.removeChild(link);
done();
@@ -40,16 +40,15 @@ if (supportsImports()) {
}
(<any>supportsOnEvents).message = 'Supports HTMLLinkElement#onxxx patching';
ifEnvSupports(supportsOnEvents, function() {
it('should work with onerror', function(done) {
ifEnvSupports(supportsOnEvents, function () {
it('should work with onerror', function (done) {
let link: HTMLLinkElement;
testZone.run(function() {
testZone.run(function () {
link = document.createElement('link');
link.rel = 'import';
link.href = 'anotherUrl';
link.onerror = function() {
link.onerror = function () {
expect(Zone.current).toBe(testZone);
document.head.removeChild(link);
done();
@@ -59,14 +58,14 @@ if (supportsImports()) {
document.head.appendChild(link!);
});
it('should work with onload', function(done) {
it('should work with onload', function (done) {
let link: HTMLLinkElement;
testZone.run(function() {
testZone.run(function () {
link = document.createElement('link');
link.rel = 'import';
link.href = '/base/angular/packages/zone.js/test/assets/import.html';
link.onload = function() {
link.onload = function () {
expect(Zone.current).toBe(testZone);
document.head.removeChild(link);
done();
@@ -12,15 +12,18 @@ declare const global: any;
function supportMediaQuery() {
const _global =
typeof window === 'object' && window || typeof self === 'object' && self || global;
(typeof window === 'object' && window) || (typeof self === 'object' && self) || global;
return _global['MediaQueryList'] && _global['matchMedia'];
}
describe('test mediaQuery patch', ifEnvSupports(supportMediaQuery, () => {
it('test whether addListener is patched', () => {
const mqList = window.matchMedia('min-width:500px');
if (mqList && mqList['addListener']) {
expect((mqList as any)[zoneSymbol('addListener')]).toBeTruthy();
}
});
}));
describe(
'test mediaQuery patch',
ifEnvSupports(supportMediaQuery, () => {
it('test whether addListener is patched', () => {
const mqList = window.matchMedia('min-width:500px');
if (mqList && mqList['addListener']) {
expect((mqList as any)[zoneSymbol('addListener')]).toBeTruthy();
}
});
}),
);
@@ -9,73 +9,78 @@
import {ifEnvSupports} from '../test-util';
declare const global: any;
describe(
'MutationObserver',
ifEnvSupports('MutationObserver', function () {
let elt: HTMLDivElement;
describe('MutationObserver', ifEnvSupports('MutationObserver', function() {
let elt: HTMLDivElement;
beforeEach(function () {
elt = document.createElement('div');
document.body.appendChild(elt);
});
beforeEach(function() {
elt = document.createElement('div');
document.body.appendChild(elt);
});
afterEach(function () {
document.body.removeChild(elt);
});
afterEach(function() {
document.body.removeChild(elt);
});
it('should run observers within the zone', function (done) {
const testZone = Zone.current.fork({name: 'test'});
let ob;
elt = document.createElement('div');
document.body.appendChild(elt);
it('should run observers within the zone', function(done) {
const testZone = Zone.current.fork({name: 'test'});
let ob;
elt = document.createElement('div');
document.body.appendChild(elt);
testZone.run(function () {
ob = new MutationObserver(function () {
expect(Zone.current).toBe(testZone);
done();
});
testZone.run(function() {
ob = new MutationObserver(function() {
expect(Zone.current).toBe(testZone);
done();
});
ob.observe(elt, {childList: true});
});
ob.observe(elt, {childList: true});
});
elt.innerHTML = '<p>hey</p>';
});
elt.innerHTML = '<p>hey</p>';
});
it('should only dequeue upon disconnect if something is observed', function () {
let ob: MutationObserver;
let flag = false;
const elt = document.createElement('div');
const childZone = Zone.current.fork({
name: 'test',
onInvokeTask: function () {
flag = true;
},
});
it('should only dequeue upon disconnect if something is observed', function() {
let ob: MutationObserver;
let flag = false;
const elt = document.createElement('div');
const childZone = Zone.current.fork({
name: 'test',
onInvokeTask: function() {
flag = true;
}
});
childZone.run(function () {
ob = new MutationObserver(function () {});
});
childZone.run(function() {
ob = new MutationObserver(function() {});
});
ob!.disconnect();
expect(flag).toBe(false);
});
}),
);
ob!.disconnect();
expect(flag).toBe(false);
});
}));
describe(
'WebKitMutationObserver',
ifEnvSupports('WebKitMutationObserver', function () {
it('should run observers within the zone', function (done) {
const testZone = Zone.current.fork({name: 'test'});
let elt: HTMLDivElement;
describe('WebKitMutationObserver', ifEnvSupports('WebKitMutationObserver', function() {
it('should run observers within the zone', function(done) {
const testZone = Zone.current.fork({name: 'test'});
let elt: HTMLDivElement;
testZone.run(function () {
elt = document.createElement('div');
testZone.run(function() {
elt = document.createElement('div');
const ob = new global['WebKitMutationObserver'](function () {
expect(Zone.current).toBe(testZone);
done();
});
const ob = new global['WebKitMutationObserver'](function() {
expect(Zone.current).toBe(testZone);
done();
});
ob.observe(elt, {childList: true});
});
ob.observe(elt, {childList: true});
});
elt!.innerHTML = '<p>hey</p>';
});
}));
elt!.innerHTML = '<p>hey</p>';
});
}),
);
@@ -11,16 +11,20 @@ import {ifEnvSupports} from '../test-util';
declare const window: any;
function notificationSupport() {
const desc = window['Notification'] &&
Object.getOwnPropertyDescriptor(window['Notification'].prototype, 'onerror');
const desc =
window['Notification'] &&
Object.getOwnPropertyDescriptor(window['Notification'].prototype, 'onerror');
return window['Notification'] && window['Notification'].prototype && desc && desc.configurable;
}
(<any>notificationSupport).message = 'Notification Support';
describe('Notification API', ifEnvSupports(notificationSupport, function() {
it('Notification API should be patched by Zone', () => {
const Notification = window['Notification'];
expect(Notification.prototype[zoneSymbol('addEventListener')]).toBeTruthy();
});
}));
describe(
'Notification API',
ifEnvSupports(notificationSupport, function () {
it('Notification API should be patched by Zone', () => {
const Notification = window['Notification'];
expect(Notification.prototype[zoneSymbol('addEventListener')]).toBeTruthy();
});
}),
);
+126 -106
View File
@@ -14,131 +14,151 @@ const TIMEOUT = 5000;
if (!window['saucelabs']) {
// sauceLabs does not support WebSockets; skip these tests
xdescribe('WebSocket', ifEnvSupports('WebSocket', function() {
let socket: WebSocket;
const TEST_SERVER_URL = 'ws://localhost:8001';
const testZone = Zone.current.fork({name: 'test'});
xdescribe(
'WebSocket',
ifEnvSupports('WebSocket', function () {
let socket: WebSocket;
const TEST_SERVER_URL = 'ws://localhost:8001';
const testZone = Zone.current.fork({name: 'test'});
beforeEach(function (done) {
socket = new WebSocket(TEST_SERVER_URL);
socket.addEventListener('open', function () {
done();
});
socket.addEventListener('error', function () {
fail(
"Can't establish socket to " +
TEST_SERVER_URL +
'! do you have test/ws-server.js running?',
);
done();
});
}, TIMEOUT);
beforeEach(function(done) {
socket = new WebSocket(TEST_SERVER_URL);
socket.addEventListener('open', function() {
done();
});
socket.addEventListener('error', function() {
fail(
'Can\'t establish socket to ' + TEST_SERVER_URL +
'! do you have test/ws-server.js running?');
done();
});
}, TIMEOUT);
afterEach(function (done) {
socket.addEventListener('close', function () {
done();
});
socket.close();
}, TIMEOUT);
afterEach(function(done) {
socket.addEventListener('close', function() {
done();
});
socket.close();
}, TIMEOUT);
xit('should be patched in a Web Worker', (done) => {
const worker = new Worker('/base/test/ws-webworker-context.js');
worker.onmessage = (e: MessageEvent) => {
if (e.data !== 'pass' && e.data !== 'fail') {
fail(`web worker ${e.data}`);
return;
}
expect(e.data).toBe('pass');
done();
};
}, 10000);
xit('should be patched in a Web Worker', done => {
const worker = new Worker('/base/test/ws-webworker-context.js');
worker.onmessage = (e: MessageEvent) => {
if (e.data !== 'pass' && e.data !== 'fail') {
fail(`web worker ${e.data}`);
return;
}
expect(e.data).toBe('pass');
done();
};
}, 10000);
it(
'should work with addEventListener',
function (done) {
testZone.run(function () {
socket.addEventListener('message', function (event) {
expect(Zone.current).toBe(testZone);
expect(event['data']).toBe('hi');
done();
});
});
socket.send('hi');
},
TIMEOUT,
);
it('should work with addEventListener', function(done) {
testZone.run(function() {
socket.addEventListener('message', function(event) {
expect(Zone.current).toBe(testZone);
expect(event['data']).toBe('hi');
done();
});
});
socket.send('hi');
}, TIMEOUT);
it(
'should respect removeEventListener',
function (done) {
let log = '';
function logOnMessage() {
log += 'a';
it('should respect removeEventListener', function(done) {
let log = '';
expect(log).toEqual('a');
function logOnMessage() {
log += 'a';
socket.removeEventListener('message', logOnMessage);
socket.send('hi');
expect(log).toEqual('a');
setTimeout(function () {
expect(log).toEqual('a');
done();
}, 10);
}
socket.removeEventListener('message', logOnMessage);
socket.send('hi');
socket.addEventListener('message', logOnMessage);
socket.send('hi');
},
TIMEOUT,
);
setTimeout(function() {
expect(log).toEqual('a');
done();
}, 10);
}
it(
'should work with onmessage',
function (done) {
testZone.run(function () {
socket.onmessage = function (contents) {
expect(Zone.current).toBe(testZone);
expect(contents.data).toBe('hi');
done();
};
});
socket.send('hi');
},
TIMEOUT,
);
socket.addEventListener('message', logOnMessage);
socket.send('hi');
}, TIMEOUT);
it(
'should only allow one onmessage handler',
function (done) {
let log = '';
socket.onmessage = function () {
log += 'a';
expect(log).toEqual('b');
done();
};
it('should work with onmessage', function(done) {
testZone.run(function() {
socket.onmessage = function(contents) {
expect(Zone.current).toBe(testZone);
expect(contents.data).toBe('hi');
done();
};
});
socket.send('hi');
}, TIMEOUT);
socket.onmessage = function () {
log += 'b';
expect(log).toEqual('b');
done();
};
socket.send('hi');
},
TIMEOUT,
);
it('should only allow one onmessage handler', function(done) {
let log = '';
it(
'should handler removing onmessage',
function (done) {
let log = '';
socket.onmessage = function() {
log += 'a';
expect(log).toEqual('b');
done();
};
socket.onmessage = function () {
log += 'a';
};
socket.onmessage = function() {
log += 'b';
expect(log).toEqual('b');
done();
};
socket.onmessage = null as any;
socket.send('hi');
}, TIMEOUT);
socket.send('hi');
setTimeout(function () {
expect(log).toEqual('');
done();
}, 100);
},
TIMEOUT,
);
it('should handler removing onmessage', function(done) {
let log = '';
socket.onmessage = function() {
log += 'a';
};
socket.onmessage = null as any;
socket.send('hi');
setTimeout(function() {
expect(log).toEqual('');
done();
}, 100);
}, TIMEOUT);
it('should have constants', function() {
expect(Object.keys(WebSocket)).toContain('CONNECTING');
expect(Object.keys(WebSocket)).toContain('OPEN');
expect(Object.keys(WebSocket)).toContain('CLOSING');
expect(Object.keys(WebSocket)).toContain('CLOSED');
});
}));
it('should have constants', function () {
expect(Object.keys(WebSocket)).toContain('CONNECTING');
expect(Object.keys(WebSocket)).toContain('OPEN');
expect(Object.keys(WebSocket)).toContain('CLOSING');
expect(Object.keys(WebSocket)).toContain('CLOSED');
});
}),
);
}
+19 -14
View File
@@ -23,17 +23,22 @@ function workerSupport() {
(workerSupport as any).message = 'Worker Support';
xdescribe('Worker API', ifEnvSupports(workerSupport, function() {
it('Worker API should be patched by Zone', asyncTest((done: Function) => {
const zone: Zone = Zone.current.fork({name: 'worker'});
zone.run(() => {
const worker =
new Worker('/base/angular/packages/zone.js/test/assets/worker.js');
worker.onmessage = function(evt: MessageEvent) {
expect(evt.data).toEqual('worker');
expect(Zone.current.name).toEqual('worker');
done();
};
});
}, Zone.root));
}));
xdescribe(
'Worker API',
ifEnvSupports(workerSupport, function () {
it(
'Worker API should be patched by Zone',
asyncTest((done: Function) => {
const zone: Zone = Zone.current.fork({name: 'worker'});
zone.run(() => {
const worker = new Worker('/base/angular/packages/zone.js/test/assets/worker.js');
worker.onmessage = function (evt: MessageEvent) {
expect(evt.data).toEqual('worker');
expect(Zone.current.name).toEqual('worker');
done();
};
});
}, Zone.root),
);
}),
);
@@ -6,18 +6,23 @@
* found in the LICENSE file at https://angular.io/license
*/
import {ifEnvSupports, ifEnvSupportsWithDone, supportPatchXHROnProperty, zoneSymbol} from '../test-util';
import {
ifEnvSupports,
ifEnvSupportsWithDone,
supportPatchXHROnProperty,
zoneSymbol,
} from '../test-util';
declare const global: any;
const wtfMock = global.wtfMock;
describe('XMLHttpRequest', function() {
describe('XMLHttpRequest', function () {
let testZone: Zone;
beforeEach(() => {
testZone = Zone.current.fork({name: 'test'});
});
it('should intercept XHRs and treat them as MacroTasks', function(done) {
it('should intercept XHRs and treat them as MacroTasks', function (done) {
let req: XMLHttpRequest;
let onStable: any;
const testZoneWithWtf = Zone.current.fork((Zone as any)['wtfZoneSpec']).fork({
@@ -26,42 +31,51 @@ describe('XMLHttpRequest', function() {
if (!hasTask.macroTask) {
onStable && onStable();
}
}
},
});
testZoneWithWtf.run(() => {
req = new XMLHttpRequest();
const logs: string[] = [];
req.onload = () => {
logs.push('onload');
};
onStable = function() {
expect(wtfMock.log[wtfMock.log.length - 2])
.toEqual('> Zone:invokeTask:XMLHttpRequest.send("<root>::ProxyZone::WTF::TestZone")');
expect(wtfMock.log[wtfMock.log.length - 1])
.toEqual('< Zone:invokeTask:XMLHttpRequest.send');
if (supportPatchXHROnProperty()) {
expect(wtfMock.log[wtfMock.log.length - 3])
.toMatch(/\< Zone\:invokeTask.*addEventListener\:load/);
expect(wtfMock.log[wtfMock.log.length - 4])
.toMatch(/\> Zone\:invokeTask.*addEventListener\:load/);
}
// if browser can patch onload
if ((req as any)[zoneSymbol('loadfalse')]) {
expect(logs).toEqual(['onload']);
}
onStable = null;
done();
};
testZoneWithWtf.run(
() => {
req = new XMLHttpRequest();
const logs: string[] = [];
req.onload = () => {
logs.push('onload');
};
onStable = function () {
expect(wtfMock.log[wtfMock.log.length - 2]).toEqual(
'> Zone:invokeTask:XMLHttpRequest.send("<root>::ProxyZone::WTF::TestZone")',
);
expect(wtfMock.log[wtfMock.log.length - 1]).toEqual(
'< Zone:invokeTask:XMLHttpRequest.send',
);
if (supportPatchXHROnProperty()) {
expect(wtfMock.log[wtfMock.log.length - 3]).toMatch(
/\< Zone\:invokeTask.*addEventListener\:load/,
);
expect(wtfMock.log[wtfMock.log.length - 4]).toMatch(
/\> Zone\:invokeTask.*addEventListener\:load/,
);
}
// if browser can patch onload
if ((req as any)[zoneSymbol('loadfalse')]) {
expect(logs).toEqual(['onload']);
}
onStable = null;
done();
};
req.open('get', '/', true);
req.send();
const lastScheduled = wtfMock.log[wtfMock.log.length - 1];
expect(lastScheduled).toMatch('# Zone:schedule:macroTask:XMLHttpRequest.send');
}, null, undefined, 'unit-test');
req.open('get', '/', true);
req.send();
const lastScheduled = wtfMock.log[wtfMock.log.length - 1];
expect(lastScheduled).toMatch('# Zone:schedule:macroTask:XMLHttpRequest.send');
},
null,
undefined,
'unit-test',
);
});
it('should not trigger Zone callback of internal onreadystatechange', function(done) {
it('should not trigger Zone callback of internal onreadystatechange', function (done) {
const scheduleSpy = jasmine.createSpy('schedule');
const xhrZone = Zone.current.fork({
name: 'xhr',
@@ -70,12 +84,12 @@ describe('XMLHttpRequest', function() {
scheduleSpy(task.source);
}
return delegate.scheduleTask(targetZone, task);
}
},
});
xhrZone.run(() => {
const req = new XMLHttpRequest();
req.onload = function() {
req.onload = function () {
expect(Zone.current.name).toEqual('xhr');
if (supportPatchXHROnProperty()) {
expect(scheduleSpy).toHaveBeenCalled();
@@ -87,12 +101,12 @@ describe('XMLHttpRequest', function() {
});
});
it('should work with onreadystatechange', function(done) {
it('should work with onreadystatechange', function (done) {
let req: XMLHttpRequest;
testZone.run(function() {
testZone.run(function () {
req = new XMLHttpRequest();
req.onreadystatechange = function() {
req.onreadystatechange = function () {
// Make sure that the wrapCallback will only be called once
req.onreadystatechange = null as any;
expect(Zone.current).toBe(testZone);
@@ -104,25 +118,26 @@ describe('XMLHttpRequest', function() {
req!.send();
});
it('should run onload listeners before internal readystatechange', function(done) {
it('should run onload listeners before internal readystatechange', function (done) {
const logs: string[] = [];
const xhrZone = Zone.current.fork({
name: 'xhr',
onInvokeTask: (delegate, curr, target, task, applyThis, applyArgs) => {
logs.push('invokeTask ' + task.source);
return delegate.invokeTask(target, task, applyThis, applyArgs);
}
},
});
xhrZone.run(function() {
xhrZone.run(function () {
const req = new XMLHttpRequest();
req.onload = function() {
req.onload = function () {
logs.push('onload');
(window as any)[Zone.__symbol__('setTimeout')](() => {
expect(logs).toEqual([
'invokeTask XMLHttpRequest.addEventListener:load', 'onload',
'invokeTask XMLHttpRequest.send'
])
'invokeTask XMLHttpRequest.addEventListener:load',
'onload',
'invokeTask XMLHttpRequest.send',
]);
done();
});
};
@@ -131,10 +146,10 @@ describe('XMLHttpRequest', function() {
});
});
it('should invoke xhr task even onload listener throw error', function(done) {
it('should invoke xhr task even onload listener throw error', function (done) {
const oriWindowError = window.onerror;
const logs: string[] = [];
window.onerror = function(err: any) {
window.onerror = function (err: any) {
logs.push(err);
};
try {
@@ -149,12 +164,12 @@ describe('XMLHttpRequest', function() {
logs.push('hasTask ' + hasTaskState.macroTask);
}
return delegate.hasTask(target, hasTaskState);
}
},
});
xhrZone.run(function() {
xhrZone.run(function () {
const req = new XMLHttpRequest();
req.onload = function() {
req.onload = function () {
logs.push('onload');
throw new Error('test');
};
@@ -166,9 +181,14 @@ describe('XMLHttpRequest', function() {
logs.push('onload1');
(window as any)[Zone.__symbol__('setTimeout')](() => {
expect(logs).toEqual([
'hasTask true', 'invokeTask XMLHttpRequest.addEventListener:load', 'onload',
'invokeTask XMLHttpRequest.addEventListener:load', 'onload1',
'invokeTask XMLHttpRequest.send', 'hasTask false', 'Uncaught Error: test'
'hasTask true',
'invokeTask XMLHttpRequest.addEventListener:load',
'onload',
'invokeTask XMLHttpRequest.addEventListener:load',
'onload1',
'invokeTask XMLHttpRequest.send',
'hasTask false',
'Uncaught Error: test',
]);
window.removeEventListener('unhandledrejection', unhandledRejection);
window.onerror = oriWindowError;
@@ -183,96 +203,102 @@ describe('XMLHttpRequest', function() {
}
});
it('should return null when access ontimeout first time without error', function() {
it('should return null when access ontimeout first time without error', function () {
let req: XMLHttpRequest = new XMLHttpRequest();
expect(req.ontimeout).toBe(null);
});
const supportsOnProgress = function() {
return 'onprogress' in (new XMLHttpRequest());
const supportsOnProgress = function () {
return 'onprogress' in new XMLHttpRequest();
};
(<any>supportsOnProgress).message = 'XMLHttpRequest.onprogress';
describe('onprogress', ifEnvSupports(supportsOnProgress, function() {
it('should work with onprogress', function(done) {
let req: XMLHttpRequest;
testZone.run(function() {
req = new XMLHttpRequest();
req.onprogress = function() {
// Make sure that the wrapCallback will only be called once
req.onprogress = null as any;
expect(Zone.current).toBe(testZone);
done();
};
req.open('get', '/', true);
});
describe(
'onprogress',
ifEnvSupports(supportsOnProgress, function () {
it('should work with onprogress', function (done) {
let req: XMLHttpRequest;
testZone.run(function () {
req = new XMLHttpRequest();
req.onprogress = function () {
// Make sure that the wrapCallback will only be called once
req.onprogress = null as any;
expect(Zone.current).toBe(testZone);
done();
};
req.open('get', '/', true);
});
req!.send();
});
req!.send();
});
it('should allow canceling of an XMLHttpRequest', function(done) {
const spy = jasmine.createSpy('spy');
let req: XMLHttpRequest;
let pending = false;
it('should allow canceling of an XMLHttpRequest', function (done) {
const spy = jasmine.createSpy('spy');
let req: XMLHttpRequest;
let pending = false;
const trackingTestZone = Zone.current.fork({
name: 'tracking test zone',
onHasTask:
(delegate: ZoneDelegate, current: Zone, target: Zone,
hasTaskState: HasTaskState) => {
if (hasTaskState.change == 'macroTask') {
pending = hasTaskState.macroTask;
}
delegate.hasTask(target, hasTaskState);
}
});
const trackingTestZone = Zone.current.fork({
name: 'tracking test zone',
onHasTask: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
hasTaskState: HasTaskState,
) => {
if (hasTaskState.change == 'macroTask') {
pending = hasTaskState.macroTask;
}
delegate.hasTask(target, hasTaskState);
},
});
trackingTestZone.run(function() {
req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState === XMLHttpRequest.DONE) {
if (req.status !== 0) {
spy();
}
}
};
req.open('get', '/', true);
trackingTestZone.run(function () {
req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState === XMLHttpRequest.DONE) {
if (req.status !== 0) {
spy();
}
}
};
req.open('get', '/', true);
req.send();
req.abort();
});
req.send();
req.abort();
});
setTimeout(function() {
expect(spy).not.toHaveBeenCalled();
expect(pending).toEqual(false);
done();
}, 0);
});
setTimeout(function () {
expect(spy).not.toHaveBeenCalled();
expect(pending).toEqual(false);
done();
}, 0);
});
it('should allow aborting an XMLHttpRequest after its completed', function(done) {
let req: XMLHttpRequest;
it('should allow aborting an XMLHttpRequest after its completed', function (done) {
let req: XMLHttpRequest;
testZone.run(function() {
req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState === XMLHttpRequest.DONE) {
if (req.status !== 0) {
setTimeout(function() {
req.abort();
done();
}, 0);
}
}
};
req.open('get', '/', true);
testZone.run(function () {
req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState === XMLHttpRequest.DONE) {
if (req.status !== 0) {
setTimeout(function () {
req.abort();
done();
}, 0);
}
}
};
req.open('get', '/', true);
req.send();
});
});
}));
req.send();
});
});
}),
);
it('should preserve other setters', function() {
it('should preserve other setters', function () {
const req = new XMLHttpRequest();
req.open('get', '/', true);
req.send();
@@ -285,26 +311,30 @@ describe('XMLHttpRequest', function() {
}
});
it('should work with synchronous XMLHttpRequest', function() {
it('should work with synchronous XMLHttpRequest', function () {
const log: HasTaskState[] = [];
Zone.current
.fork({
name: 'sync-xhr-test',
onHasTask: function(
delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState) {
log.push(hasTaskState);
delegate.hasTask(target, hasTaskState);
}
})
.run(() => {
const req = new XMLHttpRequest();
req.open('get', '/', false);
req.send();
});
.fork({
name: 'sync-xhr-test',
onHasTask: function (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
hasTaskState: HasTaskState,
) {
log.push(hasTaskState);
delegate.hasTask(target, hasTaskState);
},
})
.run(() => {
const req = new XMLHttpRequest();
req.open('get', '/', false);
req.send();
});
expect(log).toEqual([]);
});
it('should preserve static constants', function() {
it('should preserve static constants', function () {
expect(XMLHttpRequest.UNSENT).toEqual(0);
expect(XMLHttpRequest.OPENED).toEqual(1);
expect(XMLHttpRequest.HEADERS_RECEIVED).toEqual(2);
@@ -312,76 +342,73 @@ describe('XMLHttpRequest', function() {
expect(XMLHttpRequest.DONE).toEqual(4);
});
it('should work properly when send request multiple times on single xmlRequest instance',
function(done) {
testZone.run(function() {
const req = new XMLHttpRequest();
req.open('get', '/', true);
req.send();
req.onload = function() {
req.onload = null as any;
req.open('get', '/', true);
req.onload = function() {
done();
};
expect(() => {
req.send();
}).not.toThrow();
};
});
});
it('should work properly when send request multiple times on single xmlRequest instance', function (done) {
testZone.run(function () {
const req = new XMLHttpRequest();
req.open('get', '/', true);
req.send();
req.onload = function () {
req.onload = null as any;
req.open('get', '/', true);
req.onload = function () {
done();
};
expect(() => {
req.send();
}).not.toThrow();
};
});
});
it('should keep taskcount correctly when abort was called multiple times before request is done',
function(done) {
testZone.run(function() {
const req = new XMLHttpRequest();
it('should keep taskcount correctly when abort was called multiple times before request is done', function (done) {
testZone.run(function () {
const req = new XMLHttpRequest();
req.open('get', '/', true);
req.send();
req.open('get', '/', true);
req.send();
let count = 0;
const listener = function(ev: any) {
if (req.readyState >= 2) {
const isInitial = count++ === 0;
let count = 0;
const listener = function (ev: any) {
if (req.readyState >= 2) {
const isInitial = count++ === 0;
expect(() => {
// this triggers a synchronous dispatch of the state change event.
req.abort();
}).not.toThrow();
expect(() => {
// this triggers a synchronous dispatch of the state change event.
req.abort();
}).not.toThrow();
req.removeEventListener('readystatechange', listener);
req.removeEventListener('readystatechange', listener);
if (isInitial) {
done();
}
}
};
req.addEventListener('readystatechange', listener);
});
});
if (isInitial) {
done();
}
}
};
req.addEventListener('readystatechange', listener);
});
});
it('should close xhr request if error happened when connect', function(done) {
it('should close xhr request if error happened when connect', function (done) {
const logs: boolean[] = [];
Zone.current
.fork({
name: 'xhr',
onHasTask:
(delegate: ZoneDelegate, curr: Zone, target: Zone, taskState: HasTaskState) => {
if (taskState.change === 'macroTask') {
logs.push(taskState.macroTask);
}
return delegate.hasTask(target, taskState);
}
})
.run(function() {
const req = new XMLHttpRequest();
req.open('get', 'http://notexists.url', true);
req.send();
req.addEventListener('error', () => {
expect(logs).toEqual([true, false]);
done();
});
.fork({
name: 'xhr',
onHasTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, taskState: HasTaskState) => {
if (taskState.change === 'macroTask') {
logs.push(taskState.macroTask);
}
return delegate.hasTask(target, taskState);
},
})
.run(function () {
const req = new XMLHttpRequest();
req.open('get', 'http://notexists.url', true);
req.send();
req.addEventListener('error', () => {
expect(logs).toEqual([true, false]);
done();
});
});
});
it('should trigger readystatechange if xhr request trigger cors error', (done) => {
@@ -394,7 +421,7 @@ describe('XMLHttpRequest', function() {
done();
return;
}
req.addEventListener('readystatechange', function(ev) {
req.addEventListener('readystatechange', function (ev) {
if (req.readyState === 4) {
const xhrScheduled = (req as any)[zoneSymbol('xhrScheduled')];
const task = (req as any)[zoneSymbol('xhrTask')];
@@ -427,7 +454,7 @@ describe('XMLHttpRequest', function() {
name: 'xhr',
onHasTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, hasTask: HasTaskState) => {
logs.push(JSON.stringify(hasTask));
}
},
});
const req = new XMLHttpRequest();
try {
@@ -444,7 +471,7 @@ describe('XMLHttpRequest', function() {
timerId = (window as any)[zoneSymbol('setTimeout')](() => {
expect(logs).toEqual([
`{"microTask":false,"macroTask":true,"eventTask":false,"change":"macroTask"}`,
`{"microTask":false,"macroTask":false,"eventTask":false,"change":"macroTask"}`
`{"microTask":false,"macroTask":false,"eventTask":false,"change":"macroTask"}`,
]);
done();
}, 500);
@@ -457,26 +484,25 @@ describe('XMLHttpRequest', function() {
});
});
it('should not throw error when get XMLHttpRequest.prototype.onreadystatechange the first time',
function() {
const func = function() {
testZone.run(function() {
const req = new XMLHttpRequest();
req.onreadystatechange;
});
};
expect(func).not.toThrow();
});
it('should not throw error when get XMLHttpRequest.prototype.onreadystatechange the first time', function () {
const func = function () {
testZone.run(function () {
const req = new XMLHttpRequest();
req.onreadystatechange;
});
};
expect(func).not.toThrow();
});
it('should be in the zone when use XMLHttpRequest.addEventListener', function(done) {
testZone.run(function() {
it('should be in the zone when use XMLHttpRequest.addEventListener', function (done) {
testZone.run(function () {
// sometimes this case will cause timeout
// so we set it longer
const interval = (<any>jasmine).DEFAULT_TIMEOUT_INTERVAL;
(<any>jasmine).DEFAULT_TIMEOUT_INTERVAL = 5000;
const req = new XMLHttpRequest();
req.open('get', '/', true);
req.addEventListener('readystatechange', function() {
req.addEventListener('readystatechange', function () {
if (req.readyState === 4) {
// expect(Zone.current.name).toEqual('test');
(<any>jasmine).DEFAULT_TIMEOUT_INTERVAL = interval;
@@ -487,26 +513,28 @@ describe('XMLHttpRequest', function() {
});
});
it('should return origin listener when call xhr.onreadystatechange',
ifEnvSupportsWithDone(supportPatchXHROnProperty, function(done: Function) {
testZone.run(function() {
// sometimes this case will cause timeout
// so we set it longer
const req = new XMLHttpRequest();
req.open('get', '/', true);
const interval = (<any>jasmine).DEFAULT_TIMEOUT_INTERVAL;
(<any>jasmine).DEFAULT_TIMEOUT_INTERVAL = 5000;
const listener = req.onreadystatechange = function() {
if (req.readyState === 4) {
(<any>jasmine).DEFAULT_TIMEOUT_INTERVAL = interval;
done();
}
};
expect(req.onreadystatechange).toBe(listener);
req.onreadystatechange = function() {
return listener.call(this);
};
req.send();
});
}));
it(
'should return origin listener when call xhr.onreadystatechange',
ifEnvSupportsWithDone(supportPatchXHROnProperty, function (done: Function) {
testZone.run(function () {
// sometimes this case will cause timeout
// so we set it longer
const req = new XMLHttpRequest();
req.open('get', '/', true);
const interval = (<any>jasmine).DEFAULT_TIMEOUT_INTERVAL;
(<any>jasmine).DEFAULT_TIMEOUT_INTERVAL = 5000;
const listener = (req.onreadystatechange = function () {
if (req.readyState === 4) {
(<any>jasmine).DEFAULT_TIMEOUT_INTERVAL = interval;
done();
}
});
expect(req.onreadystatechange).toBe(listener);
req.onreadystatechange = function () {
return listener.call(this);
};
req.send();
});
}),
);
});
File diff suppressed because it is too large Load Diff
@@ -20,14 +20,14 @@ function supportsFormAssociatedElements() {
return 'attachInternals' in HTMLElement.prototype;
}
describe('customElements', function() {
describe('customElements', function () {
const testZone = Zone.current.fork({name: 'test'});
const bridge = {
connectedCallback: () => {},
disconnectedCallback: () => {},
adoptedCallback: () => {},
attributeChangedCallback: () => {},
formAssociatedCallback: () => {}
formAssociatedCallback: () => {},
};
class TestCustomElement extends HTMLElement {
@@ -86,8 +86,8 @@ describe('customElements', function() {
}
});
it('should work with connectedCallback', function(done) {
bridge.connectedCallback = function() {
it('should work with connectedCallback', function (done) {
bridge.connectedCallback = function () {
expect(Zone.current.name).toBe(testZone.name);
done();
};
@@ -96,8 +96,8 @@ describe('customElements', function() {
document.body.appendChild(elt);
});
it('should work with disconnectedCallback', function(done) {
bridge.disconnectedCallback = function() {
it('should work with disconnectedCallback', function (done) {
bridge.disconnectedCallback = function () {
expect(Zone.current.name).toBe(testZone.name);
done();
};
@@ -108,8 +108,8 @@ describe('customElements', function() {
elt = null;
});
it('should work with attributeChanged', function(done) {
bridge.attributeChangedCallback = function(attrName, oldVal, newVal) {
it('should work with attributeChanged', function (done) {
bridge.attributeChangedCallback = function (attrName, oldVal, newVal) {
expect(Zone.current.name).toBe(testZone.name);
expect(attrName).toEqual('attr1');
expect(newVal).toEqual('value1');
@@ -121,12 +121,12 @@ describe('customElements', function() {
elt.setAttribute('attr1', 'value1');
});
it('should work with formAssociatedCallback', function(done) {
it('should work with formAssociatedCallback', function (done) {
if (!supportsFormAssociatedElements()) {
return;
}
bridge.formAssociatedCallback = function() {
bridge.formAssociatedCallback = function () {
expect(Zone.current.name).toBe(testZone.name);
done();
};
@@ -6,14 +6,15 @@
* found in the LICENSE file at https://angular.io/license
*/
describe('defineProperty', function() {
it('should not throw when defining length on an array', function() {
describe('defineProperty', function () {
it('should not throw when defining length on an array', function () {
const someArray: any[] = [];
expect(() => Object.defineProperty(someArray, 'length', {value: 2, writable: false}))
.not.toThrow();
expect(() =>
Object.defineProperty(someArray, 'length', {value: 2, writable: false}),
).not.toThrow();
});
it('should not be able to change a frozen desc', function() {
it('should not be able to change a frozen desc', function () {
const obj = {};
const desc = Object.freeze({value: null, writable: true});
Object.defineProperty(obj, 'prop', desc);
@@ -21,19 +22,17 @@ describe('defineProperty', function() {
expect(objDesc.writable).toBeTruthy();
try {
Object.defineProperty(obj, 'prop', {configurable: true, writable: true, value: 'test'});
} catch (err) {
}
} catch (err) {}
objDesc = Object.getOwnPropertyDescriptor(obj, 'prop');
expect(objDesc.configurable).toBeFalsy();
});
it('should not throw error when try to defineProperty with a frozen obj', function() {
it('should not throw error when try to defineProperty with a frozen obj', function () {
const obj = {};
Object.freeze(obj);
try {
Object.defineProperty(obj, 'prop', {configurable: true, writable: true, value: 'value'});
} catch (err) {
}
} catch (err) {}
expect((obj as any).prop).toBeFalsy();
});
});
@@ -47,11 +46,11 @@ describe('defineProperties', () => {
'property3': {
enumerable: true,
get: () => {
return obj.p3
return obj.p3;
},
set: (val: string) => obj.p3 = val
set: (val: string) => (obj.p3 = val),
},
'property4': {enumerable: false, writable: true, value: 'hidden'}
'property4': {enumerable: false, writable: true, value: 'hidden'},
});
expect(Object.keys(obj).sort()).toEqual(['property1', 'property2', 'property3']);
expect(obj.property1).toBeTrue();
@@ -60,7 +59,7 @@ describe('defineProperties', () => {
expect(obj.property4).toEqual('hidden');
obj.property1 = false;
expect(obj.property1).toBeFalse();
expect(() => obj.property2 = 'new Hello').toThrow();
expect(() => (obj.property2 = 'new Hello')).toThrow();
obj.property3 = 'property3';
expect(obj.property3).toEqual('property3');
obj.property4 = 'property4';
@@ -72,7 +71,7 @@ describe('defineProperties', () => {
const obj: any = {};
Object.defineProperties(obj, {
[a]: {value: true, writable: true},
[b]: {get: () => obj.b1, set: (val: string) => obj.b1 = val}
[b]: {get: () => obj.b1, set: (val: string) => (obj.b1 = val)},
});
expect(Object.keys(obj)).toEqual([]);
expect(obj[a]).toBeTrue();
@@ -130,7 +129,7 @@ describe('defineProperties', () => {
writable: false,
enumerable: false,
});
class Test {};
class Test {}
const obj = new Test();
Object.defineProperties(Test, props);
expect(Object.keys(obj)).toEqual([]);
+83 -82
View File
@@ -8,60 +8,59 @@
import {ifEnvSupports} from '../test-util';
describe('element', function() {
describe('element', function () {
let button: HTMLButtonElement;
beforeEach(function() {
beforeEach(function () {
button = document.createElement('button');
document.body.appendChild(button);
});
afterEach(function() {
afterEach(function () {
document.body.removeChild(button);
});
// https://github.com/angular/zone.js/issues/190
it('should work when addEventListener / removeEventListener are called in the global context',
function() {
const clickEvent = document.createEvent('Event');
let callCount = 0;
it('should work when addEventListener / removeEventListener are called in the global context', function () {
const clickEvent = document.createEvent('Event');
let callCount = 0;
clickEvent.initEvent('click', true, true);
clickEvent.initEvent('click', true, true);
const listener = function(event: Event) {
callCount++;
expect(event).toBe(clickEvent);
};
const listener = function (event: Event) {
callCount++;
expect(event).toBe(clickEvent);
};
// `this` would be null inside the method when `addEventListener` is called from strict mode
// it would be `window`:
// - when called from non strict-mode,
// - when `window.addEventListener` is called explicitly.
addEventListener('click', listener);
// `this` would be null inside the method when `addEventListener` is called from strict mode
// it would be `window`:
// - when called from non strict-mode,
// - when `window.addEventListener` is called explicitly.
addEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(callCount).toEqual(1);
button.dispatchEvent(clickEvent);
expect(callCount).toEqual(1);
removeEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(callCount).toEqual(1);
});
removeEventListener('click', listener);
button.dispatchEvent(clickEvent);
expect(callCount).toEqual(1);
});
it('should work with addEventListener when called with a function listener', function() {
it('should work with addEventListener when called with a function listener', function () {
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
button.addEventListener('click', function(event) {
button.addEventListener('click', function (event) {
expect(event).toBe(clickEvent as any);
});
button.dispatchEvent(clickEvent);
});
it('should not call microtasks early when an event is invoked', function(done) {
it('should not call microtasks early when an event is invoked', function (done) {
let log = '';
button.addEventListener('click', () => {
Zone.current.scheduleMicroTask('test', () => log += 'microtask;');
Zone.current.scheduleMicroTask('test', () => (log += 'microtask;'));
log += 'click;';
});
button.click();
@@ -70,7 +69,7 @@ describe('element', function() {
done();
});
it('should call microtasks early when an event is invoked', function(done) {
it('should call microtasks early when an event is invoked', function (done) {
/*
* In this test we escape the Zone using unpatched setTimeout.
* This way the eventTask invoked from click will think it is the top most
@@ -94,7 +93,7 @@ describe('element', function() {
(window as any)[(Zone as any).__symbol__('setTimeout')](() => {
let log = '';
button.addEventListener('click', () => {
Zone.current.scheduleMicroTask('test', () => log += 'microtask;');
Zone.current.scheduleMicroTask('test', () => (log += 'microtask;'));
log += 'click;';
});
button.click();
@@ -104,27 +103,26 @@ describe('element', function() {
});
});
it('should work with addEventListener when called with an EventListener-implementing listener',
function() {
const eventListener = {
x: 5,
handleEvent: function(event: Event) {
// Test that context is preserved
expect(this.x).toBe(5);
it('should work with addEventListener when called with an EventListener-implementing listener', function () {
const eventListener = {
x: 5,
handleEvent: function (event: Event) {
// Test that context is preserved
expect(this.x).toBe(5);
expect(event).toBe(clickEvent);
}
};
expect(event).toBe(clickEvent);
},
};
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
const clickEvent = document.createEvent('Event');
clickEvent.initEvent('click', true, true);
button.addEventListener('click', eventListener);
button.addEventListener('click', eventListener);
button.dispatchEvent(clickEvent);
});
button.dispatchEvent(clickEvent);
});
it('should respect removeEventListener when called with a function listener', function() {
it('should respect removeEventListener when called with a function listener', function () {
let log = '';
const logFunction = function logFunction() {
log += 'a';
@@ -144,7 +142,7 @@ describe('element', function() {
expect(log).toEqual('aa');
});
it('should respect removeEventListener with an EventListener-implementing listener', function() {
it('should respect removeEventListener with an EventListener-implementing listener', function () {
const eventListener = {x: 5, handleEvent: jasmine.createSpy('handleEvent')};
button.addEventListener('click', eventListener);
@@ -155,12 +153,14 @@ describe('element', function() {
expect(eventListener.handleEvent).not.toHaveBeenCalled();
});
it('should have no effect while calling addEventListener without listener', function() {
it('should have no effect while calling addEventListener without listener', function () {
const onAddEventListenerSpy = jasmine.createSpy('addEventListener');
const eventListenerZone =
Zone.current.fork({name: 'eventListenerZone', onScheduleTask: onAddEventListenerSpy});
expect(function() {
eventListenerZone.run(function() {
const eventListenerZone = Zone.current.fork({
name: 'eventListenerZone',
onScheduleTask: onAddEventListenerSpy,
});
expect(function () {
eventListenerZone.run(function () {
button.addEventListener('click', null as any);
button.addEventListener('click', undefined as any);
});
@@ -168,12 +168,14 @@ describe('element', function() {
expect(onAddEventListenerSpy).not.toHaveBeenCalledWith();
});
it('should have no effect while calling removeEventListener without listener', function() {
it('should have no effect while calling removeEventListener without listener', function () {
const onAddEventListenerSpy = jasmine.createSpy('removeEventListener');
const eventListenerZone =
Zone.current.fork({name: 'eventListenerZone', onScheduleTask: onAddEventListenerSpy});
expect(function() {
eventListenerZone.run(function() {
const eventListenerZone = Zone.current.fork({
name: 'eventListenerZone',
onScheduleTask: onAddEventListenerSpy,
});
expect(function () {
eventListenerZone.run(function () {
button.removeEventListener('click', null as any);
button.removeEventListener('click', undefined as any);
});
@@ -181,8 +183,7 @@ describe('element', function() {
expect(onAddEventListenerSpy).not.toHaveBeenCalledWith();
});
it('should only add a listener once for a given set of arguments', function() {
it('should only add a listener once for a given set of arguments', function () {
const log: string[] = [];
const clickEvent = document.createEvent('Event');
@@ -205,7 +206,7 @@ describe('element', function() {
expect(log).toEqual(['listener']);
});
it('should correctly handler capturing versus nonCapturing eventListeners', function() {
it('should correctly handler capturing versus nonCapturing eventListeners', function () {
const log: string[] = [];
const clickEvent = document.createEvent('Event');
@@ -227,7 +228,7 @@ describe('element', function() {
expect(log).toEqual(['capturingListener', 'bubblingListener']);
});
it('should correctly handler a listener that is both capturing and nonCapturing', function() {
it('should correctly handler a listener that is both capturing and nonCapturing', function () {
const log: string[] = [];
const clickEvent = document.createEvent('Event');
@@ -250,21 +251,23 @@ describe('element', function() {
expect(log).toEqual(['listener', 'listener']);
});
describe('onclick', function() {
describe('onclick', function () {
function supportsOnClick() {
const div = document.createElement('div');
const clickPropDesc = Object.getOwnPropertyDescriptor(div, 'onclick');
return !(
EventTarget && div instanceof EventTarget && clickPropDesc &&
clickPropDesc.value === null);
EventTarget &&
div instanceof EventTarget &&
clickPropDesc &&
clickPropDesc.value === null
);
}
(<any>supportsOnClick).message = 'Supports Element#onclick patching';
ifEnvSupports(supportsOnClick, function() {
it('should spawn new child zones', function() {
ifEnvSupports(supportsOnClick, function () {
it('should spawn new child zones', function () {
let run = false;
button.onclick = function() {
button.onclick = function () {
run = true;
};
@@ -273,13 +276,12 @@ describe('element', function() {
});
});
it('should only allow one onclick handler', function() {
it('should only allow one onclick handler', function () {
let log = '';
button.onclick = function() {
button.onclick = function () {
log += 'a';
};
button.onclick = function() {
button.onclick = function () {
log += 'b';
};
@@ -287,10 +289,9 @@ describe('element', function() {
expect(log).toEqual('b');
});
it('should handler removing onclick', function() {
it('should handler removing onclick', function () {
let log = '';
button.onclick = function() {
button.onclick = function () {
log += 'a';
};
button.onclick = null as any;
@@ -299,7 +300,7 @@ describe('element', function() {
expect(log).toEqual('');
});
it('should be able to deregister the same event twice', function() {
it('should be able to deregister the same event twice', function () {
const listener = (event: Event) => {};
document.body.addEventListener('click', listener, false);
document.body.removeEventListener('click', listener, false);
@@ -307,20 +308,20 @@ describe('element', function() {
});
});
describe('onEvent default behavior', function() {
describe('onEvent default behavior', function () {
let checkbox: HTMLInputElement;
beforeEach(function() {
beforeEach(function () {
checkbox = document.createElement('input');
checkbox.type = 'checkbox';
document.body.appendChild(checkbox);
});
afterEach(function() {
afterEach(function () {
document.body.removeChild(checkbox);
});
it('should be possible to prevent default behavior by returning false', function() {
checkbox.onclick = function() {
it('should be possible to prevent default behavior by returning false', function () {
checkbox.onclick = function () {
return false;
};
@@ -328,8 +329,8 @@ describe('element', function() {
expect(checkbox.checked).toBe(false);
});
it('should have no effect on default behavior when not returning anything', function() {
checkbox.onclick = function() {};
it('should have no effect on default behavior when not returning anything', function () {
checkbox.onclick = function () {};
checkbox.click();
expect(checkbox.checked).toBe(true);
@@ -13,26 +13,29 @@ function supportsGeolocation() {
}
(<any>supportsGeolocation).message = 'Geolocation';
describe('Geolocation', ifEnvSupports(supportsGeolocation, function() {
const testZone = Zone.current.fork({name: 'geotest'});
describe(
'Geolocation',
ifEnvSupports(supportsGeolocation, function () {
const testZone = Zone.current.fork({name: 'geotest'});
it('should work for getCurrentPosition', function(done) {
testZone.run(function() {
navigator.geolocation.getCurrentPosition(function(pos) {
expect(Zone.current).toBe(testZone);
done();
});
});
}, 10000);
it('should work for getCurrentPosition', function (done) {
testZone.run(function () {
navigator.geolocation.getCurrentPosition(function (pos) {
expect(Zone.current).toBe(testZone);
done();
});
});
}, 10000);
it('should work for watchPosition', function(done) {
testZone.run(function() {
let watchId: number;
watchId = navigator.geolocation.watchPosition(function(pos) {
expect(Zone.current).toBe(testZone);
navigator.geolocation.clearWatch(watchId);
done();
});
});
}, 10000);
}));
it('should work for watchPosition', function (done) {
testZone.run(function () {
let watchId: number;
watchId = navigator.geolocation.watchPosition(function (pos) {
expect(Zone.current).toBe(testZone);
navigator.geolocation.clearWatch(watchId);
done();
});
});
}, 10000);
}),
);
@@ -33,9 +33,9 @@ describe('MessagePort onproperties', () => {
it('onmessge should in the zone', (done) => {
const channel = new MessageChannel();
const zone = Zone.current.fork({name: 'zone'});
iframe.onload = function() {
iframe.onload = function () {
zone.run(() => {
channel.port1.onmessage = function() {
channel.port1.onmessage = function () {
expect(Zone.current.name).toBe(zone.name);
done();
};
@@ -12,30 +12,30 @@
*/
function registerElement() {
return ('registerElement' in document) && (typeof customElements === 'undefined');
return 'registerElement' in document && typeof customElements === 'undefined';
}
if (registerElement()) {
describe('document.registerElement', function() {
describe('document.registerElement', function () {
// register a custom element for each callback
const callbackNames = ['created', 'attached', 'detached', 'attributeChanged'];
const callbacks: any = {};
const testZone = Zone.current.fork({name: 'test'});
let customElements;
customElements = testZone.run(function() {
callbackNames.forEach(function(callbackName) {
customElements = testZone.run(function () {
callbackNames.forEach(function (callbackName) {
const fullCallbackName = callbackName + 'Callback';
const proto = Object.create(HTMLElement.prototype);
(proto as any)[fullCallbackName] = function(arg: any) {
(proto as any)[fullCallbackName] = function (arg: any) {
callbacks[callbackName](arg);
};
(<any>document).registerElement('x-' + callbackName.toLowerCase(), {prototype: proto});
});
});
it('should work with createdCallback', function(done) {
callbacks.created = function() {
it('should work with createdCallback', function (done) {
callbacks.created = function () {
expect(Zone.current).toBe(testZone);
done();
};
@@ -43,9 +43,8 @@ if (registerElement()) {
document.createElement('x-created');
});
it('should work with attachedCallback', function(done) {
callbacks.attached = function() {
it('should work with attachedCallback', function (done) {
callbacks.attached = function () {
expect(Zone.current).toBe(testZone);
done();
};
@@ -55,9 +54,8 @@ if (registerElement()) {
document.body.removeChild(elt);
});
it('should work with detachedCallback', function(done) {
callbacks.detached = function() {
it('should work with detachedCallback', function (done) {
callbacks.detached = function () {
expect(Zone.current).toBe(testZone);
done();
};
@@ -67,9 +65,8 @@ if (registerElement()) {
document.body.removeChild(elt);
});
it('should work with attributeChanged', function(done) {
callbacks.attributeChanged = function() {
it('should work with attributeChanged', function (done) {
callbacks.attributeChanged = function () {
expect(Zone.current).toBe(testZone);
done();
};
@@ -78,70 +75,76 @@ if (registerElement()) {
elt.id = 'bar';
});
it('should work with non-writable, non-configurable prototypes created with defineProperty', function (done) {
testZone.run(function () {
const proto = Object.create(HTMLElement.prototype);
it('should work with non-writable, non-configurable prototypes created with defineProperty',
function(done) {
testZone.run(function() {
const proto = Object.create(HTMLElement.prototype);
Object.defineProperty(proto, 'createdCallback', <any>{
writable: false,
configurable: false,
value: checkZone,
});
Object.defineProperty(
proto, 'createdCallback',
<any>{writable: false, configurable: false, value: checkZone});
(<any>document).registerElement('x-prop-desc', {prototype: proto});
(<any>document).registerElement('x-prop-desc', {prototype: proto});
function checkZone() {
expect(Zone.current).toBe(testZone);
done();
}
});
function checkZone() {
expect(Zone.current).toBe(testZone);
done();
}
});
const elt = document.createElement('x-prop-desc');
});
const elt = document.createElement('x-prop-desc');
});
it('should work with non-writable, non-configurable prototypes created with defineProperties', function (done) {
testZone.run(function () {
const proto = Object.create(HTMLElement.prototype);
Object.defineProperties(proto, {
createdCallback: <any>{
writable: false,
configurable: false,
value: checkZone,
},
});
it('should work with non-writable, non-configurable prototypes created with defineProperties',
function(done) {
testZone.run(function() {
const proto = Object.create(HTMLElement.prototype);
(<any>document).registerElement('x-props-desc', {prototype: proto});
Object.defineProperties(proto, {
createdCallback: <any> {
writable: false, configurable: false, value: checkZone
}
});
function checkZone() {
expect(Zone.current).toBe(testZone);
done();
}
});
(<any>document).registerElement('x-props-desc', {prototype: proto});
const elt = document.createElement('x-props-desc');
});
function checkZone() {
expect(Zone.current).toBe(testZone);
done();
}
});
it('should not throw with frozen prototypes ', function () {
testZone.run(function () {
const proto = Object.create(
HTMLElement.prototype,
Object.freeze(<PropertyDescriptorMap>{
createdCallback: <PropertyDescriptor>{
value: () => {},
writable: true,
configurable: true,
},
}),
);
const elt = document.createElement('x-props-desc');
});
Object.defineProperty(proto, 'createdCallback', <any>{
writable: false,
configurable: false,
});
it('should not throw with frozen prototypes ', function() {
testZone.run(function() {
const proto = Object.create(HTMLElement.prototype, Object.freeze(<PropertyDescriptorMap>{
createdCallback: <PropertyDescriptor> {
value: () => {}, writable: true, configurable: true
}
}));
Object.defineProperty(
proto, 'createdCallback', <any>{writable: false, configurable: false});
expect(function() {
expect(function () {
(<any>document).registerElement('x-frozen-desc', {prototype: proto});
}).not.toThrow();
});
});
it('should check bind callback if not own property', function(done) {
testZone.run(function() {
it('should check bind callback if not own property', function (done) {
testZone.run(function () {
const originalProto = {createdCallback: checkZone};
const secondaryProto = Object.create(originalProto);
@@ -159,9 +162,8 @@ if (registerElement()) {
});
});
it('should not throw if no options passed to registerElement', function() {
expect(function() {
it('should not throw if no options passed to registerElement', function () {
expect(function () {
(<any>document).registerElement('x-no-opts');
}).not.toThrow();
});
@@ -6,13 +6,16 @@
* found in the LICENSE file at https://angular.io/license
*/
describe('requestAnimationFrame', function() {
const functions =
['requestAnimationFrame', 'webkitRequestAnimationFrame', 'mozRequestAnimationFrame'];
describe('requestAnimationFrame', function () {
const functions = [
'requestAnimationFrame',
'webkitRequestAnimationFrame',
'mozRequestAnimationFrame',
];
functions.forEach(function(fnName) {
functions.forEach(function (fnName) {
if ((global as any)[fnName] !== undefined) {
describe(fnName, function() {
describe(fnName, function () {
const originalTimeout: number = (<any>jasmine).DEFAULT_TIMEOUT_INTERVAL;
beforeEach(() => {
(<any>jasmine).DEFAULT_TIMEOUT_INTERVAL = 10000;
@@ -23,14 +26,14 @@ describe('requestAnimationFrame', function() {
});
const requestAnimationFrameFn = (window as any)[fnName];
it('should be tolerant of invalid arguments', function() {
it('should be tolerant of invalid arguments', function () {
// requestAnimationFrameFn throws an error on invalid arguments, so expect that.
expect(function() {
expect(function () {
requestAnimationFrameFn(null);
}).toThrow();
});
it('should bind to same zone when called recursively', function(done) {
it('should bind to same zone when called recursively', function (done) {
Zone.current.fork({name: 'TestZone'}).run(() => {
let frames = 0;
let previousTimeStamp = 0;
@@ -16,9 +16,12 @@ describe('shadydom', () => {
document.body.appendChild(span);
document.body.appendChild(fragment);
const targets = [
{name: 'window', target: window}, {name: 'div', target: div}, {name: 'text', target: text},
{name: 'span', target: span}, {name: 'document', target: document},
{name: 'fragment', target: fragment}
{name: 'window', target: window},
{name: 'div', target: div},
{name: 'text', target: text},
{name: 'span', target: span},
{name: 'document', target: document},
{name: 'fragment', target: fragment},
];
targets.forEach((t: any) => {
it(`test for prototype ${t.name}`, () => {
@@ -8,15 +8,21 @@
function initAddEventListeners() {
const HTMLSlotElement = (window as any).HTMLSlotElement;
const prototypes = [
Object.getPrototypeOf(window), Node.prototype, Text.prototype, Element.prototype,
Object.getPrototypeOf(window), HTMLElement.prototype,
HTMLSlotElement && HTMLSlotElement.prototype, DocumentFragment.prototype, Document.prototype
Object.getPrototypeOf(window),
Node.prototype,
Text.prototype,
Element.prototype,
Object.getPrototypeOf(window),
HTMLElement.prototype,
HTMLSlotElement && HTMLSlotElement.prototype,
DocumentFragment.prototype,
Document.prototype,
];
prototypes.forEach(proto => {
proto.addEventListener = function(eventName: string, callback: any) {
prototypes.forEach((proto) => {
proto.addEventListener = function (eventName: string, callback: any) {
this.callback = callback;
};
proto.dispatchEvent = function(event: any) {
proto.dispatchEvent = function (event: any) {
this.callback && this.callback.call(this, event);
};
});
+79 -33
View File
@@ -12,52 +12,86 @@ const testClosureFunction = () => {
const testZoneSpec: ZoneSpec = {
name: 'closure',
properties: {},
onFork:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
zoneSpec: ZoneSpec) => {
return parentZoneDelegate.fork(targetZone, zoneSpec);
},
onFork: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
zoneSpec: ZoneSpec,
) => {
return parentZoneDelegate.fork(targetZone, zoneSpec);
},
onIntercept:
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
source: string) => {
return parentZoneDelegate.intercept(targetZone, delegate, source);
},
onIntercept: (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
source: string,
) => {
return parentZoneDelegate.intercept(targetZone, delegate, source);
},
onInvoke: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
applyThis?: any, applyArgs?: any[], source?: string) {
onInvoke: function (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
delegate: Function,
applyThis?: any,
applyArgs?: any[],
source?: string,
) {
return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
},
onHandleError: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any) {
onHandleError: function (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: any,
) {
return parentZoneDelegate.handleError(targetZone, error);
},
onScheduleTask: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) {
onScheduleTask: function (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
) {
return parentZoneDelegate.scheduleTask(targetZone, task);
},
onInvokeTask: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
applyThis?: any, applyArgs?: any[]) {
onInvokeTask: function (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
applyThis?: any,
applyArgs?: any[],
) {
return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
},
onCancelTask: function(
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) {
onCancelTask: function (
parentZoneDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
task: Task,
) {
return parentZoneDelegate.cancelTask(targetZone, task);
},
onHasTask: function(
delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState) {
onHasTask: function (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
hasTaskState: HasTaskState,
) {
return delegate.hasTask(target, hasTaskState);
}
},
};
Zone.__load_patch('test_closure_load_patch', function() {});
Zone.__load_patch('test_closure_load_patch', function () {});
Zone.__symbol__('test_symbol');
const testZone: Zone = Zone.current.fork(testZoneSpec);
@@ -86,7 +120,7 @@ const testClosureFunction = () => {
'scheduleEventTask',
'cancelTask',
];
zonePrototypeKeys.forEach(key => {
zonePrototypeKeys.forEach((key) => {
if ((Zone as any).prototype.hasOwnProperty(key)) {
logs.push(key);
}
@@ -104,19 +138,31 @@ const testClosureFunction = () => {
'onCancelTask',
'onHasTask',
];
zoneSpecKeys.forEach(key => {
zoneSpecKeys.forEach((key) => {
if (testZoneSpec.hasOwnProperty(key)) {
logs.push(key);
}
});
const zoneTaskKeys = [
'onHasTask', 'runCount', 'type', 'source', 'data', 'scheduleFn', 'cancelFn', 'callback',
'invoke'
'onHasTask',
'runCount',
'type',
'source',
'data',
'scheduleFn',
'cancelFn',
'callback',
'invoke',
];
const task = Zone.current.scheduleMicroTask('testTask', () => {}, undefined, () => {});
zoneTaskKeys.forEach(key => {
const task = Zone.current.scheduleMicroTask(
'testTask',
() => {},
undefined,
() => {},
);
zoneTaskKeys.forEach((key) => {
if (task.hasOwnProperty(key)) {
logs.push(key);
}
@@ -159,7 +205,7 @@ const testClosureFunction = () => {
'scheduleFn',
'cancelFn',
'callback',
'invoke'
'invoke',
];
let result: boolean = true;
+168 -113
View File
@@ -49,7 +49,7 @@ class WrappedError extends BaseError {
override get stack() {
return ((this.originalError instanceof Error ? this.originalError : this._nativeError) as any)
.stack;
.stack;
}
}
@@ -171,7 +171,7 @@ describe('ZoneAwareError', () => {
it('should copy customized NativeError properties to ZoneAwareError', () => {
const spy = jasmine.createSpy('errorCustomFunction');
const NativeError = (global as any)[(Zone as any).__symbol__('Error')];
NativeError.customFunction = function(args: any) {
NativeError.customFunction = function (args: any) {
spy(args);
};
expect((Error as any)['customProperty']).toBe('customProperty');
@@ -288,13 +288,24 @@ describe('ZoneAwareError', () => {
});
const zoneAwareFrames = [
'Zone.run', 'Zone.runGuarded', 'Zone.scheduleEventTask', 'Zone.scheduleMicroTask',
'Zone.scheduleMacroTask', 'Zone.runTask', 'ZoneDelegate.scheduleTask',
'ZoneDelegate.invokeTask', 'zoneAwareAddListener', 'Zone.prototype.run',
'Zone.prototype.runGuarded', 'Zone.prototype.scheduleEventTask',
'Zone.prototype.scheduleMicroTask', 'Zone.prototype.scheduleMacroTask',
'Zone.prototype.runTask', 'ZoneDelegate.prototype.scheduleTask',
'ZoneDelegate.prototype.invokeTask', 'ZoneTask.invokeTask'
'Zone.run',
'Zone.runGuarded',
'Zone.scheduleEventTask',
'Zone.scheduleMicroTask',
'Zone.scheduleMacroTask',
'Zone.runTask',
'ZoneDelegate.scheduleTask',
'ZoneDelegate.invokeTask',
'zoneAwareAddListener',
'Zone.prototype.run',
'Zone.prototype.runGuarded',
'Zone.prototype.scheduleEventTask',
'Zone.prototype.scheduleMicroTask',
'Zone.prototype.scheduleMacroTask',
'Zone.prototype.runTask',
'ZoneDelegate.prototype.scheduleTask',
'ZoneDelegate.prototype.invokeTask',
'ZoneTask.invokeTask',
];
function assertStackDoesNotContainZoneFrames(err: any) {
@@ -305,7 +316,7 @@ describe('ZoneAwareError', () => {
if (hasZoneStack) {
break;
}
hasZoneStack = zoneAwareFrames.filter(f => frames[i].indexOf(f) !== -1).length > 0;
hasZoneStack = zoneAwareFrames.filter((f) => frames[i].indexOf(f) !== -1).length > 0;
}
if (!hasZoneStack) {
console.log('stack', hasZoneStack, frames, err.originalStack);
@@ -313,137 +324,181 @@ describe('ZoneAwareError', () => {
expect(hasZoneStack).toBe(true);
} else {
for (let i = 0; i < frames.length; i++) {
expect(zoneAwareFrames.filter(f => frames[i].indexOf(f) !== -1)).toEqual([]);
expect(zoneAwareFrames.filter((f) => frames[i].indexOf(f) !== -1)).toEqual([]);
}
}
};
}
const errorZoneSpec = {
name: 'errorZone',
done: <(() => void)|null>null,
onHandleError:
(parentDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: Error) => {
assertStackDoesNotContainZoneFrames(error);
setTimeout(() => {
errorZoneSpec.done && errorZoneSpec.done();
}, 0);
return false;
}
done: <(() => void) | null>null,
onHandleError: (
parentDelegate: ZoneDelegate,
currentZone: Zone,
targetZone: Zone,
error: Error,
) => {
assertStackDoesNotContainZoneFrames(error);
setTimeout(() => {
errorZoneSpec.done && errorZoneSpec.done();
}, 0);
return false;
},
};
const errorZone = Zone.root.fork(errorZoneSpec);
const assertStackDoesNotContainZoneFramesTest = function(testFn: Function) {
return function(done: () => void) {
const assertStackDoesNotContainZoneFramesTest = function (testFn: Function) {
return function (done: () => void) {
errorZoneSpec.done = done;
errorZone.run(testFn);
};
};
describe('Error stack', () => {
it('Error with new which occurs in setTimeout callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
setTimeout(() => {
throw new Error('timeout test error');
}, 10);
}));
it(
'Error with new which occurs in setTimeout callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
setTimeout(() => {
throw new Error('timeout test error');
}, 10);
}),
);
it('Error without new which occurs in setTimeout callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
setTimeout(() => {
throw Error('test error');
}, 10);
}));
it(
'Error without new which occurs in setTimeout callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
setTimeout(() => {
throw Error('test error');
}, 10);
}),
);
it('Error with new which cause by promise rejection should not have zone frames visible',
(done) => {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('test error'));
});
});
p.catch(err => {
assertStackDoesNotContainZoneFrames(err);
done();
});
});
it('Error with new which cause by promise rejection should not have zone frames visible', (done) => {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('test error'));
});
});
p.catch((err) => {
assertStackDoesNotContainZoneFrames(err);
done();
});
});
it('Error without new which cause by promise rejection should not have zone frames visible',
(done) => {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(Error('test error'));
});
});
p.catch(err => {
assertStackDoesNotContainZoneFrames(err);
done();
});
});
it('Error without new which cause by promise rejection should not have zone frames visible', (done) => {
const p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(Error('test error'));
});
});
p.catch((err) => {
assertStackDoesNotContainZoneFrames(err);
done();
});
});
it('Error with new which occurs in eventTask callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.scheduleEventTask('errorEvent', () => {
throw new Error('test error');
}, undefined, () => null, undefined);
task.invoke();
}));
it(
'Error with new which occurs in eventTask callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.scheduleEventTask(
'errorEvent',
() => {
throw new Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it('Error without new which occurs in eventTask callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.scheduleEventTask('errorEvent', () => {
throw Error('test error');
}, undefined, () => null, undefined);
task.invoke();
}));
it(
'Error without new which occurs in eventTask callback should not have zone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.scheduleEventTask(
'errorEvent',
() => {
throw Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it('Error with new which occurs in longStackTraceZone should not have zone frames and longStackTraceZone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.fork((Zone as any)['longStackTraceZoneSpec'])
.scheduleEventTask('errorEvent', () => {
throw new Error('test error');
}, undefined, () => null, undefined);
task.invoke();
}));
it(
'Error with new which occurs in longStackTraceZone should not have zone frames and longStackTraceZone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.fork((Zone as any)['longStackTraceZoneSpec']).scheduleEventTask(
'errorEvent',
() => {
throw new Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it('Error without new which occurs in longStackTraceZone should not have zone frames and longStackTraceZone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.fork((Zone as any)['longStackTraceZoneSpec'])
.scheduleEventTask('errorEvent', () => {
throw Error('test error');
}, undefined, () => null, undefined);
task.invoke();
}));
it(
'Error without new which occurs in longStackTraceZone should not have zone frames and longStackTraceZone frames visible',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.fork((Zone as any)['longStackTraceZoneSpec']).scheduleEventTask(
'errorEvent',
() => {
throw Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it('stack frames of the callback in user customized zoneSpec should be kept',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current.fork((Zone as any)['longStackTraceZoneSpec'])
.fork({
name: 'customZone',
onScheduleTask: (parentDelegate, currentZone, targetZone, task) => {
return parentDelegate.scheduleTask(targetZone, task);
},
onHandleError: (parentDelegate, currentZone, targetZone, error) => {
parentDelegate.handleError(targetZone, error);
const containsCustomZoneSpecStackTrace =
error.stack.indexOf('onScheduleTask') !== -1;
expect(containsCustomZoneSpecStackTrace).toBeTruthy();
return false;
}
})
.scheduleEventTask('errorEvent', () => {
throw new Error('test error');
}, undefined, () => null, undefined);
task.invoke();
}));
it(
'stack frames of the callback in user customized zoneSpec should be kept',
assertStackDoesNotContainZoneFramesTest(() => {
const task = Zone.current
.fork((Zone as any)['longStackTraceZoneSpec'])
.fork({
name: 'customZone',
onScheduleTask: (parentDelegate, currentZone, targetZone, task) => {
return parentDelegate.scheduleTask(targetZone, task);
},
onHandleError: (parentDelegate, currentZone, targetZone, error) => {
parentDelegate.handleError(targetZone, error);
const containsCustomZoneSpecStackTrace = error.stack.indexOf('onScheduleTask') !== -1;
expect(containsCustomZoneSpecStackTrace).toBeTruthy();
return false;
},
})
.scheduleEventTask(
'errorEvent',
() => {
throw new Error('test error');
},
undefined,
() => null,
undefined,
);
task.invoke();
}),
);
it('should be able to generate zone free stack even NativeError stack is readonly', function() {
it('should be able to generate zone free stack even NativeError stack is readonly', function () {
const _global: any =
typeof window === 'object' && window || typeof self === 'object' && self || global;
(typeof window === 'object' && window) || (typeof self === 'object' && self) || global;
const NativeError = _global[zoneSymbol('Error')];
const desc = Object.getOwnPropertyDescriptor(NativeError.prototype, 'stack');
if (desc) {
const originalSet: ((value: any) => void)|undefined = desc.set;
const originalSet: ((value: any) => void) | undefined = desc.set;
// make stack readonly
desc.set = null as any;
File diff suppressed because it is too large Load Diff
+262 -216
View File
@@ -11,243 +11,289 @@ import {ifEnvSupports, ifEnvSupportsWithDone, isFirefox, isSafari} from '../test
declare const global: any;
describe(
'fetch', isNode ? () => {
it('is untested for node as the fetch implementation is experimental', () => {});
} : ifEnvSupports('fetch', function() {
let testZone: Zone;
beforeEach(() => {
testZone = Zone.current.fork({name: 'TestZone'});
});
it('should work for text response', function(done) {
testZone.run(function() {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json')
.then(function(response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
'fetch',
isNode
? () => {
it('is untested for node as the fetch implementation is experimental', () => {});
}
: ifEnvSupports(
'fetch',
function () {
let testZone: Zone;
beforeEach(() => {
testZone = Zone.current.fork({name: 'TestZone'});
});
it('should work for text response', function (done) {
testZone.run(function () {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
response.text().then(function(text: string) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(text.trim()).toEqual('{"hello": "world"}');
done();
});
});
});
});
it('should work for json response', function(done) {
testZone.run(function() {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json')
.then(function(response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
response.json().then(function(obj: any) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(obj.hello).toEqual('world');
done();
});
});
});
});
it('should work for blob response', function(done) {
testZone.run(function() {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json')
.then(function(response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
// Android 4.3- doesn't support response.blob()
if (response.blob) {
response.blob().then(function(blob: any) {
response.text().then(function (text: string) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(blob instanceof Blob).toEqual(true);
expect(text.trim()).toEqual('{"hello": "world"}');
done();
});
} else {
done();
}
});
});
});
},
);
});
});
it('should work for arrayBuffer response', function(done) {
testZone.run(function() {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json')
.then(function(response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
it('should work for json response', function (done) {
testZone.run(function () {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
// Android 4.3- doesn't support response.arrayBuffer()
if (response.arrayBuffer) {
response.arrayBuffer().then(function(blob: any) {
expect(Zone.current).toBe(fetchZone);
expect(blob instanceof ArrayBuffer).toEqual(true);
response.json().then(function (obj: any) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(obj.hello).toEqual('world');
done();
});
} else {
done();
}
},
);
});
});
it('should work for blob response', function (done) {
testZone.run(function () {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
// Android 4.3- doesn't support response.blob()
if (response.blob) {
response.blob().then(function (blob: any) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(blob instanceof Blob).toEqual(true);
done();
});
} else {
done();
}
},
);
});
});
it('should work for arrayBuffer response', function (done) {
testZone.run(function () {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
const fetchZone = Zone.current;
expect(fetchZone.name).toBe(testZone.name);
// Android 4.3- doesn't support response.arrayBuffer()
if (response.arrayBuffer) {
response.arrayBuffer().then(function (blob: any) {
expect(Zone.current).toBe(fetchZone);
expect(blob instanceof ArrayBuffer).toEqual(true);
done();
});
} else {
done();
}
},
);
});
});
it(
'should throw error when send crendential',
ifEnvSupportsWithDone(isFirefox, function (done: DoneFn) {
testZone.run(function () {
global['fetch']('http://user:password@example.com').then(
function (response: any) {
fail('should not success');
},
(error: any) => {
expect(Zone.current.name).toEqual(testZone.name);
expect(error.constructor.name).toEqual('TypeError');
done();
},
);
});
});
});
}),
);
it('should throw error when send crendential',
ifEnvSupportsWithDone(isFirefox, function(done: DoneFn) {
testZone.run(function() {
global['fetch']('http://user:password@example.com')
.then(
function(response: any) {
fail('should not success');
},
(error: any) => {
expect(Zone.current.name).toEqual(testZone.name);
expect(error.constructor.name).toEqual('TypeError');
done();
});
});
}));
describe('macroTask', () => {
const logs: string[] = [];
let fetchZone: Zone;
let fetchTask: any = null;
beforeEach(() => {
logs.splice(0);
fetchZone = Zone.current.fork({
name: 'fetch',
onScheduleTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
if (task.type !== 'eventTask') {
logs.push(`scheduleTask:${task.source}:${task.type}`);
}
if (task.source === 'fetch') {
fetchTask = task;
}
return delegate.scheduleTask(target, task);
},
onInvokeTask:
(delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task, applyThis: any,
applyArgs: any) => {
describe('macroTask', () => {
const logs: string[] = [];
let fetchZone: Zone;
let fetchTask: any = null;
beforeEach(() => {
logs.splice(0);
fetchZone = Zone.current.fork({
name: 'fetch',
onScheduleTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
if (task.type !== 'eventTask') {
logs.push(`scheduleTask:${task.source}:${task.type}`);
}
if (task.source === 'fetch') {
fetchTask = task;
}
return delegate.scheduleTask(target, task);
},
onInvokeTask: (
delegate: ZoneDelegate,
curr: Zone,
target: Zone,
task: Task,
applyThis: any,
applyArgs: any,
) => {
if (task.type !== 'eventTask') {
logs.push(`invokeTask:${task.source}:${task.type}`);
}
return delegate.invokeTask(target, task, applyThis, applyArgs);
},
onCancelTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
if (task.type !== 'eventTask') {
logs.push(`cancelTask:${task.source}:${task.type}`);
}
return delegate.cancelTask(target, task);
}
});
});
it('fetch should be considered as macroTask', (done: DoneFn) => {
fetchZone.run(() => {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json')
.then(function(response: any) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(logs).toEqual([
'scheduleTask:fetch:macroTask', 'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask', 'invokeTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask'
]);
onCancelTask: (delegate: ZoneDelegate, curr: Zone, target: Zone, task: Task) => {
if (task.type !== 'eventTask') {
logs.push(`cancelTask:${task.source}:${task.type}`);
}
return delegate.cancelTask(target, task);
},
});
});
it('fetch should be considered as macroTask', (done: DoneFn) => {
fetchZone.run(() => {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json').then(
function (response: any) {
expect(Zone.current.name).toBe(fetchZone.name);
expect(logs).toEqual([
'scheduleTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'invokeTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
]);
done();
},
);
});
});
// https://github.com/angular/angular/issues/50327
it('Response.json() should be considered as macroTask', (done) => {
fetchZone.run(() => {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json')
.then((response: any) => {
const promise = response.json();
// Ensure it's a `ZoneAwarePromise`.
expect(promise).toBeInstanceOf(global.Promise);
return promise;
})
.then(() => {
expect(logs).toEqual([
'scheduleTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'invokeTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
// Please refer to the issue link above. Previously, `Response` methods were not
// patched by zone.js, and their return values were considered only as
// microtasks (not macrotasks). The Angular zone stabilized prematurely,
// occurring before the resolution of the `response.json()` promise due to the
// falsy value of `zone.hasPendingMacrotasks`. We are now ensuring that
// `Response` methods are treated as macrotasks, similar to the behavior of
// `fetch`.
'scheduleTask:Response.json:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'invokeTask:Response.json:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
]);
done();
});
});
});
it(
'cancel fetch should invoke onCancelTask',
ifEnvSupportsWithDone('AbortController', (done: DoneFn) => {
if (isSafari()) {
// safari not work with AbortController
done();
return;
}
fetchZone.run(() => {
const AbortController = global['AbortController'];
const abort = new AbortController();
const signal = abort.signal;
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json', {
signal,
})
.then(function (response: any) {
fail('should not get response');
})
.catch(function (error: any) {
expect(error.name).toEqual('AbortError');
expect(logs).toEqual([
'scheduleTask:fetch:macroTask',
'cancelTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
]);
done();
});
abort.abort();
});
});
});
// https://github.com/angular/angular/issues/50327
it('Response.json() should be considered as macroTask', done => {
fetchZone.run(() => {
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json')
.then((response: any) => {
const promise = response.json();
// Ensure it's a `ZoneAwarePromise`.
expect(promise).toBeInstanceOf(global.Promise);
return promise;
})
.then(() => {
expect(logs).toEqual([
'scheduleTask:fetch:macroTask', 'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask', 'invokeTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask',
// Please refer to the issue link above. Previously, `Response` methods were not
// patched by zone.js, and their return values were considered only as
// microtasks (not macrotasks). The Angular zone stabilized prematurely,
// occurring before the resolution of the `response.json()` promise due to the
// falsy value of `zone.hasPendingMacrotasks`. We are now ensuring that
// `Response` methods are treated as macrotasks, similar to the behavior of
// `fetch`.
'scheduleTask:Response.json:macroTask', 'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask', 'invokeTask:Response.json:macroTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask'
]);
}),
);
it(
'cancel fetchTask should trigger abort',
ifEnvSupportsWithDone('AbortController', (done: DoneFn) => {
if (isSafari()) {
// safari not work with AbortController
done();
return;
}
fetchZone.run(() => {
const AbortController = global['AbortController'];
const abort = new AbortController();
const signal = abort.signal;
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json', {
signal,
})
.then(function (response: any) {
fail('should not get response');
})
.catch(function (error: any) {
expect(error.name).toEqual('AbortError');
expect(logs).toEqual([
'scheduleTask:fetch:macroTask',
'cancelTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask',
'invokeTask:Promise.then:microTask',
]);
done();
});
fetchTask.zone.cancelTask(fetchTask);
});
}),
);
});
});
it('cancel fetch should invoke onCancelTask',
ifEnvSupportsWithDone('AbortController', (done: DoneFn) => {
if (isSafari()) {
// safari not work with AbortController
done();
return;
}
fetchZone.run(() => {
const AbortController = global['AbortController'];
const abort = new AbortController();
const signal = abort.signal;
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json', {signal})
.then(function(response: any) {
fail('should not get response');
})
.catch(function(error: any) {
expect(error.name).toEqual('AbortError');
expect(logs).toEqual([
'scheduleTask:fetch:macroTask', 'cancelTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask'
]);
done();
});
abort.abort();
});
}));
it('cancel fetchTask should trigger abort',
ifEnvSupportsWithDone('AbortController', (done: DoneFn) => {
if (isSafari()) {
// safari not work with AbortController
done();
return;
}
fetchZone.run(() => {
const AbortController = global['AbortController'];
const abort = new AbortController();
const signal = abort.signal;
global['fetch']('/base/angular/packages/zone.js/test/assets/sample.json', {signal})
.then(function(response: any) {
fail('should not get response');
})
.catch(function(error: any) {
expect(error.name).toEqual('AbortError');
expect(logs).toEqual([
'scheduleTask:fetch:macroTask', 'cancelTask:fetch:macroTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask',
'scheduleTask:Promise.then:microTask', 'invokeTask:Promise.then:microTask'
]);
done();
});
fetchTask.zone.cancelTask(fetchTask);
});
}));
});
}, emptyRun));
},
emptyRun,
),
);
function emptyRun() {
// Jasmine will throw if there are no tests.
+44 -38
View File
@@ -6,42 +6,42 @@
* found in the LICENSE file at https://angular.io/license
*/
describe('Microtasks', function() {
describe('Microtasks', function () {
if (!global.Promise) return;
function scheduleFn(task: Task) {
Promise.resolve().then(<any>task.invoke);
}
it('should execute microtasks enqueued in the root zone', function(done) {
it('should execute microtasks enqueued in the root zone', function (done) {
const log: number[] = [];
Zone.current.scheduleMicroTask('test', () => log.push(1), undefined, scheduleFn);
Zone.current.scheduleMicroTask('test', () => log.push(2), undefined, scheduleFn);
Zone.current.scheduleMicroTask('test', () => log.push(3), undefined, scheduleFn);
setTimeout(function() {
setTimeout(function () {
expect(log).toEqual([1, 2, 3]);
done();
}, 10);
});
it('should correctly scheduleMacroTask microtasks vs macrotasks', function(done) {
it('should correctly scheduleMacroTask microtasks vs macrotasks', function (done) {
const log = ['+root'];
Zone.current.scheduleMicroTask('test', () => log.push('root.mit'), undefined, scheduleFn);
setTimeout(function() {
setTimeout(function () {
log.push('+mat1');
Zone.current.scheduleMicroTask('test', () => log.push('mat1.mit'), undefined, scheduleFn);
log.push('-mat1');
}, 10);
setTimeout(function() {
setTimeout(function () {
log.push('mat2');
}, 30);
setTimeout(function() {
setTimeout(function () {
expect(log).toEqual(['+root', '-root', 'root.mit', '+mat1', '-mat1', 'mat1.mit', 'mat2']);
done();
}, 40);
@@ -49,56 +49,62 @@ describe('Microtasks', function() {
log.push('-root');
});
it('should execute Promise wrapCallback in the zone where they are scheduled', function(done) {
it('should execute Promise wrapCallback in the zone where they are scheduled', function (done) {
const resolvedPromise = Promise.resolve(null);
const testZone = Zone.current.fork({name: ''});
testZone.run(function() {
resolvedPromise.then(function() {
testZone.run(function () {
resolvedPromise.then(function () {
expect(Zone.current.name).toBe(testZone.name);
done();
});
});
});
it('should execute Promise wrapCallback in the zone where they are scheduled even if resolved ' +
'in different zone.',
function(done) {
let resolve: Function;
const promise = new Promise(function(rs) {
resolve = rs;
});
it(
'should execute Promise wrapCallback in the zone where they are scheduled even if resolved ' +
'in different zone.',
function (done) {
let resolve: Function;
const promise = new Promise(function (rs) {
resolve = rs;
});
const testZone = Zone.current.fork({name: 'test'});
const testZone = Zone.current.fork({name: 'test'});
testZone.run(function() {
promise.then(function() {
expect(Zone.current).toBe(testZone);
done();
});
});
testZone.run(function () {
promise.then(function () {
expect(Zone.current).toBe(testZone);
done();
});
});
Zone.current.fork({name: 'test'}).run(function() {
resolve(null);
});
});
Zone.current.fork({name: 'test'}).run(function () {
resolve(null);
});
},
);
describe('Promise', function() {
it('should go through scheduleTask', function(done) {
describe('Promise', function () {
it('should go through scheduleTask', function (done) {
let called = false;
const testZone = Zone.current.fork({
name: 'test',
onScheduleTask: function(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task):
Task {
called = true;
delegate.scheduleTask(target, task);
return task;
}
onScheduleTask: function (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
task: Task,
): Task {
called = true;
delegate.scheduleTask(target, task);
return task;
},
});
testZone.run(function() {
Promise.resolve('value').then(function() {
testZone.run(function () {
Promise.resolve('value').then(function () {
expect(called).toEqual(true);
done();
});
@@ -13,32 +13,35 @@ class TestRejection {
describe('disable wrap uncaught promise rejection', () => {
it('should notify Zone.onHandleError if promise is uncaught', (done) => {
let promiseError: Error|null = null;
let zone: Zone|null = null;
let task: Task|null = null;
let error: Error|null = null;
let promiseError: Error | null = null;
let zone: Zone | null = null;
let task: Task | null = null;
let error: Error | null = null;
Zone.current
.fork({
name: 'promise-error',
onHandleError: (delegate: ZoneDelegate, current: Zone, target: Zone, error: any):
boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
}
})
.run(() => {
zone = Zone.current;
task = Zone.currentTask;
error = new Error('rejectedErrorShouldBeHandled');
try {
// throw so that the stack trace is captured
throw error;
} catch (e) {
}
Promise.reject(error);
expect(promiseError).toBe(null);
});
.fork({
name: 'promise-error',
onHandleError: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
error: any,
): boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
},
})
.run(() => {
zone = Zone.current;
task = Zone.currentTask;
error = new Error('rejectedErrorShouldBeHandled');
try {
// throw so that the stack trace is captured
throw error;
} catch (e) {}
Promise.reject(error);
expect(promiseError).toBe(null);
});
setTimeout((): any => null);
setTimeout(() => {
expect(promiseError).toBe(error);
@@ -50,26 +53,30 @@ describe('disable wrap uncaught promise rejection', () => {
});
it('should print original information when a non-Error object is used for rejection', (done) => {
let promiseError: Error|null = null;
let promiseError: Error | null = null;
let rejectObj: TestRejection;
Zone.current
.fork({
name: 'promise-error',
onHandleError: (delegate: ZoneDelegate, current: Zone, target: Zone, error: any):
boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
}
})
.run(() => {
rejectObj = new TestRejection();
rejectObj.prop1 = 'value1';
rejectObj.prop2 = 'value2';
(rejectObj as any).message = 'rejectMessage';
Promise.reject(rejectObj);
expect(promiseError).toBe(null);
});
.fork({
name: 'promise-error',
onHandleError: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
error: any,
): boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
},
})
.run(() => {
rejectObj = new TestRejection();
rejectObj.prop1 = 'value1';
rejectObj.prop2 = 'value2';
(rejectObj as any).message = 'rejectMessage';
Promise.reject(rejectObj);
expect(promiseError).toBe(null);
});
setTimeout((): any => null);
setTimeout(() => {
expect(promiseError).toEqual(rejectObj as any);
@@ -78,21 +85,25 @@ describe('disable wrap uncaught promise rejection', () => {
});
it('should print original information when a primitive value is used for rejection', (done) => {
let promiseError: number|null = null;
let promiseError: number | null = null;
Zone.current
.fork({
name: 'promise-error',
onHandleError: (delegate: ZoneDelegate, current: Zone, target: Zone, error: any):
boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
}
})
.run(() => {
Promise.reject(42);
expect(promiseError).toBe(null);
});
.fork({
name: 'promise-error',
onHandleError: (
delegate: ZoneDelegate,
current: Zone,
target: Zone,
error: any,
): boolean => {
promiseError = error;
delegate.handleError(target, error);
return false;
},
})
.run(() => {
Promise.reject(42);
expect(promiseError).toBe(null);
});
setTimeout((): any => null);
setTimeout(() => {
expect(promiseError).toBe(42);

Some files were not shown because too many files have changed in this diff Show More