@openrail/netzgrafik-editor-frontend 2.10.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +337 -0
  3. package/dist/netzgrafik-frontend/assets/i18n/de.json +706 -0
  4. package/dist/netzgrafik-frontend/assets/i18n/en.json +706 -0
  5. package/dist/netzgrafik-frontend/assets/i18n/fr.json +706 -0
  6. package/dist/netzgrafik-frontend/favicon.ico +0 -0
  7. package/dist/netzgrafik-frontend/index.html +14 -0
  8. package/dist/netzgrafik-frontend/main.js +48605 -0
  9. package/dist/netzgrafik-frontend/main.js.map +1 -0
  10. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_de_mjs.js +56 -0
  11. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_de_mjs.js.map +1 -0
  12. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_en_mjs.js +35 -0
  13. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_en_mjs.js.map +1 -0
  14. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_extra_de_mjs.js +28 -0
  15. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_extra_de_mjs.js.map +1 -0
  16. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_extra_en_mjs.js +28 -0
  17. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_extra_en_mjs.js.map +1 -0
  18. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_extra_fr_mjs.js +28 -0
  19. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_extra_fr_mjs.js.map +1 -0
  20. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_extra_kde_mjs.js +28 -0
  21. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_extra_kde_mjs.js.map +1 -0
  22. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_fr_mjs.js +84 -0
  23. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_fr_mjs.js.map +1 -0
  24. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_kde_mjs.js +36 -0
  25. package/dist/netzgrafik-frontend/node_modules_angular_common_locales_kde_mjs.js.map +1 -0
  26. package/dist/netzgrafik-frontend/polyfills.js +3861 -0
  27. package/dist/netzgrafik-frontend/polyfills.js.map +1 -0
  28. package/dist/netzgrafik-frontend/runtime.js +334 -0
  29. package/dist/netzgrafik-frontend/runtime.js.map +1 -0
  30. package/dist/netzgrafik-frontend/src_assets_i18n_de_json.js +14 -0
  31. package/dist/netzgrafik-frontend/src_assets_i18n_en_json.js +14 -0
  32. package/dist/netzgrafik-frontend/src_assets_i18n_fr_json.js +14 -0
  33. package/dist/netzgrafik-frontend/styles.css +155 -0
  34. package/dist/netzgrafik-frontend/styles.css.map +1 -0
  35. package/dist/netzgrafik-frontend/vendor.js +177368 -0
  36. package/dist/netzgrafik-frontend/vendor.js.map +1 -0
  37. package/package.json +35 -0
@@ -0,0 +1,3861 @@
1
+ "use strict";
2
+ (self["webpackChunknetzgrafik_frontend"] = self["webpackChunknetzgrafik_frontend"] || []).push([["polyfills"],{
3
+
4
+ /***/ 10762:
5
+ /*!**************************!*\
6
+ !*** ./src/polyfills.ts ***!
7
+ \**************************/
8
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
9
+
10
+ __webpack_require__.r(__webpack_exports__);
11
+ /* harmony import */ var zone_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! zone.js */ 74124);
12
+ /* harmony import */ var zone_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(zone_js__WEBPACK_IMPORTED_MODULE_0__);
13
+ /* harmony import */ var _angular_localize_init__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @angular/localize/init */ 1643);
14
+ /**
15
+ * This file includes polyfills needed by Angular and is loaded before the app.
16
+ * You can add your own extra polyfills to this file.
17
+ *
18
+ * This file is divided into 2 sections:
19
+ * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
20
+ * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
21
+ * file.
22
+ *
23
+ * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
24
+ * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
25
+ * TrainrunSection >= 13 on the desktop, and iOS 10 and Chrome on mobile.
26
+ *
27
+ * Learn more in https://angular.io/guide/browser-support
28
+ */
29
+ /***************************************************************************************************
30
+ * BROWSER POLYFILLS
31
+ */
32
+ /**
33
+ * By default, zone.js will patch all possible macroTask and DomEvents
34
+ * user can disable parts of macroTask/DomEvents patch by setting following flags
35
+ * because those flags need to be set before `zone.js` being loaded, and webpack
36
+ * will put import in the top of bundle, so user need to create a separate file
37
+ * in this directory (for example: zone-flags.ts), and put the following flags
38
+ * into that file, and then add the following code before importing zone.js.
39
+ * import './zone-flags';
40
+ *
41
+ * The flags allowed in zone-flags.ts are listed here.
42
+ *
43
+ * The following flags will work for all browsers.
44
+ *
45
+ * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
46
+ * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
47
+ * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
48
+ *
49
+ * in IE/TrainrunSection developer tools, the addEventListener will also be wrapped by zone.js
50
+ * with the following flag, it will bypass `zone.js` patch for IE/TrainrunSection
51
+ *
52
+ * (window as any).__Zone_enable_cross_context_check = true;
53
+ *
54
+ */
55
+ /***************************************************************************************************
56
+ * Zone JS is required by default for Angular itself.
57
+ */
58
+ // Included with Angular CLI.
59
+ /***************************************************************************************************
60
+ * Load `$localize` onto the global scope - used if i18n tags appear in Angular templates.
61
+ */
62
+
63
+ /***************************************************************************************************
64
+ * APPLICATION IMPORTS
65
+ */
66
+
67
+ /***/ }),
68
+
69
+ /***/ 74124:
70
+ /*!***********************************************!*\
71
+ !*** ./node_modules/zone.js/fesm2015/zone.js ***!
72
+ \***********************************************/
73
+ /***/ (() => {
74
+
75
+
76
+
77
+ /**
78
+ * @license Angular v<unknown>
79
+ * (c) 2010-2024 Google LLC. https://angular.io/
80
+ * License: MIT
81
+ */
82
+ const global = globalThis;
83
+ // __Zone_symbol_prefix global can be used to override the default zone
84
+ // symbol prefix with a custom one if needed.
85
+ function __symbol__(name) {
86
+ const symbolPrefix = global['__Zone_symbol_prefix'] || '__zone_symbol__';
87
+ return symbolPrefix + name;
88
+ }
89
+ function initZone() {
90
+ const performance = global['performance'];
91
+ function mark(name) {
92
+ performance && performance['mark'] && performance['mark'](name);
93
+ }
94
+ function performanceMeasure(name, label) {
95
+ performance && performance['measure'] && performance['measure'](name, label);
96
+ }
97
+ mark('Zone');
98
+ class ZoneImpl {
99
+ // tslint:disable-next-line:require-internal-with-underscore
100
+ static {
101
+ this.__symbol__ = __symbol__;
102
+ }
103
+ static assertZonePatched() {
104
+ if (global['Promise'] !== patches['ZoneAwarePromise']) {
105
+ throw new Error('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.)');
106
+ }
107
+ }
108
+ static get root() {
109
+ let zone = ZoneImpl.current;
110
+ while (zone.parent) {
111
+ zone = zone.parent;
112
+ }
113
+ return zone;
114
+ }
115
+ static get current() {
116
+ return _currentZoneFrame.zone;
117
+ }
118
+ static get currentTask() {
119
+ return _currentTask;
120
+ }
121
+ // tslint:disable-next-line:require-internal-with-underscore
122
+ static __load_patch(name, fn, ignoreDuplicate = false) {
123
+ if (patches.hasOwnProperty(name)) {
124
+ // `checkDuplicate` option is defined from global variable
125
+ // so it works for all modules.
126
+ // `ignoreDuplicate` can work for the specified module
127
+ const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
128
+ if (!ignoreDuplicate && checkDuplicate) {
129
+ throw Error('Already loaded patch: ' + name);
130
+ }
131
+ } else if (!global['__Zone_disable_' + name]) {
132
+ const perfName = 'Zone:' + name;
133
+ mark(perfName);
134
+ patches[name] = fn(global, ZoneImpl, _api);
135
+ performanceMeasure(perfName, perfName);
136
+ }
137
+ }
138
+ get parent() {
139
+ return this._parent;
140
+ }
141
+ get name() {
142
+ return this._name;
143
+ }
144
+ constructor(parent, zoneSpec) {
145
+ this._parent = parent;
146
+ this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
147
+ this._properties = zoneSpec && zoneSpec.properties || {};
148
+ this._zoneDelegate = new _ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
149
+ }
150
+ get(key) {
151
+ const zone = this.getZoneWith(key);
152
+ if (zone) return zone._properties[key];
153
+ }
154
+ getZoneWith(key) {
155
+ let current = this;
156
+ while (current) {
157
+ if (current._properties.hasOwnProperty(key)) {
158
+ return current;
159
+ }
160
+ current = current._parent;
161
+ }
162
+ return null;
163
+ }
164
+ fork(zoneSpec) {
165
+ if (!zoneSpec) throw new Error('ZoneSpec required!');
166
+ return this._zoneDelegate.fork(this, zoneSpec);
167
+ }
168
+ wrap(callback, source) {
169
+ if (typeof callback !== 'function') {
170
+ throw new Error('Expecting function got: ' + callback);
171
+ }
172
+ const _callback = this._zoneDelegate.intercept(this, callback, source);
173
+ const zone = this;
174
+ return function () {
175
+ return zone.runGuarded(_callback, this, arguments, source);
176
+ };
177
+ }
178
+ run(callback, applyThis, applyArgs, source) {
179
+ _currentZoneFrame = {
180
+ parent: _currentZoneFrame,
181
+ zone: this
182
+ };
183
+ try {
184
+ return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
185
+ } finally {
186
+ _currentZoneFrame = _currentZoneFrame.parent;
187
+ }
188
+ }
189
+ runGuarded(callback, applyThis = null, applyArgs, source) {
190
+ _currentZoneFrame = {
191
+ parent: _currentZoneFrame,
192
+ zone: this
193
+ };
194
+ try {
195
+ try {
196
+ return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
197
+ } catch (error) {
198
+ if (this._zoneDelegate.handleError(this, error)) {
199
+ throw error;
200
+ }
201
+ }
202
+ } finally {
203
+ _currentZoneFrame = _currentZoneFrame.parent;
204
+ }
205
+ }
206
+ runTask(task, applyThis, applyArgs) {
207
+ if (task.zone != this) {
208
+ throw new Error('A task can only be run in the zone of creation! (Creation: ' + (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
209
+ }
210
+ const zoneTask = task;
211
+ // https://github.com/angular/zone.js/issues/778, sometimes eventTask
212
+ // will run in notScheduled(canceled) state, we should not try to
213
+ // run such kind of task but just return
214
+ const {
215
+ type,
216
+ data: {
217
+ isPeriodic = false,
218
+ isRefreshable = false
219
+ } = {}
220
+ } = task;
221
+ if (task.state === notScheduled && (type === eventTask || type === macroTask)) {
222
+ return;
223
+ }
224
+ const reEntryGuard = task.state != running;
225
+ reEntryGuard && zoneTask._transitionTo(running, scheduled);
226
+ const previousTask = _currentTask;
227
+ _currentTask = zoneTask;
228
+ _currentZoneFrame = {
229
+ parent: _currentZoneFrame,
230
+ zone: this
231
+ };
232
+ try {
233
+ if (type == macroTask && task.data && !isPeriodic && !isRefreshable) {
234
+ task.cancelFn = undefined;
235
+ }
236
+ try {
237
+ return this._zoneDelegate.invokeTask(this, zoneTask, applyThis, applyArgs);
238
+ } catch (error) {
239
+ if (this._zoneDelegate.handleError(this, error)) {
240
+ throw error;
241
+ }
242
+ }
243
+ } finally {
244
+ // if the task's state is notScheduled or unknown, then it has already been cancelled
245
+ // we should not reset the state to scheduled
246
+ const state = task.state;
247
+ if (state !== notScheduled && state !== unknown) {
248
+ if (type == eventTask || isPeriodic || isRefreshable && state === scheduling) {
249
+ reEntryGuard && zoneTask._transitionTo(scheduled, running, scheduling);
250
+ } else {
251
+ const zoneDelegates = zoneTask._zoneDelegates;
252
+ this._updateTaskCount(zoneTask, -1);
253
+ reEntryGuard && zoneTask._transitionTo(notScheduled, running, notScheduled);
254
+ if (isRefreshable) {
255
+ zoneTask._zoneDelegates = zoneDelegates;
256
+ }
257
+ }
258
+ }
259
+ _currentZoneFrame = _currentZoneFrame.parent;
260
+ _currentTask = previousTask;
261
+ }
262
+ }
263
+ scheduleTask(task) {
264
+ if (task.zone && task.zone !== this) {
265
+ // check if the task was rescheduled, the newZone
266
+ // should not be the children of the original zone
267
+ let newZone = this;
268
+ while (newZone) {
269
+ if (newZone === task.zone) {
270
+ throw Error(`can not reschedule task to ${this.name} which is descendants of the original zone ${task.zone.name}`);
271
+ }
272
+ newZone = newZone.parent;
273
+ }
274
+ }
275
+ task._transitionTo(scheduling, notScheduled);
276
+ const zoneDelegates = [];
277
+ task._zoneDelegates = zoneDelegates;
278
+ task._zone = this;
279
+ try {
280
+ task = this._zoneDelegate.scheduleTask(this, task);
281
+ } catch (err) {
282
+ // should set task's state to unknown when scheduleTask throw error
283
+ // because the err may from reschedule, so the fromState maybe notScheduled
284
+ task._transitionTo(unknown, scheduling, notScheduled);
285
+ // TODO: @JiaLiPassion, should we check the result from handleError?
286
+ this._zoneDelegate.handleError(this, err);
287
+ throw err;
288
+ }
289
+ if (task._zoneDelegates === zoneDelegates) {
290
+ // we have to check because internally the delegate can reschedule the task.
291
+ this._updateTaskCount(task, 1);
292
+ }
293
+ if (task.state == scheduling) {
294
+ task._transitionTo(scheduled, scheduling);
295
+ }
296
+ return task;
297
+ }
298
+ scheduleMicroTask(source, callback, data, customSchedule) {
299
+ return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
300
+ }
301
+ scheduleMacroTask(source, callback, data, customSchedule, customCancel) {
302
+ return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
303
+ }
304
+ scheduleEventTask(source, callback, data, customSchedule, customCancel) {
305
+ return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
306
+ }
307
+ cancelTask(task) {
308
+ 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 + ')');
309
+ if (task.state !== scheduled && task.state !== running) {
310
+ return;
311
+ }
312
+ task._transitionTo(canceling, scheduled, running);
313
+ try {
314
+ this._zoneDelegate.cancelTask(this, task);
315
+ } catch (err) {
316
+ // if error occurs when cancelTask, transit the state to unknown
317
+ task._transitionTo(unknown, canceling);
318
+ this._zoneDelegate.handleError(this, err);
319
+ throw err;
320
+ }
321
+ this._updateTaskCount(task, -1);
322
+ task._transitionTo(notScheduled, canceling);
323
+ task.runCount = -1;
324
+ return task;
325
+ }
326
+ _updateTaskCount(task, count) {
327
+ const zoneDelegates = task._zoneDelegates;
328
+ if (count == -1) {
329
+ task._zoneDelegates = null;
330
+ }
331
+ for (let i = 0; i < zoneDelegates.length; i++) {
332
+ zoneDelegates[i]._updateTaskCount(task.type, count);
333
+ }
334
+ }
335
+ }
336
+ const DELEGATE_ZS = {
337
+ name: '',
338
+ onHasTask: (delegate, _, target, hasTaskState) => delegate.hasTask(target, hasTaskState),
339
+ onScheduleTask: (delegate, _, target, task) => delegate.scheduleTask(target, task),
340
+ onInvokeTask: (delegate, _, target, task, applyThis, applyArgs) => delegate.invokeTask(target, task, applyThis, applyArgs),
341
+ onCancelTask: (delegate, _, target, task) => delegate.cancelTask(target, task)
342
+ };
343
+ class _ZoneDelegate {
344
+ get zone() {
345
+ return this._zone;
346
+ }
347
+ constructor(zone, parentDelegate, zoneSpec) {
348
+ this._taskCounts = {
349
+ 'microTask': 0,
350
+ 'macroTask': 0,
351
+ 'eventTask': 0
352
+ };
353
+ this._zone = zone;
354
+ this._parentDelegate = parentDelegate;
355
+ this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
356
+ this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
357
+ this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this._zone : parentDelegate._forkCurrZone);
358
+ this._interceptZS = zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
359
+ this._interceptDlgt = zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
360
+ this._interceptCurrZone = zoneSpec && (zoneSpec.onIntercept ? this._zone : parentDelegate._interceptCurrZone);
361
+ this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
362
+ this._invokeDlgt = zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
363
+ this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this._zone : parentDelegate._invokeCurrZone);
364
+ this._handleErrorZS = zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
365
+ this._handleErrorDlgt = zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
366
+ this._handleErrorCurrZone = zoneSpec && (zoneSpec.onHandleError ? this._zone : parentDelegate._handleErrorCurrZone);
367
+ this._scheduleTaskZS = zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
368
+ this._scheduleTaskDlgt = zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
369
+ this._scheduleTaskCurrZone = zoneSpec && (zoneSpec.onScheduleTask ? this._zone : parentDelegate._scheduleTaskCurrZone);
370
+ this._invokeTaskZS = zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
371
+ this._invokeTaskDlgt = zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
372
+ this._invokeTaskCurrZone = zoneSpec && (zoneSpec.onInvokeTask ? this._zone : parentDelegate._invokeTaskCurrZone);
373
+ this._cancelTaskZS = zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
374
+ this._cancelTaskDlgt = zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
375
+ this._cancelTaskCurrZone = zoneSpec && (zoneSpec.onCancelTask ? this._zone : parentDelegate._cancelTaskCurrZone);
376
+ this._hasTaskZS = null;
377
+ this._hasTaskDlgt = null;
378
+ this._hasTaskDlgtOwner = null;
379
+ this._hasTaskCurrZone = null;
380
+ const zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
381
+ const parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
382
+ if (zoneSpecHasTask || parentHasTask) {
383
+ // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
384
+ // a case all task related interceptors must go through this ZD. We can't short circuit it.
385
+ this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
386
+ this._hasTaskDlgt = parentDelegate;
387
+ this._hasTaskDlgtOwner = this;
388
+ this._hasTaskCurrZone = this._zone;
389
+ if (!zoneSpec.onScheduleTask) {
390
+ this._scheduleTaskZS = DELEGATE_ZS;
391
+ this._scheduleTaskDlgt = parentDelegate;
392
+ this._scheduleTaskCurrZone = this._zone;
393
+ }
394
+ if (!zoneSpec.onInvokeTask) {
395
+ this._invokeTaskZS = DELEGATE_ZS;
396
+ this._invokeTaskDlgt = parentDelegate;
397
+ this._invokeTaskCurrZone = this._zone;
398
+ }
399
+ if (!zoneSpec.onCancelTask) {
400
+ this._cancelTaskZS = DELEGATE_ZS;
401
+ this._cancelTaskDlgt = parentDelegate;
402
+ this._cancelTaskCurrZone = this._zone;
403
+ }
404
+ }
405
+ }
406
+ fork(targetZone, zoneSpec) {
407
+ return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) : new ZoneImpl(targetZone, zoneSpec);
408
+ }
409
+ intercept(targetZone, callback, source) {
410
+ return this._interceptZS ? this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) : callback;
411
+ }
412
+ invoke(targetZone, callback, applyThis, applyArgs, source) {
413
+ return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) : callback.apply(applyThis, applyArgs);
414
+ }
415
+ handleError(targetZone, error) {
416
+ return this._handleErrorZS ? this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) : true;
417
+ }
418
+ scheduleTask(targetZone, task) {
419
+ let returnTask = task;
420
+ if (this._scheduleTaskZS) {
421
+ if (this._hasTaskZS) {
422
+ returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
423
+ }
424
+ returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
425
+ if (!returnTask) returnTask = task;
426
+ } else {
427
+ if (task.scheduleFn) {
428
+ task.scheduleFn(task);
429
+ } else if (task.type == microTask) {
430
+ scheduleMicroTask(task);
431
+ } else {
432
+ throw new Error('Task is missing scheduleFn.');
433
+ }
434
+ }
435
+ return returnTask;
436
+ }
437
+ invokeTask(targetZone, task, applyThis, applyArgs) {
438
+ return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) : task.callback.apply(applyThis, applyArgs);
439
+ }
440
+ cancelTask(targetZone, task) {
441
+ let value;
442
+ if (this._cancelTaskZS) {
443
+ value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
444
+ } else {
445
+ if (!task.cancelFn) {
446
+ throw Error('Task is not cancelable');
447
+ }
448
+ value = task.cancelFn(task);
449
+ }
450
+ return value;
451
+ }
452
+ hasTask(targetZone, isEmpty) {
453
+ // hasTask should not throw error so other ZoneDelegate
454
+ // can still trigger hasTask callback
455
+ try {
456
+ this._hasTaskZS && this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
457
+ } catch (err) {
458
+ this.handleError(targetZone, err);
459
+ }
460
+ }
461
+ // tslint:disable-next-line:require-internal-with-underscore
462
+ _updateTaskCount(type, count) {
463
+ const counts = this._taskCounts;
464
+ const prev = counts[type];
465
+ const next = counts[type] = prev + count;
466
+ if (next < 0) {
467
+ throw new Error('More tasks executed then were scheduled.');
468
+ }
469
+ if (prev == 0 || next == 0) {
470
+ const isEmpty = {
471
+ microTask: counts['microTask'] > 0,
472
+ macroTask: counts['macroTask'] > 0,
473
+ eventTask: counts['eventTask'] > 0,
474
+ change: type
475
+ };
476
+ this.hasTask(this._zone, isEmpty);
477
+ }
478
+ }
479
+ }
480
+ class ZoneTask {
481
+ constructor(type, source, callback, options, scheduleFn, cancelFn) {
482
+ // tslint:disable-next-line:require-internal-with-underscore
483
+ this._zone = null;
484
+ this.runCount = 0;
485
+ // tslint:disable-next-line:require-internal-with-underscore
486
+ this._zoneDelegates = null;
487
+ // tslint:disable-next-line:require-internal-with-underscore
488
+ this._state = 'notScheduled';
489
+ this.type = type;
490
+ this.source = source;
491
+ this.data = options;
492
+ this.scheduleFn = scheduleFn;
493
+ this.cancelFn = cancelFn;
494
+ if (!callback) {
495
+ throw new Error('callback is not defined');
496
+ }
497
+ this.callback = callback;
498
+ const self = this;
499
+ // TODO: @JiaLiPassion options should have interface
500
+ if (type === eventTask && options && options.useG) {
501
+ this.invoke = ZoneTask.invokeTask;
502
+ } else {
503
+ this.invoke = function () {
504
+ return ZoneTask.invokeTask.call(global, self, this, arguments);
505
+ };
506
+ }
507
+ }
508
+ static invokeTask(task, target, args) {
509
+ if (!task) {
510
+ task = this;
511
+ }
512
+ _numberOfNestedTaskFrames++;
513
+ try {
514
+ task.runCount++;
515
+ return task.zone.runTask(task, target, args);
516
+ } finally {
517
+ if (_numberOfNestedTaskFrames == 1) {
518
+ drainMicroTaskQueue();
519
+ }
520
+ _numberOfNestedTaskFrames--;
521
+ }
522
+ }
523
+ get zone() {
524
+ return this._zone;
525
+ }
526
+ get state() {
527
+ return this._state;
528
+ }
529
+ cancelScheduleRequest() {
530
+ this._transitionTo(notScheduled, scheduling);
531
+ }
532
+ // tslint:disable-next-line:require-internal-with-underscore
533
+ _transitionTo(toState, fromState1, fromState2) {
534
+ if (this._state === fromState1 || this._state === fromState2) {
535
+ this._state = toState;
536
+ if (toState == notScheduled) {
537
+ this._zoneDelegates = null;
538
+ }
539
+ } else {
540
+ throw new Error(`${this.type} '${this.source}': can not transition to '${toState}', expecting state '${fromState1}'${fromState2 ? " or '" + fromState2 + "'" : ''}, was '${this._state}'.`);
541
+ }
542
+ }
543
+ toString() {
544
+ if (this.data && typeof this.data.handleId !== 'undefined') {
545
+ return this.data.handleId.toString();
546
+ } else {
547
+ return Object.prototype.toString.call(this);
548
+ }
549
+ }
550
+ // add toJSON method to prevent cyclic error when
551
+ // call JSON.stringify(zoneTask)
552
+ toJSON() {
553
+ return {
554
+ type: this.type,
555
+ state: this.state,
556
+ source: this.source,
557
+ zone: this.zone.name,
558
+ runCount: this.runCount
559
+ };
560
+ }
561
+ }
562
+ //////////////////////////////////////////////////////
563
+ //////////////////////////////////////////////////////
564
+ /// MICROTASK QUEUE
565
+ //////////////////////////////////////////////////////
566
+ //////////////////////////////////////////////////////
567
+ const symbolSetTimeout = __symbol__('setTimeout');
568
+ const symbolPromise = __symbol__('Promise');
569
+ const symbolThen = __symbol__('then');
570
+ let _microTaskQueue = [];
571
+ let _isDrainingMicrotaskQueue = false;
572
+ let nativeMicroTaskQueuePromise;
573
+ function nativeScheduleMicroTask(func) {
574
+ if (!nativeMicroTaskQueuePromise) {
575
+ if (global[symbolPromise]) {
576
+ nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
577
+ }
578
+ }
579
+ if (nativeMicroTaskQueuePromise) {
580
+ let nativeThen = nativeMicroTaskQueuePromise[symbolThen];
581
+ if (!nativeThen) {
582
+ // native Promise is not patchable, we need to use `then` directly
583
+ // issue 1078
584
+ nativeThen = nativeMicroTaskQueuePromise['then'];
585
+ }
586
+ nativeThen.call(nativeMicroTaskQueuePromise, func);
587
+ } else {
588
+ global[symbolSetTimeout](func, 0);
589
+ }
590
+ }
591
+ function scheduleMicroTask(task) {
592
+ // if we are not running in any task, and there has not been anything scheduled
593
+ // we must bootstrap the initial task creation by manually scheduling the drain
594
+ if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
595
+ // We are not running in Task, so we need to kickstart the microtask queue.
596
+ nativeScheduleMicroTask(drainMicroTaskQueue);
597
+ }
598
+ task && _microTaskQueue.push(task);
599
+ }
600
+ function drainMicroTaskQueue() {
601
+ if (!_isDrainingMicrotaskQueue) {
602
+ _isDrainingMicrotaskQueue = true;
603
+ while (_microTaskQueue.length) {
604
+ const queue = _microTaskQueue;
605
+ _microTaskQueue = [];
606
+ for (let i = 0; i < queue.length; i++) {
607
+ const task = queue[i];
608
+ try {
609
+ task.zone.runTask(task, null, null);
610
+ } catch (error) {
611
+ _api.onUnhandledError(error);
612
+ }
613
+ }
614
+ }
615
+ _api.microtaskDrainDone();
616
+ _isDrainingMicrotaskQueue = false;
617
+ }
618
+ }
619
+ //////////////////////////////////////////////////////
620
+ //////////////////////////////////////////////////////
621
+ /// BOOTSTRAP
622
+ //////////////////////////////////////////////////////
623
+ //////////////////////////////////////////////////////
624
+ const NO_ZONE = {
625
+ name: 'NO ZONE'
626
+ };
627
+ const notScheduled = 'notScheduled',
628
+ scheduling = 'scheduling',
629
+ scheduled = 'scheduled',
630
+ running = 'running',
631
+ canceling = 'canceling',
632
+ unknown = 'unknown';
633
+ const microTask = 'microTask',
634
+ macroTask = 'macroTask',
635
+ eventTask = 'eventTask';
636
+ const patches = {};
637
+ const _api = {
638
+ symbol: __symbol__,
639
+ currentZoneFrame: () => _currentZoneFrame,
640
+ onUnhandledError: noop,
641
+ microtaskDrainDone: noop,
642
+ scheduleMicroTask: scheduleMicroTask,
643
+ showUncaughtError: () => !ZoneImpl[__symbol__('ignoreConsoleErrorUncaughtError')],
644
+ patchEventTarget: () => [],
645
+ patchOnProperties: noop,
646
+ patchMethod: () => noop,
647
+ bindArguments: () => [],
648
+ patchThen: () => noop,
649
+ patchMacroTask: () => noop,
650
+ patchEventPrototype: () => noop,
651
+ isIEOrEdge: () => false,
652
+ getGlobalObjects: () => undefined,
653
+ ObjectDefineProperty: () => noop,
654
+ ObjectGetOwnPropertyDescriptor: () => undefined,
655
+ ObjectCreate: () => undefined,
656
+ ArraySlice: () => [],
657
+ patchClass: () => noop,
658
+ wrapWithCurrentZone: () => noop,
659
+ filterProperties: () => [],
660
+ attachOriginToPatched: () => noop,
661
+ _redefineProperty: () => noop,
662
+ patchCallbacks: () => noop,
663
+ nativeScheduleMicroTask: nativeScheduleMicroTask
664
+ };
665
+ let _currentZoneFrame = {
666
+ parent: null,
667
+ zone: new ZoneImpl(null, null)
668
+ };
669
+ let _currentTask = null;
670
+ let _numberOfNestedTaskFrames = 0;
671
+ function noop() {}
672
+ performanceMeasure('Zone', 'Zone');
673
+ return ZoneImpl;
674
+ }
675
+ function loadZone() {
676
+ // if global['Zone'] already exists (maybe zone.js was already loaded or
677
+ // some other lib also registered a global object named Zone), we may need
678
+ // to throw an error, but sometimes user may not want this error.
679
+ // For example,
680
+ // we have two web pages, page1 includes zone.js, page2 doesn't.
681
+ // and the 1st time user load page1 and page2, everything work fine,
682
+ // but when user load page2 again, error occurs because global['Zone'] already exists.
683
+ // so we add a flag to let user choose whether to throw this error or not.
684
+ // By default, if existing Zone is from zone.js, we will not throw the error.
685
+ const global = globalThis;
686
+ const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
687
+ if (global['Zone'] && (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function')) {
688
+ throw new Error('Zone already loaded.');
689
+ }
690
+ // Initialize global `Zone` constant.
691
+ global['Zone'] ??= initZone();
692
+ return global['Zone'];
693
+ }
694
+
695
+ /**
696
+ * Suppress closure compiler errors about unknown 'Zone' variable
697
+ * @fileoverview
698
+ * @suppress {undefinedVars,globalThis,missingRequire}
699
+ */
700
+ // issue #989, to reduce bundle size, use short name
701
+ /** Object.getOwnPropertyDescriptor */
702
+ const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
703
+ /** Object.defineProperty */
704
+ const ObjectDefineProperty = Object.defineProperty;
705
+ /** Object.getPrototypeOf */
706
+ const ObjectGetPrototypeOf = Object.getPrototypeOf;
707
+ /** Object.create */
708
+ const ObjectCreate = Object.create;
709
+ /** Array.prototype.slice */
710
+ const ArraySlice = Array.prototype.slice;
711
+ /** addEventListener string const */
712
+ const ADD_EVENT_LISTENER_STR = 'addEventListener';
713
+ /** removeEventListener string const */
714
+ const REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
715
+ /** zoneSymbol addEventListener */
716
+ const ZONE_SYMBOL_ADD_EVENT_LISTENER = __symbol__(ADD_EVENT_LISTENER_STR);
717
+ /** zoneSymbol removeEventListener */
718
+ const ZONE_SYMBOL_REMOVE_EVENT_LISTENER = __symbol__(REMOVE_EVENT_LISTENER_STR);
719
+ /** true string const */
720
+ const TRUE_STR = 'true';
721
+ /** false string const */
722
+ const FALSE_STR = 'false';
723
+ /** Zone symbol prefix string const. */
724
+ const ZONE_SYMBOL_PREFIX = __symbol__('');
725
+ function wrapWithCurrentZone(callback, source) {
726
+ return Zone.current.wrap(callback, source);
727
+ }
728
+ function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
729
+ return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
730
+ }
731
+ const zoneSymbol = __symbol__;
732
+ const isWindowExists = typeof window !== 'undefined';
733
+ const internalWindow = isWindowExists ? window : undefined;
734
+ const _global = isWindowExists && internalWindow || globalThis;
735
+ const REMOVE_ATTRIBUTE = 'removeAttribute';
736
+ function bindArguments(args, source) {
737
+ for (let i = args.length - 1; i >= 0; i--) {
738
+ if (typeof args[i] === 'function') {
739
+ args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
740
+ }
741
+ }
742
+ return args;
743
+ }
744
+ function patchPrototype(prototype, fnNames) {
745
+ const source = prototype.constructor['name'];
746
+ for (let i = 0; i < fnNames.length; i++) {
747
+ const name = fnNames[i];
748
+ const delegate = prototype[name];
749
+ if (delegate) {
750
+ const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name);
751
+ if (!isPropertyWritable(prototypeDesc)) {
752
+ continue;
753
+ }
754
+ prototype[name] = (delegate => {
755
+ const patched = function () {
756
+ return delegate.apply(this, bindArguments(arguments, source + '.' + name));
757
+ };
758
+ attachOriginToPatched(patched, delegate);
759
+ return patched;
760
+ })(delegate);
761
+ }
762
+ }
763
+ }
764
+ function isPropertyWritable(propertyDesc) {
765
+ if (!propertyDesc) {
766
+ return true;
767
+ }
768
+ if (propertyDesc.writable === false) {
769
+ return false;
770
+ }
771
+ return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
772
+ }
773
+ const isWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
774
+ // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
775
+ // this code.
776
+ const isNode = !('nw' in _global) && typeof _global.process !== 'undefined' && _global.process.toString() === '[object process]';
777
+ const isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
778
+ // we are in electron of nw, so we are both browser and nodejs
779
+ // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
780
+ // this code.
781
+ const isMix = typeof _global.process !== 'undefined' && _global.process.toString() === '[object process]' && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
782
+ const zoneSymbolEventNames$1 = {};
783
+ const enableBeforeunloadSymbol = zoneSymbol('enable_beforeunload');
784
+ const wrapFn = function (event) {
785
+ // https://github.com/angular/zone.js/issues/911, in IE, sometimes
786
+ // event will be undefined, so we need to use window.event
787
+ event = event || _global.event;
788
+ if (!event) {
789
+ return;
790
+ }
791
+ let eventNameSymbol = zoneSymbolEventNames$1[event.type];
792
+ if (!eventNameSymbol) {
793
+ eventNameSymbol = zoneSymbolEventNames$1[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
794
+ }
795
+ const target = this || event.target || _global;
796
+ const listener = target[eventNameSymbol];
797
+ let result;
798
+ if (isBrowser && target === internalWindow && event.type === 'error') {
799
+ // window.onerror have different signature
800
+ // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
801
+ // and onerror callback will prevent default when callback return true
802
+ const errorEvent = event;
803
+ result = listener && listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
804
+ if (result === true) {
805
+ event.preventDefault();
806
+ }
807
+ } else {
808
+ result = listener && listener.apply(this, arguments);
809
+ if (
810
+ // https://github.com/angular/angular/issues/47579
811
+ // https://www.w3.org/TR/2011/WD-html5-20110525/history.html#beforeunloadevent
812
+ // This is the only specific case we should check for. The spec defines that the
813
+ // `returnValue` attribute represents the message to show the user. When the event
814
+ // is created, this attribute must be set to the empty string.
815
+ event.type === 'beforeunload' &&
816
+ // To prevent any breaking changes resulting from this change, given that
817
+ // it was already causing a significant number of failures in G3, we have hidden
818
+ // that behavior behind a global configuration flag. Consumers can enable this
819
+ // flag explicitly if they want the `beforeunload` event to be handled as defined
820
+ // in the specification.
821
+ _global[enableBeforeunloadSymbol] &&
822
+ // The IDL event definition is `attribute DOMString returnValue`, so we check whether
823
+ // `typeof result` is a string.
824
+ typeof result === 'string') {
825
+ event.returnValue = result;
826
+ } else if (result != undefined && !result) {
827
+ event.preventDefault();
828
+ }
829
+ }
830
+ return result;
831
+ };
832
+ function patchProperty(obj, prop, prototype) {
833
+ let desc = ObjectGetOwnPropertyDescriptor(obj, prop);
834
+ if (!desc && prototype) {
835
+ // when patch window object, use prototype to check prop exist or not
836
+ const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
837
+ if (prototypeDesc) {
838
+ desc = {
839
+ enumerable: true,
840
+ configurable: true
841
+ };
842
+ }
843
+ }
844
+ // if the descriptor not exists or is not configurable
845
+ // just return
846
+ if (!desc || !desc.configurable) {
847
+ return;
848
+ }
849
+ const onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
850
+ if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
851
+ return;
852
+ }
853
+ // A property descriptor cannot have getter/setter and be writable
854
+ // deleting the writable and value properties avoids this error:
855
+ //
856
+ // TypeError: property descriptors must not specify a value or be writable when a
857
+ // getter or setter has been specified
858
+ delete desc.writable;
859
+ delete desc.value;
860
+ const originalDescGet = desc.get;
861
+ const originalDescSet = desc.set;
862
+ // slice(2) cuz 'onclick' -> 'click', etc
863
+ const eventName = prop.slice(2);
864
+ let eventNameSymbol = zoneSymbolEventNames$1[eventName];
865
+ if (!eventNameSymbol) {
866
+ eventNameSymbol = zoneSymbolEventNames$1[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
867
+ }
868
+ desc.set = function (newValue) {
869
+ // in some of windows's onproperty callback, this is undefined
870
+ // so we need to check it
871
+ let target = this;
872
+ if (!target && obj === _global) {
873
+ target = _global;
874
+ }
875
+ if (!target) {
876
+ return;
877
+ }
878
+ const previousValue = target[eventNameSymbol];
879
+ if (typeof previousValue === 'function') {
880
+ target.removeEventListener(eventName, wrapFn);
881
+ }
882
+ // issue #978, when onload handler was added before loading zone.js
883
+ // we should remove it with originalDescSet
884
+ originalDescSet && originalDescSet.call(target, null);
885
+ target[eventNameSymbol] = newValue;
886
+ if (typeof newValue === 'function') {
887
+ target.addEventListener(eventName, wrapFn, false);
888
+ }
889
+ };
890
+ // The getter would return undefined for unassigned properties but the default value of an
891
+ // unassigned property is null
892
+ desc.get = function () {
893
+ // in some of windows's onproperty callback, this is undefined
894
+ // so we need to check it
895
+ let target = this;
896
+ if (!target && obj === _global) {
897
+ target = _global;
898
+ }
899
+ if (!target) {
900
+ return null;
901
+ }
902
+ const listener = target[eventNameSymbol];
903
+ if (listener) {
904
+ return listener;
905
+ } else if (originalDescGet) {
906
+ // result will be null when use inline event attribute,
907
+ // such as <button onclick="func();">OK</button>
908
+ // because the onclick function is internal raw uncompiled handler
909
+ // the onclick will be evaluated when first time event was triggered or
910
+ // the property is accessed, https://github.com/angular/zone.js/issues/525
911
+ // so we should use original native get to retrieve the handler
912
+ let value = originalDescGet.call(this);
913
+ if (value) {
914
+ desc.set.call(this, value);
915
+ if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
916
+ target.removeAttribute(prop);
917
+ }
918
+ return value;
919
+ }
920
+ }
921
+ return null;
922
+ };
923
+ ObjectDefineProperty(obj, prop, desc);
924
+ obj[onPropPatchedSymbol] = true;
925
+ }
926
+ function patchOnProperties(obj, properties, prototype) {
927
+ if (properties) {
928
+ for (let i = 0; i < properties.length; i++) {
929
+ patchProperty(obj, 'on' + properties[i], prototype);
930
+ }
931
+ } else {
932
+ const onProperties = [];
933
+ for (const prop in obj) {
934
+ if (prop.slice(0, 2) == 'on') {
935
+ onProperties.push(prop);
936
+ }
937
+ }
938
+ for (let j = 0; j < onProperties.length; j++) {
939
+ patchProperty(obj, onProperties[j], prototype);
940
+ }
941
+ }
942
+ }
943
+ const originalInstanceKey = zoneSymbol('originalInstance');
944
+ // wrap some native API on `window`
945
+ function patchClass(className) {
946
+ const OriginalClass = _global[className];
947
+ if (!OriginalClass) return;
948
+ // keep original class in global
949
+ _global[zoneSymbol(className)] = OriginalClass;
950
+ _global[className] = function () {
951
+ const a = bindArguments(arguments, className);
952
+ switch (a.length) {
953
+ case 0:
954
+ this[originalInstanceKey] = new OriginalClass();
955
+ break;
956
+ case 1:
957
+ this[originalInstanceKey] = new OriginalClass(a[0]);
958
+ break;
959
+ case 2:
960
+ this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
961
+ break;
962
+ case 3:
963
+ this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
964
+ break;
965
+ case 4:
966
+ this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
967
+ break;
968
+ default:
969
+ throw new Error('Arg list too long.');
970
+ }
971
+ };
972
+ // attach original delegate to patched function
973
+ attachOriginToPatched(_global[className], OriginalClass);
974
+ const instance = new OriginalClass(function () {});
975
+ let prop;
976
+ for (prop in instance) {
977
+ // https://bugs.webkit.org/show_bug.cgi?id=44721
978
+ if (className === 'XMLHttpRequest' && prop === 'responseBlob') continue;
979
+ (function (prop) {
980
+ if (typeof instance[prop] === 'function') {
981
+ _global[className].prototype[prop] = function () {
982
+ return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
983
+ };
984
+ } else {
985
+ ObjectDefineProperty(_global[className].prototype, prop, {
986
+ set: function (fn) {
987
+ if (typeof fn === 'function') {
988
+ this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
989
+ // keep callback in wrapped function so we can
990
+ // use it in Function.prototype.toString to return
991
+ // the native one.
992
+ attachOriginToPatched(this[originalInstanceKey][prop], fn);
993
+ } else {
994
+ this[originalInstanceKey][prop] = fn;
995
+ }
996
+ },
997
+ get: function () {
998
+ return this[originalInstanceKey][prop];
999
+ }
1000
+ });
1001
+ }
1002
+ })(prop);
1003
+ }
1004
+ for (prop in OriginalClass) {
1005
+ if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
1006
+ _global[className][prop] = OriginalClass[prop];
1007
+ }
1008
+ }
1009
+ }
1010
+ function patchMethod(target, name, patchFn) {
1011
+ let proto = target;
1012
+ while (proto && !proto.hasOwnProperty(name)) {
1013
+ proto = ObjectGetPrototypeOf(proto);
1014
+ }
1015
+ if (!proto && target[name]) {
1016
+ // somehow we did not find it, but we can see it. This happens on IE for Window properties.
1017
+ proto = target;
1018
+ }
1019
+ const delegateName = zoneSymbol(name);
1020
+ let delegate = null;
1021
+ if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
1022
+ delegate = proto[delegateName] = proto[name];
1023
+ // check whether proto[name] is writable
1024
+ // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
1025
+ const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
1026
+ if (isPropertyWritable(desc)) {
1027
+ const patchDelegate = patchFn(delegate, delegateName, name);
1028
+ proto[name] = function () {
1029
+ return patchDelegate(this, arguments);
1030
+ };
1031
+ attachOriginToPatched(proto[name], delegate);
1032
+ }
1033
+ }
1034
+ return delegate;
1035
+ }
1036
+ // TODO: @JiaLiPassion, support cancel task later if necessary
1037
+ function patchMacroTask(obj, funcName, metaCreator) {
1038
+ let setNative = null;
1039
+ function scheduleTask(task) {
1040
+ const data = task.data;
1041
+ data.args[data.cbIdx] = function () {
1042
+ task.invoke.apply(this, arguments);
1043
+ };
1044
+ setNative.apply(data.target, data.args);
1045
+ return task;
1046
+ }
1047
+ setNative = patchMethod(obj, funcName, delegate => function (self, args) {
1048
+ const meta = metaCreator(self, args);
1049
+ if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
1050
+ return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
1051
+ } else {
1052
+ // cause an error by calling it directly.
1053
+ return delegate.apply(self, args);
1054
+ }
1055
+ });
1056
+ }
1057
+ function attachOriginToPatched(patched, original) {
1058
+ patched[zoneSymbol('OriginalDelegate')] = original;
1059
+ }
1060
+ let isDetectedIEOrEdge = false;
1061
+ let ieOrEdge = false;
1062
+ function isIE() {
1063
+ try {
1064
+ const ua = internalWindow.navigator.userAgent;
1065
+ if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
1066
+ return true;
1067
+ }
1068
+ } catch (error) {}
1069
+ return false;
1070
+ }
1071
+ function isIEOrEdge() {
1072
+ if (isDetectedIEOrEdge) {
1073
+ return ieOrEdge;
1074
+ }
1075
+ isDetectedIEOrEdge = true;
1076
+ try {
1077
+ const ua = internalWindow.navigator.userAgent;
1078
+ if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
1079
+ ieOrEdge = true;
1080
+ }
1081
+ } catch (error) {}
1082
+ return ieOrEdge;
1083
+ }
1084
+ function isFunction(value) {
1085
+ return typeof value === 'function';
1086
+ }
1087
+ function isNumber(value) {
1088
+ return typeof value === 'number';
1089
+ }
1090
+
1091
+ /**
1092
+ * @fileoverview
1093
+ * @suppress {missingRequire}
1094
+ */
1095
+ // Note that passive event listeners are now supported by most modern browsers,
1096
+ // including Chrome, Firefox, Safari, and Edge. There's a pending change that
1097
+ // would remove support for legacy browsers by zone.js. Removing `passiveSupported`
1098
+ // from the codebase will reduce the final code size for existing apps that still use zone.js.
1099
+ let passiveSupported = false;
1100
+ if (typeof window !== 'undefined') {
1101
+ try {
1102
+ const options = Object.defineProperty({}, 'passive', {
1103
+ get: function () {
1104
+ passiveSupported = true;
1105
+ }
1106
+ });
1107
+ // Note: We pass the `options` object as the event handler too. This is not compatible with the
1108
+ // signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
1109
+ // without an actual handler.
1110
+ window.addEventListener('test', options, options);
1111
+ window.removeEventListener('test', options, options);
1112
+ } catch (err) {
1113
+ passiveSupported = false;
1114
+ }
1115
+ }
1116
+ // an identifier to tell ZoneTask do not create a new invoke closure
1117
+ const OPTIMIZED_ZONE_EVENT_TASK_DATA = {
1118
+ useG: true
1119
+ };
1120
+ const zoneSymbolEventNames = {};
1121
+ const globalSources = {};
1122
+ const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
1123
+ const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
1124
+ function prepareEventNames(eventName, eventNameToString) {
1125
+ const falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
1126
+ const trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
1127
+ const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
1128
+ const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
1129
+ zoneSymbolEventNames[eventName] = {};
1130
+ zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
1131
+ zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
1132
+ }
1133
+ function patchEventTarget(_global, api, apis, patchOptions) {
1134
+ const ADD_EVENT_LISTENER = patchOptions && patchOptions.add || ADD_EVENT_LISTENER_STR;
1135
+ const REMOVE_EVENT_LISTENER = patchOptions && patchOptions.rm || REMOVE_EVENT_LISTENER_STR;
1136
+ const LISTENERS_EVENT_LISTENER = patchOptions && patchOptions.listeners || 'eventListeners';
1137
+ const REMOVE_ALL_LISTENERS_EVENT_LISTENER = patchOptions && patchOptions.rmAll || 'removeAllListeners';
1138
+ const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
1139
+ const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
1140
+ const PREPEND_EVENT_LISTENER = 'prependListener';
1141
+ const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
1142
+ const invokeTask = function (task, target, event) {
1143
+ // for better performance, check isRemoved which is set
1144
+ // by removeEventListener
1145
+ if (task.isRemoved) {
1146
+ return;
1147
+ }
1148
+ const delegate = task.callback;
1149
+ if (typeof delegate === 'object' && delegate.handleEvent) {
1150
+ // create the bind version of handleEvent when invoke
1151
+ task.callback = event => delegate.handleEvent(event);
1152
+ task.originalDelegate = delegate;
1153
+ }
1154
+ // invoke static task.invoke
1155
+ // need to try/catch error here, otherwise, the error in one event listener
1156
+ // will break the executions of the other event listeners. Also error will
1157
+ // not remove the event listener when `once` options is true.
1158
+ let error;
1159
+ try {
1160
+ task.invoke(task, target, [event]);
1161
+ } catch (err) {
1162
+ error = err;
1163
+ }
1164
+ const options = task.options;
1165
+ if (options && typeof options === 'object' && options.once) {
1166
+ // if options.once is true, after invoke once remove listener here
1167
+ // only browser need to do this, nodejs eventEmitter will cal removeListener
1168
+ // inside EventEmitter.once
1169
+ const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
1170
+ target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
1171
+ }
1172
+ return error;
1173
+ };
1174
+ function globalCallback(context, event, isCapture) {
1175
+ // https://github.com/angular/zone.js/issues/911, in IE, sometimes
1176
+ // event will be undefined, so we need to use window.event
1177
+ event = event || _global.event;
1178
+ if (!event) {
1179
+ return;
1180
+ }
1181
+ // event.target is needed for Samsung TV and SourceBuffer
1182
+ // || global is needed https://github.com/angular/zone.js/issues/190
1183
+ const target = context || event.target || _global;
1184
+ const tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
1185
+ if (tasks) {
1186
+ const errors = [];
1187
+ // invoke all tasks which attached to current target with given event.type and capture = false
1188
+ // for performance concern, if task.length === 1, just invoke
1189
+ if (tasks.length === 1) {
1190
+ const err = invokeTask(tasks[0], target, event);
1191
+ err && errors.push(err);
1192
+ } else {
1193
+ // https://github.com/angular/zone.js/issues/836
1194
+ // copy the tasks array before invoke, to avoid
1195
+ // the callback will remove itself or other listener
1196
+ const copyTasks = tasks.slice();
1197
+ for (let i = 0; i < copyTasks.length; i++) {
1198
+ if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
1199
+ break;
1200
+ }
1201
+ const err = invokeTask(copyTasks[i], target, event);
1202
+ err && errors.push(err);
1203
+ }
1204
+ }
1205
+ // Since there is only one error, we don't need to schedule microTask
1206
+ // to throw the error.
1207
+ if (errors.length === 1) {
1208
+ throw errors[0];
1209
+ } else {
1210
+ for (let i = 0; i < errors.length; i++) {
1211
+ const err = errors[i];
1212
+ api.nativeScheduleMicroTask(() => {
1213
+ throw err;
1214
+ });
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+ // global shared zoneAwareCallback to handle all event callback with capture = false
1220
+ const globalZoneAwareCallback = function (event) {
1221
+ return globalCallback(this, event, false);
1222
+ };
1223
+ // global shared zoneAwareCallback to handle all event callback with capture = true
1224
+ const globalZoneAwareCaptureCallback = function (event) {
1225
+ return globalCallback(this, event, true);
1226
+ };
1227
+ function patchEventTargetMethods(obj, patchOptions) {
1228
+ if (!obj) {
1229
+ return false;
1230
+ }
1231
+ let useGlobalCallback = true;
1232
+ if (patchOptions && patchOptions.useG !== undefined) {
1233
+ useGlobalCallback = patchOptions.useG;
1234
+ }
1235
+ const validateHandler = patchOptions && patchOptions.vh;
1236
+ let checkDuplicate = true;
1237
+ if (patchOptions && patchOptions.chkDup !== undefined) {
1238
+ checkDuplicate = patchOptions.chkDup;
1239
+ }
1240
+ let returnTarget = false;
1241
+ if (patchOptions && patchOptions.rt !== undefined) {
1242
+ returnTarget = patchOptions.rt;
1243
+ }
1244
+ let proto = obj;
1245
+ while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
1246
+ proto = ObjectGetPrototypeOf(proto);
1247
+ }
1248
+ if (!proto && obj[ADD_EVENT_LISTENER]) {
1249
+ // somehow we did not find it, but we can see it. This happens on IE for Window properties.
1250
+ proto = obj;
1251
+ }
1252
+ if (!proto) {
1253
+ return false;
1254
+ }
1255
+ if (proto[zoneSymbolAddEventListener]) {
1256
+ return false;
1257
+ }
1258
+ const eventNameToString = patchOptions && patchOptions.eventNameToString;
1259
+ // We use a shared global `taskData` to pass data for `scheduleEventTask`,
1260
+ // eliminating the need to create a new object solely for passing data.
1261
+ // WARNING: This object has a static lifetime, meaning it is not created
1262
+ // each time `addEventListener` is called. It is instantiated only once
1263
+ // and captured by reference inside the `addEventListener` and
1264
+ // `removeEventListener` functions. Do not add any new properties to this
1265
+ // object, as doing so would necessitate maintaining the information
1266
+ // between `addEventListener` calls.
1267
+ const taskData = {};
1268
+ const nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
1269
+ const nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] = proto[REMOVE_EVENT_LISTENER];
1270
+ const nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] = proto[LISTENERS_EVENT_LISTENER];
1271
+ const nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] = proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
1272
+ let nativePrependEventListener;
1273
+ if (patchOptions && patchOptions.prepend) {
1274
+ nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] = proto[patchOptions.prepend];
1275
+ }
1276
+ /**
1277
+ * This util function will build an option object with passive option
1278
+ * to handle all possible input from the user.
1279
+ */
1280
+ function buildEventListenerOptions(options, passive) {
1281
+ if (!passiveSupported && typeof options === 'object' && options) {
1282
+ // doesn't support passive but user want to pass an object as options.
1283
+ // this will not work on some old browser, so we just pass a boolean
1284
+ // as useCapture parameter
1285
+ return !!options.capture;
1286
+ }
1287
+ if (!passiveSupported || !passive) {
1288
+ return options;
1289
+ }
1290
+ if (typeof options === 'boolean') {
1291
+ return {
1292
+ capture: options,
1293
+ passive: true
1294
+ };
1295
+ }
1296
+ if (!options) {
1297
+ return {
1298
+ passive: true
1299
+ };
1300
+ }
1301
+ if (typeof options === 'object' && options.passive !== false) {
1302
+ return {
1303
+ ...options,
1304
+ passive: true
1305
+ };
1306
+ }
1307
+ return options;
1308
+ }
1309
+ const customScheduleGlobal = function (task) {
1310
+ // if there is already a task for the eventName + capture,
1311
+ // just return, because we use the shared globalZoneAwareCallback here.
1312
+ if (taskData.isExisting) {
1313
+ return;
1314
+ }
1315
+ return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
1316
+ };
1317
+ /**
1318
+ * In the context of events and listeners, this function will be
1319
+ * called at the end by `cancelTask`, which, in turn, calls `task.cancelFn`.
1320
+ * Cancelling a task is primarily used to remove event listeners from
1321
+ * the task target.
1322
+ */
1323
+ const customCancelGlobal = function (task) {
1324
+ // if task is not marked as isRemoved, this call is directly
1325
+ // from Zone.prototype.cancelTask, we should remove the task
1326
+ // from tasksList of target first
1327
+ if (!task.isRemoved) {
1328
+ const symbolEventNames = zoneSymbolEventNames[task.eventName];
1329
+ let symbolEventName;
1330
+ if (symbolEventNames) {
1331
+ symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
1332
+ }
1333
+ const existingTasks = symbolEventName && task.target[symbolEventName];
1334
+ if (existingTasks) {
1335
+ for (let i = 0; i < existingTasks.length; i++) {
1336
+ const existingTask = existingTasks[i];
1337
+ if (existingTask === task) {
1338
+ existingTasks.splice(i, 1);
1339
+ // set isRemoved to data for faster invokeTask check
1340
+ task.isRemoved = true;
1341
+ if (task.removeAbortListener) {
1342
+ task.removeAbortListener();
1343
+ task.removeAbortListener = null;
1344
+ }
1345
+ if (existingTasks.length === 0) {
1346
+ // all tasks for the eventName + capture have gone,
1347
+ // remove globalZoneAwareCallback and remove the task cache from target
1348
+ task.allRemoved = true;
1349
+ task.target[symbolEventName] = null;
1350
+ }
1351
+ break;
1352
+ }
1353
+ }
1354
+ }
1355
+ }
1356
+ // if all tasks for the eventName + capture have gone,
1357
+ // we will really remove the global event callback,
1358
+ // if not, return
1359
+ if (!task.allRemoved) {
1360
+ return;
1361
+ }
1362
+ return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
1363
+ };
1364
+ const customScheduleNonGlobal = function (task) {
1365
+ return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
1366
+ };
1367
+ const customSchedulePrepend = function (task) {
1368
+ return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
1369
+ };
1370
+ const customCancelNonGlobal = function (task) {
1371
+ return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
1372
+ };
1373
+ const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
1374
+ const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
1375
+ const compareTaskCallbackVsDelegate = function (task, delegate) {
1376
+ const typeOfDelegate = typeof delegate;
1377
+ return typeOfDelegate === 'function' && task.callback === delegate || typeOfDelegate === 'object' && task.originalDelegate === delegate;
1378
+ };
1379
+ const compare = patchOptions && patchOptions.diff ? patchOptions.diff : compareTaskCallbackVsDelegate;
1380
+ const unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
1381
+ const passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
1382
+ function copyEventListenerOptions(options) {
1383
+ if (typeof options === 'object' && options !== null) {
1384
+ // We need to destructure the target `options` object since it may
1385
+ // be frozen or sealed (possibly provided implicitly by a third-party
1386
+ // library), or its properties may be readonly.
1387
+ const newOptions = {
1388
+ ...options
1389
+ };
1390
+ // The `signal` option was recently introduced, which caused regressions in
1391
+ // third-party scenarios where `AbortController` was directly provided to
1392
+ // `addEventListener` as options. For instance, in cases like
1393
+ // `document.addEventListener('keydown', callback, abortControllerInstance)`,
1394
+ // which is valid because `AbortController` includes a `signal` getter, spreading
1395
+ // `{...options}` wouldn't copy the `signal`. Additionally, using `Object.create`
1396
+ // isn't feasible since `AbortController` is a built-in object type, and attempting
1397
+ // to create a new object directly with it as the prototype might result in
1398
+ // unexpected behavior.
1399
+ if (options.signal) {
1400
+ newOptions.signal = options.signal;
1401
+ }
1402
+ return newOptions;
1403
+ }
1404
+ return options;
1405
+ }
1406
+ const makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget = false, prepend = false) {
1407
+ return function () {
1408
+ const target = this || _global;
1409
+ let eventName = arguments[0];
1410
+ if (patchOptions && patchOptions.transferEventName) {
1411
+ eventName = patchOptions.transferEventName(eventName);
1412
+ }
1413
+ let delegate = arguments[1];
1414
+ if (!delegate) {
1415
+ return nativeListener.apply(this, arguments);
1416
+ }
1417
+ if (isNode && eventName === 'uncaughtException') {
1418
+ // don't patch uncaughtException of nodejs to prevent endless loop
1419
+ return nativeListener.apply(this, arguments);
1420
+ }
1421
+ // don't create the bind delegate function for handleEvent
1422
+ // case here to improve addEventListener performance
1423
+ // we will create the bind delegate when invoke
1424
+ let isHandleEvent = false;
1425
+ if (typeof delegate !== 'function') {
1426
+ if (!delegate.handleEvent) {
1427
+ return nativeListener.apply(this, arguments);
1428
+ }
1429
+ isHandleEvent = true;
1430
+ }
1431
+ if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
1432
+ return;
1433
+ }
1434
+ const passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
1435
+ const options = copyEventListenerOptions(buildEventListenerOptions(arguments[2], passive));
1436
+ const signal = options?.signal;
1437
+ if (signal?.aborted) {
1438
+ // the signal is an aborted one, just return without attaching the event listener.
1439
+ return;
1440
+ }
1441
+ if (unpatchedEvents) {
1442
+ // check unpatched list
1443
+ for (let i = 0; i < unpatchedEvents.length; i++) {
1444
+ if (eventName === unpatchedEvents[i]) {
1445
+ if (passive) {
1446
+ return nativeListener.call(target, eventName, delegate, options);
1447
+ } else {
1448
+ return nativeListener.apply(this, arguments);
1449
+ }
1450
+ }
1451
+ }
1452
+ }
1453
+ const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
1454
+ const once = options && typeof options === 'object' ? options.once : false;
1455
+ const zone = Zone.current;
1456
+ let symbolEventNames = zoneSymbolEventNames[eventName];
1457
+ if (!symbolEventNames) {
1458
+ prepareEventNames(eventName, eventNameToString);
1459
+ symbolEventNames = zoneSymbolEventNames[eventName];
1460
+ }
1461
+ const symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
1462
+ let existingTasks = target[symbolEventName];
1463
+ let isExisting = false;
1464
+ if (existingTasks) {
1465
+ // already have task registered
1466
+ isExisting = true;
1467
+ if (checkDuplicate) {
1468
+ for (let i = 0; i < existingTasks.length; i++) {
1469
+ if (compare(existingTasks[i], delegate)) {
1470
+ // same callback, same capture, same event name, just return
1471
+ return;
1472
+ }
1473
+ }
1474
+ }
1475
+ } else {
1476
+ existingTasks = target[symbolEventName] = [];
1477
+ }
1478
+ let source;
1479
+ const constructorName = target.constructor['name'];
1480
+ const targetSource = globalSources[constructorName];
1481
+ if (targetSource) {
1482
+ source = targetSource[eventName];
1483
+ }
1484
+ if (!source) {
1485
+ source = constructorName + addSource + (eventNameToString ? eventNameToString(eventName) : eventName);
1486
+ }
1487
+ // In the code below, `options` should no longer be reassigned; instead, it
1488
+ // should only be mutated. This is because we pass that object to the native
1489
+ // `addEventListener`.
1490
+ // It's generally recommended to use the same object reference for options.
1491
+ // This ensures consistency and avoids potential issues.
1492
+ taskData.options = options;
1493
+ if (once) {
1494
+ // When using `addEventListener` with the `once` option, we don't pass
1495
+ // the `once` option directly to the native `addEventListener` method.
1496
+ // Instead, we keep the `once` setting and handle it ourselves.
1497
+ taskData.options.once = false;
1498
+ }
1499
+ taskData.target = target;
1500
+ taskData.capture = capture;
1501
+ taskData.eventName = eventName;
1502
+ taskData.isExisting = isExisting;
1503
+ const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
1504
+ // keep taskData into data to allow onScheduleEventTask to access the task information
1505
+ if (data) {
1506
+ data.taskData = taskData;
1507
+ }
1508
+ if (signal) {
1509
+ // When using `addEventListener` with the `signal` option, we don't pass
1510
+ // the `signal` option directly to the native `addEventListener` method.
1511
+ // Instead, we keep the `signal` setting and handle it ourselves.
1512
+ taskData.options.signal = undefined;
1513
+ }
1514
+ // The `scheduleEventTask` function will ultimately call `customScheduleGlobal`,
1515
+ // which in turn calls the native `addEventListener`. This is why `taskData.options`
1516
+ // is updated before scheduling the task, as `customScheduleGlobal` uses
1517
+ // `taskData.options` to pass it to the native `addEventListener`.
1518
+ const task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
1519
+ if (signal) {
1520
+ // after task is scheduled, we need to store the signal back to task.options
1521
+ taskData.options.signal = signal;
1522
+ // Wrapping `task` in a weak reference would not prevent memory leaks. Weak references are
1523
+ // primarily used for preventing strong references cycles. `onAbort` is always reachable
1524
+ // as it's an event listener, so its closure retains a strong reference to the `task`.
1525
+ const onAbort = () => task.zone.cancelTask(task);
1526
+ nativeListener.call(signal, 'abort', onAbort, {
1527
+ once: true
1528
+ });
1529
+ // We need to remove the `abort` listener when the event listener is going to be removed,
1530
+ // as it creates a closure that captures `task`. This closure retains a reference to the
1531
+ // `task` object even after it goes out of scope, preventing `task` from being garbage
1532
+ // collected.
1533
+ task.removeAbortListener = () => signal.removeEventListener('abort', onAbort);
1534
+ }
1535
+ // should clear taskData.target to avoid memory leak
1536
+ // issue, https://github.com/angular/angular/issues/20442
1537
+ taskData.target = null;
1538
+ // need to clear up taskData because it is a global object
1539
+ if (data) {
1540
+ data.taskData = null;
1541
+ }
1542
+ // have to save those information to task in case
1543
+ // application may call task.zone.cancelTask() directly
1544
+ if (once) {
1545
+ taskData.options.once = true;
1546
+ }
1547
+ if (!(!passiveSupported && typeof task.options === 'boolean')) {
1548
+ // if not support passive, and we pass an option object
1549
+ // to addEventListener, we should save the options to task
1550
+ task.options = options;
1551
+ }
1552
+ task.target = target;
1553
+ task.capture = capture;
1554
+ task.eventName = eventName;
1555
+ if (isHandleEvent) {
1556
+ // save original delegate for compare to check duplicate
1557
+ task.originalDelegate = delegate;
1558
+ }
1559
+ if (!prepend) {
1560
+ existingTasks.push(task);
1561
+ } else {
1562
+ existingTasks.unshift(task);
1563
+ }
1564
+ if (returnTarget) {
1565
+ return target;
1566
+ }
1567
+ };
1568
+ };
1569
+ proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
1570
+ if (nativePrependEventListener) {
1571
+ proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
1572
+ }
1573
+ proto[REMOVE_EVENT_LISTENER] = function () {
1574
+ const target = this || _global;
1575
+ let eventName = arguments[0];
1576
+ if (patchOptions && patchOptions.transferEventName) {
1577
+ eventName = patchOptions.transferEventName(eventName);
1578
+ }
1579
+ const options = arguments[2];
1580
+ const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
1581
+ const delegate = arguments[1];
1582
+ if (!delegate) {
1583
+ return nativeRemoveEventListener.apply(this, arguments);
1584
+ }
1585
+ if (validateHandler && !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
1586
+ return;
1587
+ }
1588
+ const symbolEventNames = zoneSymbolEventNames[eventName];
1589
+ let symbolEventName;
1590
+ if (symbolEventNames) {
1591
+ symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
1592
+ }
1593
+ const existingTasks = symbolEventName && target[symbolEventName];
1594
+ // `existingTasks` may not exist if the `addEventListener` was called before
1595
+ // it was patched by zone.js. Please refer to the attached issue for
1596
+ // clarification, particularly after the `if` condition, before calling
1597
+ // the native `removeEventListener`.
1598
+ if (existingTasks) {
1599
+ for (let i = 0; i < existingTasks.length; i++) {
1600
+ const existingTask = existingTasks[i];
1601
+ if (compare(existingTask, delegate)) {
1602
+ existingTasks.splice(i, 1);
1603
+ // set isRemoved to data for faster invokeTask check
1604
+ existingTask.isRemoved = true;
1605
+ if (existingTasks.length === 0) {
1606
+ // all tasks for the eventName + capture have gone,
1607
+ // remove globalZoneAwareCallback and remove the task cache from target
1608
+ existingTask.allRemoved = true;
1609
+ target[symbolEventName] = null;
1610
+ // in the target, we have an event listener which is added by on_property
1611
+ // such as target.onclick = function() {}, so we need to clear this internal
1612
+ // property too if all delegates with capture=false were removed
1613
+ // https:// github.com/angular/angular/issues/31643
1614
+ // https://github.com/angular/angular/issues/54581
1615
+ if (!capture && typeof eventName === 'string') {
1616
+ const onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
1617
+ target[onPropertySymbol] = null;
1618
+ }
1619
+ }
1620
+ // In all other conditions, when `addEventListener` is called after being
1621
+ // patched by zone.js, we would always find an event task on the `EventTarget`.
1622
+ // This will trigger `cancelFn` on the `existingTask`, leading to `customCancelGlobal`,
1623
+ // which ultimately removes an event listener and cleans up the abort listener
1624
+ // (if an `AbortSignal` was provided when scheduling a task).
1625
+ existingTask.zone.cancelTask(existingTask);
1626
+ if (returnTarget) {
1627
+ return target;
1628
+ }
1629
+ return;
1630
+ }
1631
+ }
1632
+ }
1633
+ // https://github.com/angular/zone.js/issues/930
1634
+ // We may encounter a situation where the `addEventListener` was
1635
+ // called on the event target before zone.js is loaded, resulting
1636
+ // in no task being stored on the event target due to its invocation
1637
+ // of the native implementation. In this scenario, we simply need to
1638
+ // invoke the native `removeEventListener`.
1639
+ return nativeRemoveEventListener.apply(this, arguments);
1640
+ };
1641
+ proto[LISTENERS_EVENT_LISTENER] = function () {
1642
+ const target = this || _global;
1643
+ let eventName = arguments[0];
1644
+ if (patchOptions && patchOptions.transferEventName) {
1645
+ eventName = patchOptions.transferEventName(eventName);
1646
+ }
1647
+ const listeners = [];
1648
+ const tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
1649
+ for (let i = 0; i < tasks.length; i++) {
1650
+ const task = tasks[i];
1651
+ let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
1652
+ listeners.push(delegate);
1653
+ }
1654
+ return listeners;
1655
+ };
1656
+ proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
1657
+ const target = this || _global;
1658
+ let eventName = arguments[0];
1659
+ if (!eventName) {
1660
+ const keys = Object.keys(target);
1661
+ for (let i = 0; i < keys.length; i++) {
1662
+ const prop = keys[i];
1663
+ const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
1664
+ let evtName = match && match[1];
1665
+ // in nodejs EventEmitter, removeListener event is
1666
+ // used for monitoring the removeListener call,
1667
+ // so just keep removeListener eventListener until
1668
+ // all other eventListeners are removed
1669
+ if (evtName && evtName !== 'removeListener') {
1670
+ this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
1671
+ }
1672
+ }
1673
+ // remove removeListener listener finally
1674
+ this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
1675
+ } else {
1676
+ if (patchOptions && patchOptions.transferEventName) {
1677
+ eventName = patchOptions.transferEventName(eventName);
1678
+ }
1679
+ const symbolEventNames = zoneSymbolEventNames[eventName];
1680
+ if (symbolEventNames) {
1681
+ const symbolEventName = symbolEventNames[FALSE_STR];
1682
+ const symbolCaptureEventName = symbolEventNames[TRUE_STR];
1683
+ const tasks = target[symbolEventName];
1684
+ const captureTasks = target[symbolCaptureEventName];
1685
+ if (tasks) {
1686
+ const removeTasks = tasks.slice();
1687
+ for (let i = 0; i < removeTasks.length; i++) {
1688
+ const task = removeTasks[i];
1689
+ let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
1690
+ this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
1691
+ }
1692
+ }
1693
+ if (captureTasks) {
1694
+ const removeTasks = captureTasks.slice();
1695
+ for (let i = 0; i < removeTasks.length; i++) {
1696
+ const task = removeTasks[i];
1697
+ let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
1698
+ this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
1699
+ }
1700
+ }
1701
+ }
1702
+ }
1703
+ if (returnTarget) {
1704
+ return this;
1705
+ }
1706
+ };
1707
+ // for native toString patch
1708
+ attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
1709
+ attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
1710
+ if (nativeRemoveAllListeners) {
1711
+ attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
1712
+ }
1713
+ if (nativeListeners) {
1714
+ attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
1715
+ }
1716
+ return true;
1717
+ }
1718
+ let results = [];
1719
+ for (let i = 0; i < apis.length; i++) {
1720
+ results[i] = patchEventTargetMethods(apis[i], patchOptions);
1721
+ }
1722
+ return results;
1723
+ }
1724
+ function findEventTasks(target, eventName) {
1725
+ if (!eventName) {
1726
+ const foundTasks = [];
1727
+ for (let prop in target) {
1728
+ const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
1729
+ let evtName = match && match[1];
1730
+ if (evtName && (!eventName || evtName === eventName)) {
1731
+ const tasks = target[prop];
1732
+ if (tasks) {
1733
+ for (let i = 0; i < tasks.length; i++) {
1734
+ foundTasks.push(tasks[i]);
1735
+ }
1736
+ }
1737
+ }
1738
+ }
1739
+ return foundTasks;
1740
+ }
1741
+ let symbolEventName = zoneSymbolEventNames[eventName];
1742
+ if (!symbolEventName) {
1743
+ prepareEventNames(eventName);
1744
+ symbolEventName = zoneSymbolEventNames[eventName];
1745
+ }
1746
+ const captureFalseTasks = target[symbolEventName[FALSE_STR]];
1747
+ const captureTrueTasks = target[symbolEventName[TRUE_STR]];
1748
+ if (!captureFalseTasks) {
1749
+ return captureTrueTasks ? captureTrueTasks.slice() : [];
1750
+ } else {
1751
+ return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) : captureFalseTasks.slice();
1752
+ }
1753
+ }
1754
+ function patchEventPrototype(global, api) {
1755
+ const Event = global['Event'];
1756
+ if (Event && Event.prototype) {
1757
+ api.patchMethod(Event.prototype, 'stopImmediatePropagation', delegate => function (self, args) {
1758
+ self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
1759
+ // we need to call the native stopImmediatePropagation
1760
+ // in case in some hybrid application, some part of
1761
+ // application will be controlled by zone, some are not
1762
+ delegate && delegate.apply(self, args);
1763
+ });
1764
+ }
1765
+ }
1766
+
1767
+ /**
1768
+ * @fileoverview
1769
+ * @suppress {missingRequire}
1770
+ */
1771
+ function patchQueueMicrotask(global, api) {
1772
+ api.patchMethod(global, 'queueMicrotask', delegate => {
1773
+ return function (self, args) {
1774
+ Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
1775
+ };
1776
+ });
1777
+ }
1778
+
1779
+ /**
1780
+ * @fileoverview
1781
+ * @suppress {missingRequire}
1782
+ */
1783
+ const taskSymbol = zoneSymbol('zoneTask');
1784
+ function patchTimer(window, setName, cancelName, nameSuffix) {
1785
+ let setNative = null;
1786
+ let clearNative = null;
1787
+ setName += nameSuffix;
1788
+ cancelName += nameSuffix;
1789
+ const tasksByHandleId = {};
1790
+ function scheduleTask(task) {
1791
+ const data = task.data;
1792
+ data.args[0] = function () {
1793
+ return task.invoke.apply(this, arguments);
1794
+ };
1795
+ const handleOrId = setNative.apply(window, data.args);
1796
+ // Whlist on Node.js when get can the ID by using `[Symbol.toPrimitive]()` we do
1797
+ // to this so that we do not cause potentally leaks when using `setTimeout`
1798
+ // since this can be periodic when using `.refresh`.
1799
+ if (isNumber(handleOrId)) {
1800
+ data.handleId = handleOrId;
1801
+ } else {
1802
+ data.handle = handleOrId;
1803
+ // On Node.js a timeout and interval can be restarted over and over again by using the `.refresh` method.
1804
+ data.isRefreshable = isFunction(handleOrId.refresh);
1805
+ }
1806
+ return task;
1807
+ }
1808
+ function clearTask(task) {
1809
+ const {
1810
+ handle,
1811
+ handleId
1812
+ } = task.data;
1813
+ return clearNative.call(window, handle ?? handleId);
1814
+ }
1815
+ setNative = patchMethod(window, setName, delegate => function (self, args) {
1816
+ if (isFunction(args[0])) {
1817
+ const options = {
1818
+ isRefreshable: false,
1819
+ isPeriodic: nameSuffix === 'Interval',
1820
+ delay: nameSuffix === 'Timeout' || nameSuffix === 'Interval' ? args[1] || 0 : undefined,
1821
+ args: args
1822
+ };
1823
+ const callback = args[0];
1824
+ args[0] = function timer() {
1825
+ try {
1826
+ return callback.apply(this, arguments);
1827
+ } finally {
1828
+ // issue-934, task will be cancelled
1829
+ // even it is a periodic task such as
1830
+ // setInterval
1831
+ // https://github.com/angular/angular/issues/40387
1832
+ // Cleanup tasksByHandleId should be handled before scheduleTask
1833
+ // Since some zoneSpec may intercept and doesn't trigger
1834
+ // scheduleFn(scheduleTask) provided here.
1835
+ const {
1836
+ handle,
1837
+ handleId,
1838
+ isPeriodic,
1839
+ isRefreshable
1840
+ } = options;
1841
+ if (!isPeriodic && !isRefreshable) {
1842
+ if (handleId) {
1843
+ // in non-nodejs env, we remove timerId
1844
+ // from local cache
1845
+ delete tasksByHandleId[handleId];
1846
+ } else if (handle) {
1847
+ // Node returns complex objects as handleIds
1848
+ // we remove task reference from timer object
1849
+ handle[taskSymbol] = null;
1850
+ }
1851
+ }
1852
+ }
1853
+ };
1854
+ const task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
1855
+ if (!task) {
1856
+ return task;
1857
+ }
1858
+ // Node.js must additionally support the ref and unref functions.
1859
+ const {
1860
+ handleId,
1861
+ handle,
1862
+ isRefreshable,
1863
+ isPeriodic
1864
+ } = task.data;
1865
+ if (handleId) {
1866
+ // for non nodejs env, we save handleId: task
1867
+ // mapping in local cache for clearTimeout
1868
+ tasksByHandleId[handleId] = task;
1869
+ } else if (handle) {
1870
+ // for nodejs env, we save task
1871
+ // reference in timerId Object for clearTimeout
1872
+ handle[taskSymbol] = task;
1873
+ if (isRefreshable && !isPeriodic) {
1874
+ const originalRefresh = handle.refresh;
1875
+ handle.refresh = function () {
1876
+ const {
1877
+ zone,
1878
+ state
1879
+ } = task;
1880
+ if (state === 'notScheduled') {
1881
+ task._state = 'scheduled';
1882
+ zone._updateTaskCount(task, 1);
1883
+ } else if (state === 'running') {
1884
+ task._state = 'scheduling';
1885
+ }
1886
+ return originalRefresh.call(this);
1887
+ };
1888
+ }
1889
+ }
1890
+ return handle ?? handleId ?? task;
1891
+ } else {
1892
+ // cause an error by calling it directly.
1893
+ return delegate.apply(window, args);
1894
+ }
1895
+ });
1896
+ clearNative = patchMethod(window, cancelName, delegate => function (self, args) {
1897
+ const id = args[0];
1898
+ let task;
1899
+ if (isNumber(id)) {
1900
+ // non nodejs env.
1901
+ task = tasksByHandleId[id];
1902
+ delete tasksByHandleId[id];
1903
+ } else {
1904
+ // nodejs env ?? other environments.
1905
+ task = id?.[taskSymbol];
1906
+ if (task) {
1907
+ id[taskSymbol] = null;
1908
+ } else {
1909
+ task = id;
1910
+ }
1911
+ }
1912
+ if (task?.type) {
1913
+ if (task.cancelFn) {
1914
+ // Do not cancel already canceled functions
1915
+ task.zone.cancelTask(task);
1916
+ }
1917
+ } else {
1918
+ // cause an error by calling it directly.
1919
+ delegate.apply(window, args);
1920
+ }
1921
+ });
1922
+ }
1923
+ function patchCustomElements(_global, api) {
1924
+ const {
1925
+ isBrowser,
1926
+ isMix
1927
+ } = api.getGlobalObjects();
1928
+ if (!isBrowser && !isMix || !_global['customElements'] || !('customElements' in _global)) {
1929
+ return;
1930
+ }
1931
+ // https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-lifecycle-callbacks
1932
+ const callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback', 'formAssociatedCallback', 'formDisabledCallback', 'formResetCallback', 'formStateRestoreCallback'];
1933
+ api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
1934
+ }
1935
+ function eventTargetPatch(_global, api) {
1936
+ if (Zone[api.symbol('patchEventTarget')]) {
1937
+ // EventTarget is already patched.
1938
+ return;
1939
+ }
1940
+ const {
1941
+ eventNames,
1942
+ zoneSymbolEventNames,
1943
+ TRUE_STR,
1944
+ FALSE_STR,
1945
+ ZONE_SYMBOL_PREFIX
1946
+ } = api.getGlobalObjects();
1947
+ // predefine all __zone_symbol__ + eventName + true/false string
1948
+ for (let i = 0; i < eventNames.length; i++) {
1949
+ const eventName = eventNames[i];
1950
+ const falseEventName = eventName + FALSE_STR;
1951
+ const trueEventName = eventName + TRUE_STR;
1952
+ const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
1953
+ const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
1954
+ zoneSymbolEventNames[eventName] = {};
1955
+ zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
1956
+ zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
1957
+ }
1958
+ const EVENT_TARGET = _global['EventTarget'];
1959
+ if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
1960
+ return;
1961
+ }
1962
+ api.patchEventTarget(_global, api, [EVENT_TARGET && EVENT_TARGET.prototype]);
1963
+ return true;
1964
+ }
1965
+ function patchEvent(global, api) {
1966
+ api.patchEventPrototype(global, api);
1967
+ }
1968
+
1969
+ /**
1970
+ * @fileoverview
1971
+ * @suppress {globalThis}
1972
+ */
1973
+ function filterProperties(target, onProperties, ignoreProperties) {
1974
+ if (!ignoreProperties || ignoreProperties.length === 0) {
1975
+ return onProperties;
1976
+ }
1977
+ const tip = ignoreProperties.filter(ip => ip.target === target);
1978
+ if (!tip || tip.length === 0) {
1979
+ return onProperties;
1980
+ }
1981
+ const targetIgnoreProperties = tip[0].ignoreProperties;
1982
+ return onProperties.filter(op => targetIgnoreProperties.indexOf(op) === -1);
1983
+ }
1984
+ function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
1985
+ // check whether target is available, sometimes target will be undefined
1986
+ // because different browser or some 3rd party plugin.
1987
+ if (!target) {
1988
+ return;
1989
+ }
1990
+ const filteredProperties = filterProperties(target, onProperties, ignoreProperties);
1991
+ patchOnProperties(target, filteredProperties, prototype);
1992
+ }
1993
+ /**
1994
+ * Get all event name properties which the event name startsWith `on`
1995
+ * from the target object itself, inherited properties are not considered.
1996
+ */
1997
+ function getOnEventNames(target) {
1998
+ return Object.getOwnPropertyNames(target).filter(name => name.startsWith('on') && name.length > 2).map(name => name.substring(2));
1999
+ }
2000
+ function propertyDescriptorPatch(api, _global) {
2001
+ if (isNode && !isMix) {
2002
+ return;
2003
+ }
2004
+ if (Zone[api.symbol('patchEvents')]) {
2005
+ // events are already been patched by legacy patch.
2006
+ return;
2007
+ }
2008
+ const ignoreProperties = _global['__Zone_ignore_on_properties'];
2009
+ // for browsers that we can patch the descriptor: Chrome & Firefox
2010
+ let patchTargets = [];
2011
+ if (isBrowser) {
2012
+ const internalWindow = window;
2013
+ patchTargets = patchTargets.concat(['Document', 'SVGElement', 'Element', 'HTMLElement', 'HTMLBodyElement', 'HTMLMediaElement', 'HTMLFrameSetElement', 'HTMLFrameElement', 'HTMLIFrameElement', 'HTMLMarqueeElement', 'Worker']);
2014
+ const ignoreErrorProperties = isIE() ? [{
2015
+ target: internalWindow,
2016
+ ignoreProperties: ['error']
2017
+ }] : [];
2018
+ // in IE/Edge, onProp not exist in window object, but in WindowPrototype
2019
+ // so we need to pass WindowPrototype to check onProp exist or not
2020
+ patchFilteredProperties(internalWindow, getOnEventNames(internalWindow), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
2021
+ }
2022
+ patchTargets = patchTargets.concat(['XMLHttpRequest', 'XMLHttpRequestEventTarget', 'IDBIndex', 'IDBRequest', 'IDBOpenDBRequest', 'IDBDatabase', 'IDBTransaction', 'IDBCursor', 'WebSocket']);
2023
+ for (let i = 0; i < patchTargets.length; i++) {
2024
+ const target = _global[patchTargets[i]];
2025
+ target && target.prototype && patchFilteredProperties(target.prototype, getOnEventNames(target.prototype), ignoreProperties);
2026
+ }
2027
+ }
2028
+
2029
+ /**
2030
+ * @fileoverview
2031
+ * @suppress {missingRequire}
2032
+ */
2033
+ function patchBrowser(Zone) {
2034
+ Zone.__load_patch('legacy', global => {
2035
+ const legacyPatch = global[Zone.__symbol__('legacyPatch')];
2036
+ if (legacyPatch) {
2037
+ legacyPatch();
2038
+ }
2039
+ });
2040
+ Zone.__load_patch('timers', global => {
2041
+ const set = 'set';
2042
+ const clear = 'clear';
2043
+ patchTimer(global, set, clear, 'Timeout');
2044
+ patchTimer(global, set, clear, 'Interval');
2045
+ patchTimer(global, set, clear, 'Immediate');
2046
+ });
2047
+ Zone.__load_patch('requestAnimationFrame', global => {
2048
+ patchTimer(global, 'request', 'cancel', 'AnimationFrame');
2049
+ patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
2050
+ patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
2051
+ });
2052
+ Zone.__load_patch('blocking', (global, Zone) => {
2053
+ const blockingMethods = ['alert', 'prompt', 'confirm'];
2054
+ for (let i = 0; i < blockingMethods.length; i++) {
2055
+ const name = blockingMethods[i];
2056
+ patchMethod(global, name, (delegate, symbol, name) => {
2057
+ return function (s, args) {
2058
+ return Zone.current.run(delegate, global, args, name);
2059
+ };
2060
+ });
2061
+ }
2062
+ });
2063
+ Zone.__load_patch('EventTarget', (global, Zone, api) => {
2064
+ patchEvent(global, api);
2065
+ eventTargetPatch(global, api);
2066
+ // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
2067
+ const XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
2068
+ if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
2069
+ api.patchEventTarget(global, api, [XMLHttpRequestEventTarget.prototype]);
2070
+ }
2071
+ });
2072
+ Zone.__load_patch('MutationObserver', (global, Zone, api) => {
2073
+ patchClass('MutationObserver');
2074
+ patchClass('WebKitMutationObserver');
2075
+ });
2076
+ Zone.__load_patch('IntersectionObserver', (global, Zone, api) => {
2077
+ patchClass('IntersectionObserver');
2078
+ });
2079
+ Zone.__load_patch('FileReader', (global, Zone, api) => {
2080
+ patchClass('FileReader');
2081
+ });
2082
+ Zone.__load_patch('on_property', (global, Zone, api) => {
2083
+ propertyDescriptorPatch(api, global);
2084
+ });
2085
+ Zone.__load_patch('customElements', (global, Zone, api) => {
2086
+ patchCustomElements(global, api);
2087
+ });
2088
+ Zone.__load_patch('XHR', (global, Zone) => {
2089
+ // Treat XMLHttpRequest as a macrotask.
2090
+ patchXHR(global);
2091
+ const XHR_TASK = zoneSymbol('xhrTask');
2092
+ const XHR_SYNC = zoneSymbol('xhrSync');
2093
+ const XHR_LISTENER = zoneSymbol('xhrListener');
2094
+ const XHR_SCHEDULED = zoneSymbol('xhrScheduled');
2095
+ const XHR_URL = zoneSymbol('xhrURL');
2096
+ const XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
2097
+ function patchXHR(window) {
2098
+ const XMLHttpRequest = window['XMLHttpRequest'];
2099
+ if (!XMLHttpRequest) {
2100
+ // XMLHttpRequest is not available in service worker
2101
+ return;
2102
+ }
2103
+ const XMLHttpRequestPrototype = XMLHttpRequest.prototype;
2104
+ function findPendingTask(target) {
2105
+ return target[XHR_TASK];
2106
+ }
2107
+ let oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
2108
+ let oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
2109
+ if (!oriAddListener) {
2110
+ const XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
2111
+ if (XMLHttpRequestEventTarget) {
2112
+ const XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
2113
+ oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
2114
+ oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
2115
+ }
2116
+ }
2117
+ const READY_STATE_CHANGE = 'readystatechange';
2118
+ const SCHEDULED = 'scheduled';
2119
+ function scheduleTask(task) {
2120
+ const data = task.data;
2121
+ const target = data.target;
2122
+ target[XHR_SCHEDULED] = false;
2123
+ target[XHR_ERROR_BEFORE_SCHEDULED] = false;
2124
+ // remove existing event listener
2125
+ const listener = target[XHR_LISTENER];
2126
+ if (!oriAddListener) {
2127
+ oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
2128
+ oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
2129
+ }
2130
+ if (listener) {
2131
+ oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
2132
+ }
2133
+ const newListener = target[XHR_LISTENER] = () => {
2134
+ if (target.readyState === target.DONE) {
2135
+ // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
2136
+ // readyState=4 multiple times, so we need to check task state here
2137
+ if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
2138
+ // check whether the xhr has registered onload listener
2139
+ // if that is the case, the task should invoke after all
2140
+ // onload listeners finish.
2141
+ // Also if the request failed without response (status = 0), the load event handler
2142
+ // will not be triggered, in that case, we should also invoke the placeholder callback
2143
+ // to close the XMLHttpRequest::send macroTask.
2144
+ // https://github.com/angular/angular/issues/38795
2145
+ const loadTasks = target[Zone.__symbol__('loadfalse')];
2146
+ if (target.status !== 0 && loadTasks && loadTasks.length > 0) {
2147
+ const oriInvoke = task.invoke;
2148
+ task.invoke = function () {
2149
+ // need to load the tasks again, because in other
2150
+ // load listener, they may remove themselves
2151
+ const loadTasks = target[Zone.__symbol__('loadfalse')];
2152
+ for (let i = 0; i < loadTasks.length; i++) {
2153
+ if (loadTasks[i] === task) {
2154
+ loadTasks.splice(i, 1);
2155
+ }
2156
+ }
2157
+ if (!data.aborted && task.state === SCHEDULED) {
2158
+ oriInvoke.call(task);
2159
+ }
2160
+ };
2161
+ loadTasks.push(task);
2162
+ } else {
2163
+ task.invoke();
2164
+ }
2165
+ } else if (!data.aborted && target[XHR_SCHEDULED] === false) {
2166
+ // error occurs when xhr.send()
2167
+ target[XHR_ERROR_BEFORE_SCHEDULED] = true;
2168
+ }
2169
+ }
2170
+ };
2171
+ oriAddListener.call(target, READY_STATE_CHANGE, newListener);
2172
+ const storedTask = target[XHR_TASK];
2173
+ if (!storedTask) {
2174
+ target[XHR_TASK] = task;
2175
+ }
2176
+ sendNative.apply(target, data.args);
2177
+ target[XHR_SCHEDULED] = true;
2178
+ return task;
2179
+ }
2180
+ function placeholderCallback() {}
2181
+ function clearTask(task) {
2182
+ const data = task.data;
2183
+ // Note - ideally, we would call data.target.removeEventListener here, but it's too late
2184
+ // to prevent it from firing. So instead, we store info for the event listener.
2185
+ data.aborted = true;
2186
+ return abortNative.apply(data.target, data.args);
2187
+ }
2188
+ const openNative = patchMethod(XMLHttpRequestPrototype, 'open', () => function (self, args) {
2189
+ self[XHR_SYNC] = args[2] == false;
2190
+ self[XHR_URL] = args[1];
2191
+ return openNative.apply(self, args);
2192
+ });
2193
+ const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
2194
+ const fetchTaskAborting = zoneSymbol('fetchTaskAborting');
2195
+ const fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
2196
+ const sendNative = patchMethod(XMLHttpRequestPrototype, 'send', () => function (self, args) {
2197
+ if (Zone.current[fetchTaskScheduling] === true) {
2198
+ // a fetch is scheduling, so we are using xhr to polyfill fetch
2199
+ // and because we already schedule macroTask for fetch, we should
2200
+ // not schedule a macroTask for xhr again
2201
+ return sendNative.apply(self, args);
2202
+ }
2203
+ if (self[XHR_SYNC]) {
2204
+ // if the XHR is sync there is no task to schedule, just execute the code.
2205
+ return sendNative.apply(self, args);
2206
+ } else {
2207
+ const options = {
2208
+ target: self,
2209
+ url: self[XHR_URL],
2210
+ isPeriodic: false,
2211
+ args: args,
2212
+ aborted: false
2213
+ };
2214
+ const task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
2215
+ if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted && task.state === SCHEDULED) {
2216
+ // xhr request throw error when send
2217
+ // we should invoke task instead of leaving a scheduled
2218
+ // pending macroTask
2219
+ task.invoke();
2220
+ }
2221
+ }
2222
+ });
2223
+ const abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', () => function (self, args) {
2224
+ const task = findPendingTask(self);
2225
+ if (task && typeof task.type == 'string') {
2226
+ // If the XHR has already completed, do nothing.
2227
+ // If the XHR has already been aborted, do nothing.
2228
+ // Fix #569, call abort multiple times before done will cause
2229
+ // macroTask task count be negative number
2230
+ if (task.cancelFn == null || task.data && task.data.aborted) {
2231
+ return;
2232
+ }
2233
+ task.zone.cancelTask(task);
2234
+ } else if (Zone.current[fetchTaskAborting] === true) {
2235
+ // the abort is called from fetch polyfill, we need to call native abort of XHR.
2236
+ return abortNative.apply(self, args);
2237
+ }
2238
+ // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
2239
+ // task
2240
+ // to cancel. Do nothing.
2241
+ });
2242
+ }
2243
+ });
2244
+ Zone.__load_patch('geolocation', global => {
2245
+ /// GEO_LOCATION
2246
+ if (global['navigator'] && global['navigator'].geolocation) {
2247
+ patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
2248
+ }
2249
+ });
2250
+ Zone.__load_patch('PromiseRejectionEvent', (global, Zone) => {
2251
+ // handle unhandled promise rejection
2252
+ function findPromiseRejectionHandler(evtName) {
2253
+ return function (e) {
2254
+ const eventTasks = findEventTasks(global, evtName);
2255
+ eventTasks.forEach(eventTask => {
2256
+ // windows has added unhandledrejection event listener
2257
+ // trigger the event listener
2258
+ const PromiseRejectionEvent = global['PromiseRejectionEvent'];
2259
+ if (PromiseRejectionEvent) {
2260
+ const evt = new PromiseRejectionEvent(evtName, {
2261
+ promise: e.promise,
2262
+ reason: e.rejection
2263
+ });
2264
+ eventTask.invoke(evt);
2265
+ }
2266
+ });
2267
+ };
2268
+ }
2269
+ if (global['PromiseRejectionEvent']) {
2270
+ Zone[zoneSymbol('unhandledPromiseRejectionHandler')] = findPromiseRejectionHandler('unhandledrejection');
2271
+ Zone[zoneSymbol('rejectionHandledHandler')] = findPromiseRejectionHandler('rejectionhandled');
2272
+ }
2273
+ });
2274
+ Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
2275
+ patchQueueMicrotask(global, api);
2276
+ });
2277
+ }
2278
+ function patchPromise(Zone) {
2279
+ Zone.__load_patch('ZoneAwarePromise', (global, Zone, api) => {
2280
+ const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2281
+ const ObjectDefineProperty = Object.defineProperty;
2282
+ function readableObjectToString(obj) {
2283
+ if (obj && obj.toString === Object.prototype.toString) {
2284
+ const className = obj.constructor && obj.constructor.name;
2285
+ return (className ? className : '') + ': ' + JSON.stringify(obj);
2286
+ }
2287
+ return obj ? obj.toString() : Object.prototype.toString.call(obj);
2288
+ }
2289
+ const __symbol__ = api.symbol;
2290
+ const _uncaughtPromiseErrors = [];
2291
+ const isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] !== false;
2292
+ const symbolPromise = __symbol__('Promise');
2293
+ const symbolThen = __symbol__('then');
2294
+ const creationTrace = '__creationTrace__';
2295
+ api.onUnhandledError = e => {
2296
+ if (api.showUncaughtError()) {
2297
+ const rejection = e && e.rejection;
2298
+ if (rejection) {
2299
+ console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
2300
+ } else {
2301
+ console.error(e);
2302
+ }
2303
+ }
2304
+ };
2305
+ api.microtaskDrainDone = () => {
2306
+ while (_uncaughtPromiseErrors.length) {
2307
+ const uncaughtPromiseError = _uncaughtPromiseErrors.shift();
2308
+ try {
2309
+ uncaughtPromiseError.zone.runGuarded(() => {
2310
+ if (uncaughtPromiseError.throwOriginal) {
2311
+ throw uncaughtPromiseError.rejection;
2312
+ }
2313
+ throw uncaughtPromiseError;
2314
+ });
2315
+ } catch (error) {
2316
+ handleUnhandledRejection(error);
2317
+ }
2318
+ }
2319
+ };
2320
+ const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
2321
+ function handleUnhandledRejection(e) {
2322
+ api.onUnhandledError(e);
2323
+ try {
2324
+ const handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
2325
+ if (typeof handler === 'function') {
2326
+ handler.call(this, e);
2327
+ }
2328
+ } catch (err) {}
2329
+ }
2330
+ function isThenable(value) {
2331
+ return value && value.then;
2332
+ }
2333
+ function forwardResolution(value) {
2334
+ return value;
2335
+ }
2336
+ function forwardRejection(rejection) {
2337
+ return ZoneAwarePromise.reject(rejection);
2338
+ }
2339
+ const symbolState = __symbol__('state');
2340
+ const symbolValue = __symbol__('value');
2341
+ const symbolFinally = __symbol__('finally');
2342
+ const symbolParentPromiseValue = __symbol__('parentPromiseValue');
2343
+ const symbolParentPromiseState = __symbol__('parentPromiseState');
2344
+ const source = 'Promise.then';
2345
+ const UNRESOLVED = null;
2346
+ const RESOLVED = true;
2347
+ const REJECTED = false;
2348
+ const REJECTED_NO_CATCH = 0;
2349
+ function makeResolver(promise, state) {
2350
+ return v => {
2351
+ try {
2352
+ resolvePromise(promise, state, v);
2353
+ } catch (err) {
2354
+ resolvePromise(promise, false, err);
2355
+ }
2356
+ // Do not return value or you will break the Promise spec.
2357
+ };
2358
+ }
2359
+ const once = function () {
2360
+ let wasCalled = false;
2361
+ return function wrapper(wrappedFunction) {
2362
+ return function () {
2363
+ if (wasCalled) {
2364
+ return;
2365
+ }
2366
+ wasCalled = true;
2367
+ wrappedFunction.apply(null, arguments);
2368
+ };
2369
+ };
2370
+ };
2371
+ const TYPE_ERROR = 'Promise resolved with itself';
2372
+ const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
2373
+ // Promise Resolution
2374
+ function resolvePromise(promise, state, value) {
2375
+ const onceWrapper = once();
2376
+ if (promise === value) {
2377
+ throw new TypeError(TYPE_ERROR);
2378
+ }
2379
+ if (promise[symbolState] === UNRESOLVED) {
2380
+ // should only get value.then once based on promise spec.
2381
+ let then = null;
2382
+ try {
2383
+ if (typeof value === 'object' || typeof value === 'function') {
2384
+ then = value && value.then;
2385
+ }
2386
+ } catch (err) {
2387
+ onceWrapper(() => {
2388
+ resolvePromise(promise, false, err);
2389
+ })();
2390
+ return promise;
2391
+ }
2392
+ // if (value instanceof ZoneAwarePromise) {
2393
+ if (state !== REJECTED && value instanceof ZoneAwarePromise && value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) && value[symbolState] !== UNRESOLVED) {
2394
+ clearRejectedNoCatch(value);
2395
+ resolvePromise(promise, value[symbolState], value[symbolValue]);
2396
+ } else if (state !== REJECTED && typeof then === 'function') {
2397
+ try {
2398
+ then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
2399
+ } catch (err) {
2400
+ onceWrapper(() => {
2401
+ resolvePromise(promise, false, err);
2402
+ })();
2403
+ }
2404
+ } else {
2405
+ promise[symbolState] = state;
2406
+ const queue = promise[symbolValue];
2407
+ promise[symbolValue] = value;
2408
+ if (promise[symbolFinally] === symbolFinally) {
2409
+ // the promise is generated by Promise.prototype.finally
2410
+ if (state === RESOLVED) {
2411
+ // the state is resolved, should ignore the value
2412
+ // and use parent promise value
2413
+ promise[symbolState] = promise[symbolParentPromiseState];
2414
+ promise[symbolValue] = promise[symbolParentPromiseValue];
2415
+ }
2416
+ }
2417
+ // record task information in value when error occurs, so we can
2418
+ // do some additional work such as render longStackTrace
2419
+ if (state === REJECTED && value instanceof Error) {
2420
+ // check if longStackTraceZone is here
2421
+ const trace = Zone.currentTask && Zone.currentTask.data && Zone.currentTask.data[creationTrace];
2422
+ if (trace) {
2423
+ // only keep the long stack trace into error when in longStackTraceZone
2424
+ ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, {
2425
+ configurable: true,
2426
+ enumerable: false,
2427
+ writable: true,
2428
+ value: trace
2429
+ });
2430
+ }
2431
+ }
2432
+ for (let i = 0; i < queue.length;) {
2433
+ scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
2434
+ }
2435
+ if (queue.length == 0 && state == REJECTED) {
2436
+ promise[symbolState] = REJECTED_NO_CATCH;
2437
+ let uncaughtPromiseError = value;
2438
+ try {
2439
+ // Here we throws a new Error to print more readable error log
2440
+ // and if the value is not an error, zone.js builds an `Error`
2441
+ // Object here to attach the stack information.
2442
+ throw new Error('Uncaught (in promise): ' + readableObjectToString(value) + (value && value.stack ? '\n' + value.stack : ''));
2443
+ } catch (err) {
2444
+ uncaughtPromiseError = err;
2445
+ }
2446
+ if (isDisableWrappingUncaughtPromiseRejection) {
2447
+ // If disable wrapping uncaught promise reject
2448
+ // use the value instead of wrapping it.
2449
+ uncaughtPromiseError.throwOriginal = true;
2450
+ }
2451
+ uncaughtPromiseError.rejection = value;
2452
+ uncaughtPromiseError.promise = promise;
2453
+ uncaughtPromiseError.zone = Zone.current;
2454
+ uncaughtPromiseError.task = Zone.currentTask;
2455
+ _uncaughtPromiseErrors.push(uncaughtPromiseError);
2456
+ api.scheduleMicroTask(); // to make sure that it is running
2457
+ }
2458
+ }
2459
+ }
2460
+ // Resolving an already resolved promise is a noop.
2461
+ return promise;
2462
+ }
2463
+ const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
2464
+ function clearRejectedNoCatch(promise) {
2465
+ if (promise[symbolState] === REJECTED_NO_CATCH) {
2466
+ // if the promise is rejected no catch status
2467
+ // and queue.length > 0, means there is a error handler
2468
+ // here to handle the rejected promise, we should trigger
2469
+ // windows.rejectionhandled eventHandler or nodejs rejectionHandled
2470
+ // eventHandler
2471
+ try {
2472
+ const handler = Zone[REJECTION_HANDLED_HANDLER];
2473
+ if (handler && typeof handler === 'function') {
2474
+ handler.call(this, {
2475
+ rejection: promise[symbolValue],
2476
+ promise: promise
2477
+ });
2478
+ }
2479
+ } catch (err) {}
2480
+ promise[symbolState] = REJECTED;
2481
+ for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
2482
+ if (promise === _uncaughtPromiseErrors[i].promise) {
2483
+ _uncaughtPromiseErrors.splice(i, 1);
2484
+ }
2485
+ }
2486
+ }
2487
+ }
2488
+ function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
2489
+ clearRejectedNoCatch(promise);
2490
+ const promiseState = promise[symbolState];
2491
+ const delegate = promiseState ? typeof onFulfilled === 'function' ? onFulfilled : forwardResolution : typeof onRejected === 'function' ? onRejected : forwardRejection;
2492
+ zone.scheduleMicroTask(source, () => {
2493
+ try {
2494
+ const parentPromiseValue = promise[symbolValue];
2495
+ const isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
2496
+ if (isFinallyPromise) {
2497
+ // if the promise is generated from finally call, keep parent promise's state and value
2498
+ chainPromise[symbolParentPromiseValue] = parentPromiseValue;
2499
+ chainPromise[symbolParentPromiseState] = promiseState;
2500
+ }
2501
+ // should not pass value to finally callback
2502
+ const value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ? [] : [parentPromiseValue]);
2503
+ resolvePromise(chainPromise, true, value);
2504
+ } catch (error) {
2505
+ // if error occurs, should always return this error
2506
+ resolvePromise(chainPromise, false, error);
2507
+ }
2508
+ }, chainPromise);
2509
+ }
2510
+ const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
2511
+ const noop = function () {};
2512
+ const AggregateError = global.AggregateError;
2513
+ class ZoneAwarePromise {
2514
+ static toString() {
2515
+ return ZONE_AWARE_PROMISE_TO_STRING;
2516
+ }
2517
+ static resolve(value) {
2518
+ if (value instanceof ZoneAwarePromise) {
2519
+ return value;
2520
+ }
2521
+ return resolvePromise(new this(null), RESOLVED, value);
2522
+ }
2523
+ static reject(error) {
2524
+ return resolvePromise(new this(null), REJECTED, error);
2525
+ }
2526
+ static withResolvers() {
2527
+ const result = {};
2528
+ result.promise = new ZoneAwarePromise((res, rej) => {
2529
+ result.resolve = res;
2530
+ result.reject = rej;
2531
+ });
2532
+ return result;
2533
+ }
2534
+ static any(values) {
2535
+ if (!values || typeof values[Symbol.iterator] !== 'function') {
2536
+ return Promise.reject(new AggregateError([], 'All promises were rejected'));
2537
+ }
2538
+ const promises = [];
2539
+ let count = 0;
2540
+ try {
2541
+ for (let v of values) {
2542
+ count++;
2543
+ promises.push(ZoneAwarePromise.resolve(v));
2544
+ }
2545
+ } catch (err) {
2546
+ return Promise.reject(new AggregateError([], 'All promises were rejected'));
2547
+ }
2548
+ if (count === 0) {
2549
+ return Promise.reject(new AggregateError([], 'All promises were rejected'));
2550
+ }
2551
+ let finished = false;
2552
+ const errors = [];
2553
+ return new ZoneAwarePromise((resolve, reject) => {
2554
+ for (let i = 0; i < promises.length; i++) {
2555
+ promises[i].then(v => {
2556
+ if (finished) {
2557
+ return;
2558
+ }
2559
+ finished = true;
2560
+ resolve(v);
2561
+ }, err => {
2562
+ errors.push(err);
2563
+ count--;
2564
+ if (count === 0) {
2565
+ finished = true;
2566
+ reject(new AggregateError(errors, 'All promises were rejected'));
2567
+ }
2568
+ });
2569
+ }
2570
+ });
2571
+ }
2572
+ static race(values) {
2573
+ let resolve;
2574
+ let reject;
2575
+ let promise = new this((res, rej) => {
2576
+ resolve = res;
2577
+ reject = rej;
2578
+ });
2579
+ function onResolve(value) {
2580
+ resolve(value);
2581
+ }
2582
+ function onReject(error) {
2583
+ reject(error);
2584
+ }
2585
+ for (let value of values) {
2586
+ if (!isThenable(value)) {
2587
+ value = this.resolve(value);
2588
+ }
2589
+ value.then(onResolve, onReject);
2590
+ }
2591
+ return promise;
2592
+ }
2593
+ static all(values) {
2594
+ return ZoneAwarePromise.allWithCallback(values);
2595
+ }
2596
+ static allSettled(values) {
2597
+ const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
2598
+ return P.allWithCallback(values, {
2599
+ thenCallback: value => ({
2600
+ status: 'fulfilled',
2601
+ value
2602
+ }),
2603
+ errorCallback: err => ({
2604
+ status: 'rejected',
2605
+ reason: err
2606
+ })
2607
+ });
2608
+ }
2609
+ static allWithCallback(values, callback) {
2610
+ let resolve;
2611
+ let reject;
2612
+ let promise = new this((res, rej) => {
2613
+ resolve = res;
2614
+ reject = rej;
2615
+ });
2616
+ // Start at 2 to prevent prematurely resolving if .then is called immediately.
2617
+ let unresolvedCount = 2;
2618
+ let valueIndex = 0;
2619
+ const resolvedValues = [];
2620
+ for (let value of values) {
2621
+ if (!isThenable(value)) {
2622
+ value = this.resolve(value);
2623
+ }
2624
+ const curValueIndex = valueIndex;
2625
+ try {
2626
+ value.then(value => {
2627
+ resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
2628
+ unresolvedCount--;
2629
+ if (unresolvedCount === 0) {
2630
+ resolve(resolvedValues);
2631
+ }
2632
+ }, err => {
2633
+ if (!callback) {
2634
+ reject(err);
2635
+ } else {
2636
+ resolvedValues[curValueIndex] = callback.errorCallback(err);
2637
+ unresolvedCount--;
2638
+ if (unresolvedCount === 0) {
2639
+ resolve(resolvedValues);
2640
+ }
2641
+ }
2642
+ });
2643
+ } catch (thenErr) {
2644
+ reject(thenErr);
2645
+ }
2646
+ unresolvedCount++;
2647
+ valueIndex++;
2648
+ }
2649
+ // Make the unresolvedCount zero-based again.
2650
+ unresolvedCount -= 2;
2651
+ if (unresolvedCount === 0) {
2652
+ resolve(resolvedValues);
2653
+ }
2654
+ return promise;
2655
+ }
2656
+ constructor(executor) {
2657
+ const promise = this;
2658
+ if (!(promise instanceof ZoneAwarePromise)) {
2659
+ throw new Error('Must be an instanceof Promise.');
2660
+ }
2661
+ promise[symbolState] = UNRESOLVED;
2662
+ promise[symbolValue] = []; // queue;
2663
+ try {
2664
+ const onceWrapper = once();
2665
+ executor && executor(onceWrapper(makeResolver(promise, RESOLVED)), onceWrapper(makeResolver(promise, REJECTED)));
2666
+ } catch (error) {
2667
+ resolvePromise(promise, false, error);
2668
+ }
2669
+ }
2670
+ get [Symbol.toStringTag]() {
2671
+ return 'Promise';
2672
+ }
2673
+ get [Symbol.species]() {
2674
+ return ZoneAwarePromise;
2675
+ }
2676
+ then(onFulfilled, onRejected) {
2677
+ // We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
2678
+ // may be an object without a prototype (created through `Object.create(null)`); thus
2679
+ // `this.constructor` will be undefined. One of the use cases is SystemJS creating
2680
+ // prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
2681
+ // object and copies promise properties into that object (within the `getOrCreateLoad`
2682
+ // function). The zone.js then checks if the resolved value has the `then` method and
2683
+ // invokes it with the `value` context. Otherwise, this will throw an error: `TypeError:
2684
+ // Cannot read properties of undefined (reading 'Symbol(Symbol.species)')`.
2685
+ let C = this.constructor?.[Symbol.species];
2686
+ if (!C || typeof C !== 'function') {
2687
+ C = this.constructor || ZoneAwarePromise;
2688
+ }
2689
+ const chainPromise = new C(noop);
2690
+ const zone = Zone.current;
2691
+ if (this[symbolState] == UNRESOLVED) {
2692
+ this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
2693
+ } else {
2694
+ scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
2695
+ }
2696
+ return chainPromise;
2697
+ }
2698
+ catch(onRejected) {
2699
+ return this.then(null, onRejected);
2700
+ }
2701
+ finally(onFinally) {
2702
+ // See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
2703
+ let C = this.constructor?.[Symbol.species];
2704
+ if (!C || typeof C !== 'function') {
2705
+ C = ZoneAwarePromise;
2706
+ }
2707
+ const chainPromise = new C(noop);
2708
+ chainPromise[symbolFinally] = symbolFinally;
2709
+ const zone = Zone.current;
2710
+ if (this[symbolState] == UNRESOLVED) {
2711
+ this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
2712
+ } else {
2713
+ scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
2714
+ }
2715
+ return chainPromise;
2716
+ }
2717
+ }
2718
+ // Protect against aggressive optimizers dropping seemingly unused properties.
2719
+ // E.g. Closure Compiler in advanced mode.
2720
+ ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
2721
+ ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
2722
+ ZoneAwarePromise['race'] = ZoneAwarePromise.race;
2723
+ ZoneAwarePromise['all'] = ZoneAwarePromise.all;
2724
+ const NativePromise = global[symbolPromise] = global['Promise'];
2725
+ global['Promise'] = ZoneAwarePromise;
2726
+ const symbolThenPatched = __symbol__('thenPatched');
2727
+ function patchThen(Ctor) {
2728
+ const proto = Ctor.prototype;
2729
+ const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
2730
+ if (prop && (prop.writable === false || !prop.configurable)) {
2731
+ // check Ctor.prototype.then propertyDescriptor is writable or not
2732
+ // in meteor env, writable is false, we should ignore such case
2733
+ return;
2734
+ }
2735
+ const originalThen = proto.then;
2736
+ // Keep a reference to the original method.
2737
+ proto[symbolThen] = originalThen;
2738
+ Ctor.prototype.then = function (onResolve, onReject) {
2739
+ const wrapped = new ZoneAwarePromise((resolve, reject) => {
2740
+ originalThen.call(this, resolve, reject);
2741
+ });
2742
+ return wrapped.then(onResolve, onReject);
2743
+ };
2744
+ Ctor[symbolThenPatched] = true;
2745
+ }
2746
+ api.patchThen = patchThen;
2747
+ function zoneify(fn) {
2748
+ return function (self, args) {
2749
+ let resultPromise = fn.apply(self, args);
2750
+ if (resultPromise instanceof ZoneAwarePromise) {
2751
+ return resultPromise;
2752
+ }
2753
+ let ctor = resultPromise.constructor;
2754
+ if (!ctor[symbolThenPatched]) {
2755
+ patchThen(ctor);
2756
+ }
2757
+ return resultPromise;
2758
+ };
2759
+ }
2760
+ if (NativePromise) {
2761
+ patchThen(NativePromise);
2762
+ patchMethod(global, 'fetch', delegate => zoneify(delegate));
2763
+ }
2764
+ // This is not part of public API, but it is useful for tests, so we expose it.
2765
+ Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
2766
+ return ZoneAwarePromise;
2767
+ });
2768
+ }
2769
+ function patchToString(Zone) {
2770
+ // override Function.prototype.toString to make zone.js patched function
2771
+ // look like native function
2772
+ Zone.__load_patch('toString', global => {
2773
+ // patch Func.prototype.toString to let them look like native
2774
+ const originalFunctionToString = Function.prototype.toString;
2775
+ const ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
2776
+ const PROMISE_SYMBOL = zoneSymbol('Promise');
2777
+ const ERROR_SYMBOL = zoneSymbol('Error');
2778
+ const newFunctionToString = function toString() {
2779
+ if (typeof this === 'function') {
2780
+ const originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
2781
+ if (originalDelegate) {
2782
+ if (typeof originalDelegate === 'function') {
2783
+ return originalFunctionToString.call(originalDelegate);
2784
+ } else {
2785
+ return Object.prototype.toString.call(originalDelegate);
2786
+ }
2787
+ }
2788
+ if (this === Promise) {
2789
+ const nativePromise = global[PROMISE_SYMBOL];
2790
+ if (nativePromise) {
2791
+ return originalFunctionToString.call(nativePromise);
2792
+ }
2793
+ }
2794
+ if (this === Error) {
2795
+ const nativeError = global[ERROR_SYMBOL];
2796
+ if (nativeError) {
2797
+ return originalFunctionToString.call(nativeError);
2798
+ }
2799
+ }
2800
+ }
2801
+ return originalFunctionToString.call(this);
2802
+ };
2803
+ newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
2804
+ Function.prototype.toString = newFunctionToString;
2805
+ // patch Object.prototype.toString to let them look like native
2806
+ const originalObjectToString = Object.prototype.toString;
2807
+ const PROMISE_OBJECT_TO_STRING = '[object Promise]';
2808
+ Object.prototype.toString = function () {
2809
+ if (typeof Promise === 'function' && this instanceof Promise) {
2810
+ return PROMISE_OBJECT_TO_STRING;
2811
+ }
2812
+ return originalObjectToString.call(this);
2813
+ };
2814
+ });
2815
+ }
2816
+ function patchCallbacks(api, target, targetName, method, callbacks) {
2817
+ const symbol = Zone.__symbol__(method);
2818
+ if (target[symbol]) {
2819
+ return;
2820
+ }
2821
+ const nativeDelegate = target[symbol] = target[method];
2822
+ target[method] = function (name, opts, options) {
2823
+ if (opts && opts.prototype) {
2824
+ callbacks.forEach(function (callback) {
2825
+ const source = `${targetName}.${method}::` + callback;
2826
+ const prototype = opts.prototype;
2827
+ // Note: the `patchCallbacks` is used for patching the `document.registerElement` and
2828
+ // `customElements.define`. We explicitly wrap the patching code into try-catch since
2829
+ // callbacks may be already patched by other web components frameworks (e.g. LWC), and they
2830
+ // make those properties non-writable. This means that patching callback will throw an error
2831
+ // `cannot assign to read-only property`. See this code as an example:
2832
+ // https://github.com/salesforce/lwc/blob/master/packages/@lwc/engine-core/src/framework/base-bridge-element.ts#L180-L186
2833
+ // We don't want to stop the application rendering if we couldn't patch some
2834
+ // callback, e.g. `attributeChangedCallback`.
2835
+ try {
2836
+ if (prototype.hasOwnProperty(callback)) {
2837
+ const descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
2838
+ if (descriptor && descriptor.value) {
2839
+ descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
2840
+ api._redefineProperty(opts.prototype, callback, descriptor);
2841
+ } else if (prototype[callback]) {
2842
+ prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
2843
+ }
2844
+ } else if (prototype[callback]) {
2845
+ prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
2846
+ }
2847
+ } catch {
2848
+ // Note: we leave the catch block empty since there's no way to handle the error related
2849
+ // to non-writable property.
2850
+ }
2851
+ });
2852
+ }
2853
+ return nativeDelegate.call(target, name, opts, options);
2854
+ };
2855
+ api.attachOriginToPatched(target[method], nativeDelegate);
2856
+ }
2857
+ function patchUtil(Zone) {
2858
+ Zone.__load_patch('util', (global, Zone, api) => {
2859
+ // Collect native event names by looking at properties
2860
+ // on the global namespace, e.g. 'onclick'.
2861
+ const eventNames = getOnEventNames(global);
2862
+ api.patchOnProperties = patchOnProperties;
2863
+ api.patchMethod = patchMethod;
2864
+ api.bindArguments = bindArguments;
2865
+ api.patchMacroTask = patchMacroTask;
2866
+ // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS`
2867
+ // to define which events will not be patched by `Zone.js`. In newer version (>=0.9.0), we
2868
+ // change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep the name consistent with
2869
+ // angular repo. The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be
2870
+ // supported for backwards compatibility.
2871
+ const SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
2872
+ const SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
2873
+ if (global[SYMBOL_UNPATCHED_EVENTS]) {
2874
+ global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
2875
+ }
2876
+ if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
2877
+ Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] = global[SYMBOL_BLACK_LISTED_EVENTS];
2878
+ }
2879
+ api.patchEventPrototype = patchEventPrototype;
2880
+ api.patchEventTarget = patchEventTarget;
2881
+ api.isIEOrEdge = isIEOrEdge;
2882
+ api.ObjectDefineProperty = ObjectDefineProperty;
2883
+ api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
2884
+ api.ObjectCreate = ObjectCreate;
2885
+ api.ArraySlice = ArraySlice;
2886
+ api.patchClass = patchClass;
2887
+ api.wrapWithCurrentZone = wrapWithCurrentZone;
2888
+ api.filterProperties = filterProperties;
2889
+ api.attachOriginToPatched = attachOriginToPatched;
2890
+ api._redefineProperty = Object.defineProperty;
2891
+ api.patchCallbacks = patchCallbacks;
2892
+ api.getGlobalObjects = () => ({
2893
+ globalSources,
2894
+ zoneSymbolEventNames,
2895
+ eventNames,
2896
+ isBrowser,
2897
+ isMix,
2898
+ isNode,
2899
+ TRUE_STR,
2900
+ FALSE_STR,
2901
+ ZONE_SYMBOL_PREFIX,
2902
+ ADD_EVENT_LISTENER_STR,
2903
+ REMOVE_EVENT_LISTENER_STR
2904
+ });
2905
+ });
2906
+ }
2907
+ function patchCommon(Zone) {
2908
+ patchPromise(Zone);
2909
+ patchToString(Zone);
2910
+ patchUtil(Zone);
2911
+ }
2912
+ const Zone$1 = loadZone();
2913
+ patchCommon(Zone$1);
2914
+ patchBrowser(Zone$1);
2915
+
2916
+ /***/ }),
2917
+
2918
+ /***/ 1643:
2919
+ /*!**********************************************************!*\
2920
+ !*** ./node_modules/@angular/localize/fesm2022/init.mjs ***!
2921
+ \**********************************************************/
2922
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2923
+
2924
+ __webpack_require__.r(__webpack_exports__);
2925
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2926
+ /* harmony export */ $localize: () => (/* reexport safe */ _angular_localize__WEBPACK_IMPORTED_MODULE_0__["ɵ$localize"])
2927
+ /* harmony export */ });
2928
+ /* harmony import */ var _angular_localize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @angular/localize */ 95116);
2929
+ /**
2930
+ * @license Angular v17.3.12
2931
+ * (c) 2010-2024 Google LLC. https://angular.io/
2932
+ * License: MIT
2933
+ */
2934
+
2935
+
2936
+
2937
+
2938
+ // Attach $localize to the global context, as a side-effect of this module.
2939
+ globalThis.$localize = _angular_localize__WEBPACK_IMPORTED_MODULE_0__["ɵ$localize"];
2940
+
2941
+ /***/ }),
2942
+
2943
+ /***/ 95116:
2944
+ /*!**************************************************************!*\
2945
+ !*** ./node_modules/@angular/localize/fesm2022/localize.mjs ***!
2946
+ \**************************************************************/
2947
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2948
+
2949
+ __webpack_require__.r(__webpack_exports__);
2950
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2951
+ /* harmony export */ clearTranslations: () => (/* binding */ clearTranslations),
2952
+ /* harmony export */ loadTranslations: () => (/* binding */ loadTranslations),
2953
+ /* harmony export */ "ɵ$localize": () => (/* binding */ $localize$1),
2954
+ /* harmony export */ "ɵMissingTranslationError": () => (/* binding */ MissingTranslationError),
2955
+ /* harmony export */ "ɵcomputeMsgId": () => (/* binding */ computeMsgId),
2956
+ /* harmony export */ "ɵfindEndOfBlock": () => (/* binding */ findEndOfBlock),
2957
+ /* harmony export */ "ɵisMissingTranslationError": () => (/* binding */ isMissingTranslationError),
2958
+ /* harmony export */ "ɵmakeParsedTranslation": () => (/* binding */ makeParsedTranslation),
2959
+ /* harmony export */ "ɵmakeTemplateObject": () => (/* binding */ makeTemplateObject),
2960
+ /* harmony export */ "ɵparseMessage": () => (/* binding */ parseMessage),
2961
+ /* harmony export */ "ɵparseMetadata": () => (/* binding */ parseMetadata),
2962
+ /* harmony export */ "ɵparseTranslation": () => (/* binding */ parseTranslation),
2963
+ /* harmony export */ "ɵsplitBlock": () => (/* binding */ splitBlock),
2964
+ /* harmony export */ "ɵtranslate": () => (/* binding */ translate$1)
2965
+ /* harmony export */ });
2966
+ /**
2967
+ * @license Angular v17.3.12
2968
+ * (c) 2010-2024 Google LLC. https://angular.io/
2969
+ * License: MIT
2970
+ */
2971
+
2972
+ /**
2973
+ * The character used to mark the start and end of a "block" in a `$localize` tagged string.
2974
+ * A block can indicate metadata about the message or specify a name of a placeholder for a
2975
+ * substitution expressions.
2976
+ *
2977
+ * For example:
2978
+ *
2979
+ * ```ts
2980
+ * $localize`Hello, ${title}:title:!`;
2981
+ * $localize`:meaning|description@@id:source message text`;
2982
+ * ```
2983
+ */
2984
+ const BLOCK_MARKER$1 = ':';
2985
+ /**
2986
+ * The marker used to separate a message's "meaning" from its "description" in a metadata block.
2987
+ *
2988
+ * For example:
2989
+ *
2990
+ * ```ts
2991
+ * $localize `:correct|Indicates that the user got the answer correct: Right!`;
2992
+ * $localize `:movement|Button label for moving to the right: Right!`;
2993
+ * ```
2994
+ */
2995
+ const MEANING_SEPARATOR = '|';
2996
+ /**
2997
+ * The marker used to separate a message's custom "id" from its "description" in a metadata block.
2998
+ *
2999
+ * For example:
3000
+ *
3001
+ * ```ts
3002
+ * $localize `:A welcome message on the home page@@myApp-homepage-welcome: Welcome!`;
3003
+ * ```
3004
+ */
3005
+ const ID_SEPARATOR = '@@';
3006
+ /**
3007
+ * The marker used to separate legacy message ids from the rest of a metadata block.
3008
+ *
3009
+ * For example:
3010
+ *
3011
+ * ```ts
3012
+ * $localize `:@@custom-id␟2df64767cd895a8fabe3e18b94b5b6b6f9e2e3f0: Welcome!`;
3013
+ * ```
3014
+ *
3015
+ * Note that this character is the "symbol for the unit separator" (␟) not the "unit separator
3016
+ * character" itself, since that has no visual representation. See https://graphemica.com/%E2%90%9F.
3017
+ *
3018
+ * Here is some background for the original "unit separator character":
3019
+ * https://stackoverflow.com/questions/8695118/whats-the-file-group-record-unit-separator-control-characters-and-its-usage
3020
+ */
3021
+ const LEGACY_ID_INDICATOR = '\u241F';
3022
+
3023
+ /**
3024
+ * A lazily created TextEncoder instance for converting strings into UTF-8 bytes
3025
+ */
3026
+ let textEncoder;
3027
+ /**
3028
+ * Return the message id or compute it using the XLIFF1 digest.
3029
+ */
3030
+ function digest(message) {
3031
+ return message.id || computeDigest(message);
3032
+ }
3033
+ /**
3034
+ * Compute the message id using the XLIFF1 digest.
3035
+ */
3036
+ function computeDigest(message) {
3037
+ return sha1(serializeNodes(message.nodes).join('') + `[${message.meaning}]`);
3038
+ }
3039
+ /**
3040
+ * Return the message id or compute it using the XLIFF2/XMB/$localize digest.
3041
+ */
3042
+ function decimalDigest(message) {
3043
+ return message.id || computeDecimalDigest(message);
3044
+ }
3045
+ /**
3046
+ * Compute the message id using the XLIFF2/XMB/$localize digest.
3047
+ */
3048
+ function computeDecimalDigest(message) {
3049
+ const visitor = new _SerializerIgnoreIcuExpVisitor();
3050
+ const parts = message.nodes.map(a => a.visit(visitor, null));
3051
+ return computeMsgId(parts.join(''), message.meaning);
3052
+ }
3053
+ /**
3054
+ * Serialize the i18n ast to something xml-like in order to generate an UID.
3055
+ *
3056
+ * The visitor is also used in the i18n parser tests
3057
+ *
3058
+ * @internal
3059
+ */
3060
+ class _SerializerVisitor {
3061
+ visitText(text, context) {
3062
+ return text.value;
3063
+ }
3064
+ visitContainer(container, context) {
3065
+ return `[${container.children.map(child => child.visit(this)).join(', ')}]`;
3066
+ }
3067
+ visitIcu(icu, context) {
3068
+ const strCases = Object.keys(icu.cases).map(k => `${k} {${icu.cases[k].visit(this)}}`);
3069
+ return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`;
3070
+ }
3071
+ visitTagPlaceholder(ph, context) {
3072
+ return ph.isVoid ? `<ph tag name="${ph.startName}"/>` : `<ph tag name="${ph.startName}">${ph.children.map(child => child.visit(this)).join(', ')}</ph name="${ph.closeName}">`;
3073
+ }
3074
+ visitPlaceholder(ph, context) {
3075
+ return ph.value ? `<ph name="${ph.name}">${ph.value}</ph>` : `<ph name="${ph.name}"/>`;
3076
+ }
3077
+ visitIcuPlaceholder(ph, context) {
3078
+ return `<ph icu name="${ph.name}">${ph.value.visit(this)}</ph>`;
3079
+ }
3080
+ visitBlockPlaceholder(ph, context) {
3081
+ return `<ph block name="${ph.startName}">${ph.children.map(child => child.visit(this)).join(', ')}</ph name="${ph.closeName}">`;
3082
+ }
3083
+ }
3084
+ const serializerVisitor = new _SerializerVisitor();
3085
+ function serializeNodes(nodes) {
3086
+ return nodes.map(a => a.visit(serializerVisitor, null));
3087
+ }
3088
+ /**
3089
+ * Serialize the i18n ast to something xml-like in order to generate an UID.
3090
+ *
3091
+ * Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
3092
+ *
3093
+ * @internal
3094
+ */
3095
+ class _SerializerIgnoreIcuExpVisitor extends _SerializerVisitor {
3096
+ visitIcu(icu, context) {
3097
+ let strCases = Object.keys(icu.cases).map(k => `${k} {${icu.cases[k].visit(this)}}`);
3098
+ // Do not take the expression into account
3099
+ return `{${icu.type}, ${strCases.join(', ')}}`;
3100
+ }
3101
+ }
3102
+ /**
3103
+ * Compute the SHA1 of the given string
3104
+ *
3105
+ * see https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
3106
+ *
3107
+ * WARNING: this function has not been designed not tested with security in mind.
3108
+ * DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
3109
+ */
3110
+ function sha1(str) {
3111
+ textEncoder ??= new TextEncoder();
3112
+ const utf8 = [...textEncoder.encode(str)];
3113
+ const words32 = bytesToWords32(utf8, Endian.Big);
3114
+ const len = utf8.length * 8;
3115
+ const w = new Uint32Array(80);
3116
+ let a = 0x67452301,
3117
+ b = 0xefcdab89,
3118
+ c = 0x98badcfe,
3119
+ d = 0x10325476,
3120
+ e = 0xc3d2e1f0;
3121
+ words32[len >> 5] |= 0x80 << 24 - len % 32;
3122
+ words32[(len + 64 >> 9 << 4) + 15] = len;
3123
+ for (let i = 0; i < words32.length; i += 16) {
3124
+ const h0 = a,
3125
+ h1 = b,
3126
+ h2 = c,
3127
+ h3 = d,
3128
+ h4 = e;
3129
+ for (let j = 0; j < 80; j++) {
3130
+ if (j < 16) {
3131
+ w[j] = words32[i + j];
3132
+ } else {
3133
+ w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
3134
+ }
3135
+ const fkVal = fk(j, b, c, d);
3136
+ const f = fkVal[0];
3137
+ const k = fkVal[1];
3138
+ const temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
3139
+ e = d;
3140
+ d = c;
3141
+ c = rol32(b, 30);
3142
+ b = a;
3143
+ a = temp;
3144
+ }
3145
+ a = add32(a, h0);
3146
+ b = add32(b, h1);
3147
+ c = add32(c, h2);
3148
+ d = add32(d, h3);
3149
+ e = add32(e, h4);
3150
+ }
3151
+ // Convert the output parts to a 160-bit hexadecimal string
3152
+ return toHexU32(a) + toHexU32(b) + toHexU32(c) + toHexU32(d) + toHexU32(e);
3153
+ }
3154
+ /**
3155
+ * Convert and format a number as a string representing a 32-bit unsigned hexadecimal number.
3156
+ * @param value The value to format as a string.
3157
+ * @returns A hexadecimal string representing the value.
3158
+ */
3159
+ function toHexU32(value) {
3160
+ // unsigned right shift of zero ensures an unsigned 32-bit number
3161
+ return (value >>> 0).toString(16).padStart(8, '0');
3162
+ }
3163
+ function fk(index, b, c, d) {
3164
+ if (index < 20) {
3165
+ return [b & c | ~b & d, 0x5a827999];
3166
+ }
3167
+ if (index < 40) {
3168
+ return [b ^ c ^ d, 0x6ed9eba1];
3169
+ }
3170
+ if (index < 60) {
3171
+ return [b & c | b & d | c & d, 0x8f1bbcdc];
3172
+ }
3173
+ return [b ^ c ^ d, 0xca62c1d6];
3174
+ }
3175
+ /**
3176
+ * Compute the fingerprint of the given string
3177
+ *
3178
+ * The output is 64 bit number encoded as a decimal string
3179
+ *
3180
+ * based on:
3181
+ * https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
3182
+ */
3183
+ function fingerprint(str) {
3184
+ textEncoder ??= new TextEncoder();
3185
+ const utf8 = textEncoder.encode(str);
3186
+ const view = new DataView(utf8.buffer, utf8.byteOffset, utf8.byteLength);
3187
+ let hi = hash32(view, utf8.length, 0);
3188
+ let lo = hash32(view, utf8.length, 102072);
3189
+ if (hi == 0 && (lo == 0 || lo == 1)) {
3190
+ hi = hi ^ 0x130f9bef;
3191
+ lo = lo ^ -0x6b5f56d8;
3192
+ }
3193
+ return BigInt.asUintN(32, BigInt(hi)) << BigInt(32) | BigInt.asUintN(32, BigInt(lo));
3194
+ }
3195
+ function computeMsgId(msg, meaning = '') {
3196
+ let msgFingerprint = fingerprint(msg);
3197
+ if (meaning) {
3198
+ // Rotate the 64-bit message fingerprint one bit to the left and then add the meaning
3199
+ // fingerprint.
3200
+ msgFingerprint = BigInt.asUintN(64, msgFingerprint << BigInt(1)) | msgFingerprint >> BigInt(63) & BigInt(1);
3201
+ msgFingerprint += fingerprint(meaning);
3202
+ }
3203
+ return BigInt.asUintN(63, msgFingerprint).toString();
3204
+ }
3205
+ function hash32(view, length, c) {
3206
+ let a = 0x9e3779b9,
3207
+ b = 0x9e3779b9;
3208
+ let index = 0;
3209
+ const end = length - 12;
3210
+ for (; index <= end; index += 12) {
3211
+ a += view.getUint32(index, true);
3212
+ b += view.getUint32(index + 4, true);
3213
+ c += view.getUint32(index + 8, true);
3214
+ const res = mix(a, b, c);
3215
+ a = res[0], b = res[1], c = res[2];
3216
+ }
3217
+ const remainder = length - index;
3218
+ // the first byte of c is reserved for the length
3219
+ c += length;
3220
+ if (remainder >= 4) {
3221
+ a += view.getUint32(index, true);
3222
+ index += 4;
3223
+ if (remainder >= 8) {
3224
+ b += view.getUint32(index, true);
3225
+ index += 4;
3226
+ // Partial 32-bit word for c
3227
+ if (remainder >= 9) {
3228
+ c += view.getUint8(index++) << 8;
3229
+ }
3230
+ if (remainder >= 10) {
3231
+ c += view.getUint8(index++) << 16;
3232
+ }
3233
+ if (remainder === 11) {
3234
+ c += view.getUint8(index++) << 24;
3235
+ }
3236
+ } else {
3237
+ // Partial 32-bit word for b
3238
+ if (remainder >= 5) {
3239
+ b += view.getUint8(index++);
3240
+ }
3241
+ if (remainder >= 6) {
3242
+ b += view.getUint8(index++) << 8;
3243
+ }
3244
+ if (remainder === 7) {
3245
+ b += view.getUint8(index++) << 16;
3246
+ }
3247
+ }
3248
+ } else {
3249
+ // Partial 32-bit word for a
3250
+ if (remainder >= 1) {
3251
+ a += view.getUint8(index++);
3252
+ }
3253
+ if (remainder >= 2) {
3254
+ a += view.getUint8(index++) << 8;
3255
+ }
3256
+ if (remainder === 3) {
3257
+ a += view.getUint8(index++) << 16;
3258
+ }
3259
+ }
3260
+ return mix(a, b, c)[2];
3261
+ }
3262
+ // clang-format off
3263
+ function mix(a, b, c) {
3264
+ a -= b;
3265
+ a -= c;
3266
+ a ^= c >>> 13;
3267
+ b -= c;
3268
+ b -= a;
3269
+ b ^= a << 8;
3270
+ c -= a;
3271
+ c -= b;
3272
+ c ^= b >>> 13;
3273
+ a -= b;
3274
+ a -= c;
3275
+ a ^= c >>> 12;
3276
+ b -= c;
3277
+ b -= a;
3278
+ b ^= a << 16;
3279
+ c -= a;
3280
+ c -= b;
3281
+ c ^= b >>> 5;
3282
+ a -= b;
3283
+ a -= c;
3284
+ a ^= c >>> 3;
3285
+ b -= c;
3286
+ b -= a;
3287
+ b ^= a << 10;
3288
+ c -= a;
3289
+ c -= b;
3290
+ c ^= b >>> 15;
3291
+ return [a, b, c];
3292
+ }
3293
+ // clang-format on
3294
+ // Utils
3295
+ var Endian;
3296
+ (function (Endian) {
3297
+ Endian[Endian["Little"] = 0] = "Little";
3298
+ Endian[Endian["Big"] = 1] = "Big";
3299
+ })(Endian || (Endian = {}));
3300
+ function add32(a, b) {
3301
+ return add32to64(a, b)[1];
3302
+ }
3303
+ function add32to64(a, b) {
3304
+ const low = (a & 0xffff) + (b & 0xffff);
3305
+ const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
3306
+ return [high >>> 16, high << 16 | low & 0xffff];
3307
+ }
3308
+ // Rotate a 32b number left `count` position
3309
+ function rol32(a, count) {
3310
+ return a << count | a >>> 32 - count;
3311
+ }
3312
+ function bytesToWords32(bytes, endian) {
3313
+ const size = bytes.length + 3 >>> 2;
3314
+ const words32 = [];
3315
+ for (let i = 0; i < size; i++) {
3316
+ words32[i] = wordAt(bytes, i * 4, endian);
3317
+ }
3318
+ return words32;
3319
+ }
3320
+ function byteAt(bytes, index) {
3321
+ return index >= bytes.length ? 0 : bytes[index];
3322
+ }
3323
+ function wordAt(bytes, index, endian) {
3324
+ let word = 0;
3325
+ if (endian === Endian.Big) {
3326
+ for (let i = 0; i < 4; i++) {
3327
+ word += byteAt(bytes, index + i) << 24 - 8 * i;
3328
+ }
3329
+ } else {
3330
+ for (let i = 0; i < 4; i++) {
3331
+ word += byteAt(bytes, index + i) << 8 * i;
3332
+ }
3333
+ }
3334
+ return word;
3335
+ }
3336
+
3337
+ // This module specifier is intentionally a relative path to allow bundling the code directly
3338
+ /**
3339
+ * Parse a `$localize` tagged string into a structure that can be used for translation or
3340
+ * extraction.
3341
+ *
3342
+ * See `ParsedMessage` for an example.
3343
+ */
3344
+ function parseMessage(messageParts, expressions, location, messagePartLocations, expressionLocations = []) {
3345
+ const substitutions = {};
3346
+ const substitutionLocations = {};
3347
+ const associatedMessageIds = {};
3348
+ const metadata = parseMetadata(messageParts[0], messageParts.raw[0]);
3349
+ const cleanedMessageParts = [metadata.text];
3350
+ const placeholderNames = [];
3351
+ let messageString = metadata.text;
3352
+ for (let i = 1; i < messageParts.length; i++) {
3353
+ const {
3354
+ messagePart,
3355
+ placeholderName = computePlaceholderName(i),
3356
+ associatedMessageId
3357
+ } = parsePlaceholder(messageParts[i], messageParts.raw[i]);
3358
+ messageString += `{$${placeholderName}}${messagePart}`;
3359
+ if (expressions !== undefined) {
3360
+ substitutions[placeholderName] = expressions[i - 1];
3361
+ substitutionLocations[placeholderName] = expressionLocations[i - 1];
3362
+ }
3363
+ placeholderNames.push(placeholderName);
3364
+ if (associatedMessageId !== undefined) {
3365
+ associatedMessageIds[placeholderName] = associatedMessageId;
3366
+ }
3367
+ cleanedMessageParts.push(messagePart);
3368
+ }
3369
+ const messageId = metadata.customId || computeMsgId(messageString, metadata.meaning || '');
3370
+ const legacyIds = metadata.legacyIds ? metadata.legacyIds.filter(id => id !== messageId) : [];
3371
+ return {
3372
+ id: messageId,
3373
+ legacyIds,
3374
+ substitutions,
3375
+ substitutionLocations,
3376
+ text: messageString,
3377
+ customId: metadata.customId,
3378
+ meaning: metadata.meaning || '',
3379
+ description: metadata.description || '',
3380
+ messageParts: cleanedMessageParts,
3381
+ messagePartLocations,
3382
+ placeholderNames,
3383
+ associatedMessageIds,
3384
+ location
3385
+ };
3386
+ }
3387
+ /**
3388
+ * Parse the given message part (`cooked` + `raw`) to extract the message metadata from the text.
3389
+ *
3390
+ * If the message part has a metadata block this function will extract the `meaning`,
3391
+ * `description`, `customId` and `legacyId` (if provided) from the block. These metadata properties
3392
+ * are serialized in the string delimited by `|`, `@@` and `␟` respectively.
3393
+ *
3394
+ * (Note that `␟` is the `LEGACY_ID_INDICATOR` - see `constants.ts`.)
3395
+ *
3396
+ * For example:
3397
+ *
3398
+ * ```ts
3399
+ * `:meaning|description@@custom-id:`
3400
+ * `:meaning|@@custom-id:`
3401
+ * `:meaning|description:`
3402
+ * `:description@@custom-id:`
3403
+ * `:meaning|:`
3404
+ * `:description:`
3405
+ * `:@@custom-id:`
3406
+ * `:meaning|description@@custom-id␟legacy-id-1␟legacy-id-2:`
3407
+ * ```
3408
+ *
3409
+ * @param cooked The cooked version of the message part to parse.
3410
+ * @param raw The raw version of the message part to parse.
3411
+ * @returns A object containing any metadata that was parsed from the message part.
3412
+ */
3413
+ function parseMetadata(cooked, raw) {
3414
+ const {
3415
+ text: messageString,
3416
+ block
3417
+ } = splitBlock(cooked, raw);
3418
+ if (block === undefined) {
3419
+ return {
3420
+ text: messageString
3421
+ };
3422
+ } else {
3423
+ const [meaningDescAndId, ...legacyIds] = block.split(LEGACY_ID_INDICATOR);
3424
+ const [meaningAndDesc, customId] = meaningDescAndId.split(ID_SEPARATOR, 2);
3425
+ let [meaning, description] = meaningAndDesc.split(MEANING_SEPARATOR, 2);
3426
+ if (description === undefined) {
3427
+ description = meaning;
3428
+ meaning = undefined;
3429
+ }
3430
+ if (description === '') {
3431
+ description = undefined;
3432
+ }
3433
+ return {
3434
+ text: messageString,
3435
+ meaning,
3436
+ description,
3437
+ customId,
3438
+ legacyIds
3439
+ };
3440
+ }
3441
+ }
3442
+ /**
3443
+ * Parse the given message part (`cooked` + `raw`) to extract any placeholder metadata from the
3444
+ * text.
3445
+ *
3446
+ * If the message part has a metadata block this function will extract the `placeholderName` and
3447
+ * `associatedMessageId` (if provided) from the block.
3448
+ *
3449
+ * These metadata properties are serialized in the string delimited by `@@`.
3450
+ *
3451
+ * For example:
3452
+ *
3453
+ * ```ts
3454
+ * `:placeholder-name@@associated-id:`
3455
+ * ```
3456
+ *
3457
+ * @param cooked The cooked version of the message part to parse.
3458
+ * @param raw The raw version of the message part to parse.
3459
+ * @returns A object containing the metadata (`placeholderName` and `associatedMessageId`) of the
3460
+ * preceding placeholder, along with the static text that follows.
3461
+ */
3462
+ function parsePlaceholder(cooked, raw) {
3463
+ const {
3464
+ text: messagePart,
3465
+ block
3466
+ } = splitBlock(cooked, raw);
3467
+ if (block === undefined) {
3468
+ return {
3469
+ messagePart
3470
+ };
3471
+ } else {
3472
+ const [placeholderName, associatedMessageId] = block.split(ID_SEPARATOR);
3473
+ return {
3474
+ messagePart,
3475
+ placeholderName,
3476
+ associatedMessageId
3477
+ };
3478
+ }
3479
+ }
3480
+ /**
3481
+ * Split a message part (`cooked` + `raw`) into an optional delimited "block" off the front and the
3482
+ * rest of the text of the message part.
3483
+ *
3484
+ * Blocks appear at the start of message parts. They are delimited by a colon `:` character at the
3485
+ * start and end of the block.
3486
+ *
3487
+ * If the block is in the first message part then it will be metadata about the whole message:
3488
+ * meaning, description, id. Otherwise it will be metadata about the immediately preceding
3489
+ * substitution: placeholder name.
3490
+ *
3491
+ * Since blocks are optional, it is possible that the content of a message block actually starts
3492
+ * with a block marker. In this case the marker must be escaped `\:`.
3493
+ *
3494
+ * @param cooked The cooked version of the message part to parse.
3495
+ * @param raw The raw version of the message part to parse.
3496
+ * @returns An object containing the `text` of the message part and the text of the `block`, if it
3497
+ * exists.
3498
+ * @throws an error if the `block` is unterminated
3499
+ */
3500
+ function splitBlock(cooked, raw) {
3501
+ if (raw.charAt(0) !== BLOCK_MARKER$1) {
3502
+ return {
3503
+ text: cooked
3504
+ };
3505
+ } else {
3506
+ const endOfBlock = findEndOfBlock(cooked, raw);
3507
+ return {
3508
+ block: cooked.substring(1, endOfBlock),
3509
+ text: cooked.substring(endOfBlock + 1)
3510
+ };
3511
+ }
3512
+ }
3513
+ function computePlaceholderName(index) {
3514
+ return index === 1 ? 'PH' : `PH_${index - 1}`;
3515
+ }
3516
+ /**
3517
+ * Find the end of a "marked block" indicated by the first non-escaped colon.
3518
+ *
3519
+ * @param cooked The cooked string (where escaped chars have been processed)
3520
+ * @param raw The raw string (where escape sequences are still in place)
3521
+ *
3522
+ * @returns the index of the end of block marker
3523
+ * @throws an error if the block is unterminated
3524
+ */
3525
+ function findEndOfBlock(cooked, raw) {
3526
+ for (let cookedIndex = 1, rawIndex = 1; cookedIndex < cooked.length; cookedIndex++, rawIndex++) {
3527
+ if (raw[rawIndex] === '\\') {
3528
+ rawIndex++;
3529
+ } else if (cooked[cookedIndex] === BLOCK_MARKER$1) {
3530
+ return cookedIndex;
3531
+ }
3532
+ }
3533
+ throw new Error(`Unterminated $localize metadata block in "${raw}".`);
3534
+ }
3535
+ class MissingTranslationError extends Error {
3536
+ constructor(parsedMessage) {
3537
+ super(`No translation found for ${describeMessage(parsedMessage)}.`);
3538
+ this.parsedMessage = parsedMessage;
3539
+ this.type = 'MissingTranslationError';
3540
+ }
3541
+ }
3542
+ function isMissingTranslationError(e) {
3543
+ return e.type === 'MissingTranslationError';
3544
+ }
3545
+ /**
3546
+ * Translate the text of the `$localize` tagged-string (i.e. `messageParts` and
3547
+ * `substitutions`) using the given `translations`.
3548
+ *
3549
+ * The tagged-string is parsed to extract its `messageId` which is used to find an appropriate
3550
+ * `ParsedTranslation`. If this doesn't match and there are legacy ids then try matching a
3551
+ * translation using those.
3552
+ *
3553
+ * If one is found then it is used to translate the message into a new set of `messageParts` and
3554
+ * `substitutions`.
3555
+ * The translation may reorder (or remove) substitutions as appropriate.
3556
+ *
3557
+ * If there is no translation with a matching message id then an error is thrown.
3558
+ * If a translation contains a placeholder that is not found in the message being translated then an
3559
+ * error is thrown.
3560
+ */
3561
+ function translate$1(translations, messageParts, substitutions) {
3562
+ const message = parseMessage(messageParts, substitutions);
3563
+ // Look up the translation using the messageId, and then the legacyId if available.
3564
+ let translation = translations[message.id];
3565
+ // If the messageId did not match a translation, try matching the legacy ids instead
3566
+ if (message.legacyIds !== undefined) {
3567
+ for (let i = 0; i < message.legacyIds.length && translation === undefined; i++) {
3568
+ translation = translations[message.legacyIds[i]];
3569
+ }
3570
+ }
3571
+ if (translation === undefined) {
3572
+ throw new MissingTranslationError(message);
3573
+ }
3574
+ return [translation.messageParts, translation.placeholderNames.map(placeholder => {
3575
+ if (message.substitutions.hasOwnProperty(placeholder)) {
3576
+ return message.substitutions[placeholder];
3577
+ } else {
3578
+ throw new Error(`There is a placeholder name mismatch with the translation provided for the message ${describeMessage(message)}.\n` + `The translation contains a placeholder with name ${placeholder}, which does not exist in the message.`);
3579
+ }
3580
+ })];
3581
+ }
3582
+ /**
3583
+ * Parse the `messageParts` and `placeholderNames` out of a target `message`.
3584
+ *
3585
+ * Used by `loadTranslations()` to convert target message strings into a structure that is more
3586
+ * appropriate for doing translation.
3587
+ *
3588
+ * @param message the message to be parsed.
3589
+ */
3590
+ function parseTranslation(messageString) {
3591
+ const parts = messageString.split(/{\$([^}]*)}/);
3592
+ const messageParts = [parts[0]];
3593
+ const placeholderNames = [];
3594
+ for (let i = 1; i < parts.length - 1; i += 2) {
3595
+ placeholderNames.push(parts[i]);
3596
+ messageParts.push(`${parts[i + 1]}`);
3597
+ }
3598
+ const rawMessageParts = messageParts.map(part => part.charAt(0) === BLOCK_MARKER$1 ? '\\' + part : part);
3599
+ return {
3600
+ text: messageString,
3601
+ messageParts: makeTemplateObject(messageParts, rawMessageParts),
3602
+ placeholderNames
3603
+ };
3604
+ }
3605
+ /**
3606
+ * Create a `ParsedTranslation` from a set of `messageParts` and `placeholderNames`.
3607
+ *
3608
+ * @param messageParts The message parts to appear in the ParsedTranslation.
3609
+ * @param placeholderNames The names of the placeholders to intersperse between the `messageParts`.
3610
+ */
3611
+ function makeParsedTranslation(messageParts, placeholderNames = []) {
3612
+ let messageString = messageParts[0];
3613
+ for (let i = 0; i < placeholderNames.length; i++) {
3614
+ messageString += `{$${placeholderNames[i]}}${messageParts[i + 1]}`;
3615
+ }
3616
+ return {
3617
+ text: messageString,
3618
+ messageParts: makeTemplateObject(messageParts, messageParts),
3619
+ placeholderNames
3620
+ };
3621
+ }
3622
+ /**
3623
+ * Create the specialized array that is passed to tagged-string tag functions.
3624
+ *
3625
+ * @param cooked The message parts with their escape codes processed.
3626
+ * @param raw The message parts with their escaped codes as-is.
3627
+ */
3628
+ function makeTemplateObject(cooked, raw) {
3629
+ Object.defineProperty(cooked, 'raw', {
3630
+ value: raw
3631
+ });
3632
+ return cooked;
3633
+ }
3634
+ function describeMessage(message) {
3635
+ const meaningString = message.meaning && ` - "${message.meaning}"`;
3636
+ const legacy = message.legacyIds && message.legacyIds.length > 0 ? ` [${message.legacyIds.map(l => `"${l}"`).join(', ')}]` : '';
3637
+ return `"${message.id}"${legacy} ("${message.text}"${meaningString})`;
3638
+ }
3639
+
3640
+ /**
3641
+ * Load translations for use by `$localize`, if doing runtime translation.
3642
+ *
3643
+ * If the `$localize` tagged strings are not going to be replaced at compiled time, it is possible
3644
+ * to load a set of translations that will be applied to the `$localize` tagged strings at runtime,
3645
+ * in the browser.
3646
+ *
3647
+ * Loading a new translation will overwrite a previous translation if it has the same `MessageId`.
3648
+ *
3649
+ * Note that `$localize` messages are only processed once, when the tagged string is first
3650
+ * encountered, and does not provide dynamic language changing without refreshing the browser.
3651
+ * Loading new translations later in the application life-cycle will not change the translated text
3652
+ * of messages that have already been translated.
3653
+ *
3654
+ * The message IDs and translations are in the same format as that rendered to "simple JSON"
3655
+ * translation files when extracting messages. In particular, placeholders in messages are rendered
3656
+ * using the `{$PLACEHOLDER_NAME}` syntax. For example the message from the following template:
3657
+ *
3658
+ * ```html
3659
+ * <div i18n>pre<span>inner-pre<b>bold</b>inner-post</span>post</div>
3660
+ * ```
3661
+ *
3662
+ * would have the following form in the `translations` map:
3663
+ *
3664
+ * ```ts
3665
+ * {
3666
+ * "2932901491976224757":
3667
+ * "pre{$START_TAG_SPAN}inner-pre{$START_BOLD_TEXT}bold{$CLOSE_BOLD_TEXT}inner-post{$CLOSE_TAG_SPAN}post"
3668
+ * }
3669
+ * ```
3670
+ *
3671
+ * @param translations A map from message ID to translated message.
3672
+ *
3673
+ * These messages are processed and added to a lookup based on their `MessageId`.
3674
+ *
3675
+ * @see {@link clearTranslations} for removing translations loaded using this function.
3676
+ * @see {@link $localize} for tagging messages as needing to be translated.
3677
+ * @publicApi
3678
+ */
3679
+ function loadTranslations(translations) {
3680
+ // Ensure the translate function exists
3681
+ if (!$localize.translate) {
3682
+ $localize.translate = translate;
3683
+ }
3684
+ if (!$localize.TRANSLATIONS) {
3685
+ $localize.TRANSLATIONS = {};
3686
+ }
3687
+ Object.keys(translations).forEach(key => {
3688
+ $localize.TRANSLATIONS[key] = parseTranslation(translations[key]);
3689
+ });
3690
+ }
3691
+ /**
3692
+ * Remove all translations for `$localize`, if doing runtime translation.
3693
+ *
3694
+ * All translations that had been loading into memory using `loadTranslations()` will be removed.
3695
+ *
3696
+ * @see {@link loadTranslations} for loading translations at runtime.
3697
+ * @see {@link $localize} for tagging messages as needing to be translated.
3698
+ *
3699
+ * @publicApi
3700
+ */
3701
+ function clearTranslations() {
3702
+ $localize.translate = undefined;
3703
+ $localize.TRANSLATIONS = {};
3704
+ }
3705
+ /**
3706
+ * Translate the text of the given message, using the loaded translations.
3707
+ *
3708
+ * This function may reorder (or remove) substitutions as indicated in the matching translation.
3709
+ */
3710
+ function translate(messageParts, substitutions) {
3711
+ try {
3712
+ return translate$1($localize.TRANSLATIONS, messageParts, substitutions);
3713
+ } catch (e) {
3714
+ console.warn(e.message);
3715
+ return [messageParts, substitutions];
3716
+ }
3717
+ }
3718
+
3719
+ /**
3720
+ * Tag a template literal string for localization.
3721
+ *
3722
+ * For example:
3723
+ *
3724
+ * ```ts
3725
+ * $localize `some string to localize`
3726
+ * ```
3727
+ *
3728
+ * **Providing meaning, description and id**
3729
+ *
3730
+ * You can optionally specify one or more of `meaning`, `description` and `id` for a localized
3731
+ * string by pre-pending it with a colon delimited block of the form:
3732
+ *
3733
+ * ```ts
3734
+ * $localize`:meaning|description@@id:source message text`;
3735
+ *
3736
+ * $localize`:meaning|:source message text`;
3737
+ * $localize`:description:source message text`;
3738
+ * $localize`:@@id:source message text`;
3739
+ * ```
3740
+ *
3741
+ * This format is the same as that used for `i18n` markers in Angular templates. See the
3742
+ * [Angular i18n guide](guide/i18n-common-prepare#mark-text-in-component-template).
3743
+ *
3744
+ * **Naming placeholders**
3745
+ *
3746
+ * If the template literal string contains expressions, then the expressions will be automatically
3747
+ * associated with placeholder names for you.
3748
+ *
3749
+ * For example:
3750
+ *
3751
+ * ```ts
3752
+ * $localize `Hi ${name}! There are ${items.length} items.`;
3753
+ * ```
3754
+ *
3755
+ * will generate a message-source of `Hi {$PH}! There are {$PH_1} items`.
3756
+ *
3757
+ * The recommended practice is to name the placeholder associated with each expression though.
3758
+ *
3759
+ * Do this by providing the placeholder name wrapped in `:` characters directly after the
3760
+ * expression. These placeholder names are stripped out of the rendered localized string.
3761
+ *
3762
+ * For example, to name the `items.length` expression placeholder `itemCount` you write:
3763
+ *
3764
+ * ```ts
3765
+ * $localize `There are ${items.length}:itemCount: items`;
3766
+ * ```
3767
+ *
3768
+ * **Escaping colon markers**
3769
+ *
3770
+ * If you need to use a `:` character directly at the start of a tagged string that has no
3771
+ * metadata block, or directly after a substitution expression that has no name you must escape
3772
+ * the `:` by preceding it with a backslash:
3773
+ *
3774
+ * For example:
3775
+ *
3776
+ * ```ts
3777
+ * // message has a metadata block so no need to escape colon
3778
+ * $localize `:some description::this message starts with a colon (:)`;
3779
+ * // no metadata block so the colon must be escaped
3780
+ * $localize `\:this message starts with a colon (:)`;
3781
+ * ```
3782
+ *
3783
+ * ```ts
3784
+ * // named substitution so no need to escape colon
3785
+ * $localize `${label}:label:: ${}`
3786
+ * // anonymous substitution so colon must be escaped
3787
+ * $localize `${label}\: ${}`
3788
+ * ```
3789
+ *
3790
+ * **Processing localized strings:**
3791
+ *
3792
+ * There are three scenarios:
3793
+ *
3794
+ * * **compile-time inlining**: the `$localize` tag is transformed at compile time by a
3795
+ * transpiler, removing the tag and replacing the template literal string with a translated
3796
+ * literal string from a collection of translations provided to the transpilation tool.
3797
+ *
3798
+ * * **run-time evaluation**: the `$localize` tag is a run-time function that replaces and
3799
+ * reorders the parts (static strings and expressions) of the template literal string with strings
3800
+ * from a collection of translations loaded at run-time.
3801
+ *
3802
+ * * **pass-through evaluation**: the `$localize` tag is a run-time function that simply evaluates
3803
+ * the original template literal string without applying any translations to the parts. This
3804
+ * version is used during development or where there is no need to translate the localized
3805
+ * template literals.
3806
+ *
3807
+ * @param messageParts a collection of the static parts of the template string.
3808
+ * @param expressions a collection of the values of each placeholder in the template string.
3809
+ * @returns the translated string, with the `messageParts` and `expressions` interleaved together.
3810
+ *
3811
+ * @globalApi
3812
+ * @publicApi
3813
+ */
3814
+ const $localize$1 = function (messageParts, ...expressions) {
3815
+ if ($localize$1.translate) {
3816
+ // Don't use array expansion here to avoid the compiler adding `__read()` helper unnecessarily.
3817
+ const translation = $localize$1.translate(messageParts, expressions);
3818
+ messageParts = translation[0];
3819
+ expressions = translation[1];
3820
+ }
3821
+ let message = stripBlock(messageParts[0], messageParts.raw[0]);
3822
+ for (let i = 1; i < messageParts.length; i++) {
3823
+ message += expressions[i - 1] + stripBlock(messageParts[i], messageParts.raw[i]);
3824
+ }
3825
+ return message;
3826
+ };
3827
+ const BLOCK_MARKER = ':';
3828
+ /**
3829
+ * Strip a delimited "block" from the start of the `messagePart`, if it is found.
3830
+ *
3831
+ * If a marker character (:) actually appears in the content at the start of a tagged string or
3832
+ * after a substitution expression, where a block has not been provided the character must be
3833
+ * escaped with a backslash, `\:`. This function checks for this by looking at the `raw`
3834
+ * messagePart, which should still contain the backslash.
3835
+ *
3836
+ * @param messagePart The cooked message part to process.
3837
+ * @param rawMessagePart The raw message part to check.
3838
+ * @returns the message part with the placeholder name stripped, if found.
3839
+ * @throws an error if the block is unterminated
3840
+ */
3841
+ function stripBlock(messagePart, rawMessagePart) {
3842
+ return rawMessagePart.charAt(0) === BLOCK_MARKER ? messagePart.substring(findEndOfBlock(messagePart, rawMessagePart) + 1) : messagePart;
3843
+ }
3844
+
3845
+ // This file exports all the `utils` as private exports so that other parts of `@angular/localize`
3846
+
3847
+ // This file contains the public API of the `@angular/localize` entry-point
3848
+
3849
+ // DO NOT ADD public exports to this file.
3850
+
3851
+
3852
+
3853
+ /***/ })
3854
+
3855
+ },
3856
+ /******/ __webpack_require__ => { // webpackRuntimeModules
3857
+ /******/ var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
3858
+ /******/ var __webpack_exports__ = (__webpack_exec__(10762));
3859
+ /******/ }
3860
+ ]);
3861
+ //# sourceMappingURL=polyfills.js.map