@angular/upgrade 19.2.0 → 19.2.2

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.
@@ -0,0 +1,1242 @@
1
+ /**
2
+ * @license Angular v19.2.2
3
+ * (c) 2010-2025 Google LLC. https://angular.io/
4
+ * License: MIT
5
+ */
6
+
7
+ import { Version, ɵNG_MOD_DEF as _NG_MOD_DEF, Injector, ChangeDetectorRef, Testability, TestabilityRegistry, ApplicationRef, SimpleChange, ɵSIGNAL as _SIGNAL, NgZone, ComponentFactoryResolver } from '@angular/core';
8
+
9
+ /**
10
+ * @module
11
+ * @description
12
+ * Entry point for all public APIs of the upgrade package.
13
+ */
14
+ /**
15
+ * @publicApi
16
+ */
17
+ const VERSION = new Version('19.2.2');
18
+
19
+ function noNg() {
20
+ throw new Error('AngularJS v1.x is not loaded!');
21
+ }
22
+ const noNgElement = (() => noNg());
23
+ noNgElement.cleanData = noNg;
24
+ let angular = {
25
+ bootstrap: noNg,
26
+ module: noNg,
27
+ element: noNgElement,
28
+ injector: noNg,
29
+ version: undefined,
30
+ resumeBootstrap: noNg,
31
+ getTestability: noNg,
32
+ };
33
+ try {
34
+ if (window.hasOwnProperty('angular')) {
35
+ angular = window.angular;
36
+ }
37
+ }
38
+ catch {
39
+ // ignore in CJS mode.
40
+ }
41
+ /**
42
+ * @deprecated Use `setAngularJSGlobal` instead.
43
+ *
44
+ * @publicApi
45
+ */
46
+ function setAngularLib(ng) {
47
+ setAngularJSGlobal(ng);
48
+ }
49
+ /**
50
+ * @deprecated Use `getAngularJSGlobal` instead.
51
+ *
52
+ * @publicApi
53
+ */
54
+ function getAngularLib() {
55
+ return getAngularJSGlobal();
56
+ }
57
+ /**
58
+ * Resets the AngularJS global.
59
+ *
60
+ * Used when AngularJS is loaded lazily, and not available on `window`.
61
+ *
62
+ * @publicApi
63
+ */
64
+ function setAngularJSGlobal(ng) {
65
+ angular = ng;
66
+ }
67
+ /**
68
+ * Returns the current AngularJS global.
69
+ *
70
+ * @publicApi
71
+ */
72
+ function getAngularJSGlobal() {
73
+ return angular;
74
+ }
75
+ const bootstrap = (e, modules, config) => angular.bootstrap(e, modules, config);
76
+ // Do not declare as `module` to avoid webpack bug
77
+ // (see https://github.com/angular/angular/issues/30050).
78
+ const module_ = (prefix, dependencies) => angular.module(prefix, dependencies);
79
+ const element = ((e) => angular.element(e));
80
+ element.cleanData = (nodes) => angular.element.cleanData(nodes);
81
+ const injector = (modules, strictDi) => angular.injector(modules, strictDi);
82
+ const resumeBootstrap = () => angular.resumeBootstrap();
83
+ const getTestability = (e) => angular.getTestability(e);
84
+
85
+ var angular1 = /*#__PURE__*/Object.freeze({
86
+ __proto__: null,
87
+ bootstrap: bootstrap,
88
+ element: element,
89
+ getAngularJSGlobal: getAngularJSGlobal,
90
+ getAngularLib: getAngularLib,
91
+ getTestability: getTestability,
92
+ injector: injector,
93
+ module_: module_,
94
+ resumeBootstrap: resumeBootstrap,
95
+ setAngularJSGlobal: setAngularJSGlobal,
96
+ setAngularLib: setAngularLib
97
+ });
98
+
99
+ const $COMPILE = '$compile';
100
+ const $CONTROLLER = '$controller';
101
+ const $DELEGATE = '$delegate';
102
+ const $EXCEPTION_HANDLER = '$exceptionHandler';
103
+ const $HTTP_BACKEND = '$httpBackend';
104
+ const $INJECTOR = '$injector';
105
+ const $INTERVAL = '$interval';
106
+ const $PARSE = '$parse';
107
+ const $PROVIDE = '$provide';
108
+ const $ROOT_ELEMENT = '$rootElement';
109
+ const $ROOT_SCOPE = '$rootScope';
110
+ const $SCOPE = '$scope';
111
+ const $TEMPLATE_CACHE = '$templateCache';
112
+ const $TEMPLATE_REQUEST = '$templateRequest';
113
+ const $$TESTABILITY = '$$testability';
114
+ const COMPILER_KEY = '$$angularCompiler';
115
+ const DOWNGRADED_MODULE_COUNT_KEY = '$$angularDowngradedModuleCount';
116
+ const GROUP_PROJECTABLE_NODES_KEY = '$$angularGroupProjectableNodes';
117
+ const INJECTOR_KEY = '$$angularInjector';
118
+ const LAZY_MODULE_REF = '$$angularLazyModuleRef';
119
+ const NG_ZONE_KEY = '$$angularNgZone';
120
+ const UPGRADE_APP_TYPE_KEY = '$$angularUpgradeAppType';
121
+ const REQUIRE_INJECTOR = '?^^' + INJECTOR_KEY;
122
+ const REQUIRE_NG_MODEL = '?ngModel';
123
+ const UPGRADE_MODULE_NAME = '$$UpgradeModule';
124
+
125
+ var constants = /*#__PURE__*/Object.freeze({
126
+ __proto__: null,
127
+ $$TESTABILITY: $$TESTABILITY,
128
+ $COMPILE: $COMPILE,
129
+ $CONTROLLER: $CONTROLLER,
130
+ $DELEGATE: $DELEGATE,
131
+ $EXCEPTION_HANDLER: $EXCEPTION_HANDLER,
132
+ $HTTP_BACKEND: $HTTP_BACKEND,
133
+ $INJECTOR: $INJECTOR,
134
+ $INTERVAL: $INTERVAL,
135
+ $PARSE: $PARSE,
136
+ $PROVIDE: $PROVIDE,
137
+ $ROOT_ELEMENT: $ROOT_ELEMENT,
138
+ $ROOT_SCOPE: $ROOT_SCOPE,
139
+ $SCOPE: $SCOPE,
140
+ $TEMPLATE_CACHE: $TEMPLATE_CACHE,
141
+ $TEMPLATE_REQUEST: $TEMPLATE_REQUEST,
142
+ COMPILER_KEY: COMPILER_KEY,
143
+ DOWNGRADED_MODULE_COUNT_KEY: DOWNGRADED_MODULE_COUNT_KEY,
144
+ GROUP_PROJECTABLE_NODES_KEY: GROUP_PROJECTABLE_NODES_KEY,
145
+ INJECTOR_KEY: INJECTOR_KEY,
146
+ LAZY_MODULE_REF: LAZY_MODULE_REF,
147
+ NG_ZONE_KEY: NG_ZONE_KEY,
148
+ REQUIRE_INJECTOR: REQUIRE_INJECTOR,
149
+ REQUIRE_NG_MODEL: REQUIRE_NG_MODEL,
150
+ UPGRADE_APP_TYPE_KEY: UPGRADE_APP_TYPE_KEY,
151
+ UPGRADE_MODULE_NAME: UPGRADE_MODULE_NAME
152
+ });
153
+
154
+ /**
155
+ * A `PropertyBinding` represents a mapping between a property name
156
+ * and an attribute name. It is parsed from a string of the form
157
+ * `"prop: attr"`; or simply `"propAndAttr" where the property
158
+ * and attribute have the same identifier.
159
+ */
160
+ class PropertyBinding {
161
+ prop;
162
+ attr;
163
+ bracketAttr;
164
+ bracketParenAttr;
165
+ parenAttr;
166
+ onAttr;
167
+ bindAttr;
168
+ bindonAttr;
169
+ constructor(prop, attr) {
170
+ this.prop = prop;
171
+ this.attr = attr;
172
+ this.bracketAttr = `[${this.attr}]`;
173
+ this.parenAttr = `(${this.attr})`;
174
+ this.bracketParenAttr = `[(${this.attr})]`;
175
+ const capitalAttr = this.attr.charAt(0).toUpperCase() + this.attr.slice(1);
176
+ this.onAttr = `on${capitalAttr}`;
177
+ this.bindAttr = `bind${capitalAttr}`;
178
+ this.bindonAttr = `bindon${capitalAttr}`;
179
+ }
180
+ }
181
+
182
+ const DIRECTIVE_PREFIX_REGEXP = /^(?:x|data)[:\-_]/i;
183
+ const DIRECTIVE_SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
184
+ function onError(e) {
185
+ // TODO: (misko): We seem to not have a stack trace here!
186
+ console.error(e, e.stack);
187
+ throw e;
188
+ }
189
+ /**
190
+ * Clean the jqLite/jQuery data on the element and all its descendants.
191
+ * Equivalent to how jqLite/jQuery invoke `cleanData()` on an Element when removed:
192
+ * https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/jqLite.js#L349-L355
193
+ * https://github.com/jquery/jquery/blob/6984d1747623dbc5e87fd6c261a5b6b1628c107c/src/manipulation.js#L182
194
+ *
195
+ * NOTE:
196
+ * `cleanData()` will also invoke the AngularJS `$destroy` DOM event on the element:
197
+ * https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/Angular.js#L1932-L1945
198
+ *
199
+ * @param node The DOM node whose data needs to be cleaned.
200
+ */
201
+ function cleanData(node) {
202
+ element.cleanData([node]);
203
+ if (isParentNode(node)) {
204
+ element.cleanData(node.querySelectorAll('*'));
205
+ }
206
+ }
207
+ function controllerKey(name) {
208
+ return '$' + name + 'Controller';
209
+ }
210
+ /**
211
+ * Destroy an AngularJS app given the app `$injector`.
212
+ *
213
+ * NOTE: Destroying an app is not officially supported by AngularJS, but try to do our best by
214
+ * destroying `$rootScope` and clean the jqLite/jQuery data on `$rootElement` and all
215
+ * descendants.
216
+ *
217
+ * @param $injector The `$injector` of the AngularJS app to destroy.
218
+ */
219
+ function destroyApp($injector) {
220
+ const $rootElement = $injector.get($ROOT_ELEMENT);
221
+ const $rootScope = $injector.get($ROOT_SCOPE);
222
+ $rootScope.$destroy();
223
+ cleanData($rootElement[0]);
224
+ }
225
+ function directiveNormalize(name) {
226
+ return name
227
+ .replace(DIRECTIVE_PREFIX_REGEXP, '')
228
+ .replace(DIRECTIVE_SPECIAL_CHARS_REGEXP, (_, letter) => letter.toUpperCase());
229
+ }
230
+ function getTypeName(type) {
231
+ // Return the name of the type or the first line of its stringified version.
232
+ return type.overriddenName || type.name || type.toString().split('\n')[0];
233
+ }
234
+ function getDowngradedModuleCount($injector) {
235
+ return $injector.has(DOWNGRADED_MODULE_COUNT_KEY)
236
+ ? $injector.get(DOWNGRADED_MODULE_COUNT_KEY)
237
+ : 0;
238
+ }
239
+ function getUpgradeAppType($injector) {
240
+ return $injector.has(UPGRADE_APP_TYPE_KEY)
241
+ ? $injector.get(UPGRADE_APP_TYPE_KEY)
242
+ : 0 /* UpgradeAppType.None */;
243
+ }
244
+ function isFunction(value) {
245
+ return typeof value === 'function';
246
+ }
247
+ function isNgModuleType(value) {
248
+ // NgModule class should have the `ɵmod` static property attached by AOT or JIT compiler.
249
+ return isFunction(value) && !!value[_NG_MOD_DEF];
250
+ }
251
+ function isParentNode(node) {
252
+ return isFunction(node.querySelectorAll);
253
+ }
254
+ function validateInjectionKey($injector, downgradedModule, injectionKey, attemptedAction) {
255
+ const upgradeAppType = getUpgradeAppType($injector);
256
+ const downgradedModuleCount = getDowngradedModuleCount($injector);
257
+ // Check for common errors.
258
+ switch (upgradeAppType) {
259
+ case 1 /* UpgradeAppType.Dynamic */:
260
+ case 2 /* UpgradeAppType.Static */:
261
+ if (downgradedModule) {
262
+ throw new Error(`Error while ${attemptedAction}: 'downgradedModule' unexpectedly specified.\n` +
263
+ "You should not specify a value for 'downgradedModule', unless you are downgrading " +
264
+ "more than one Angular module (via 'downgradeModule()').");
265
+ }
266
+ break;
267
+ case 3 /* UpgradeAppType.Lite */:
268
+ if (!downgradedModule && downgradedModuleCount >= 2) {
269
+ throw new Error(`Error while ${attemptedAction}: 'downgradedModule' not specified.\n` +
270
+ 'This application contains more than one downgraded Angular module, thus you need to ' +
271
+ "always specify 'downgradedModule' when downgrading components and injectables.");
272
+ }
273
+ if (!$injector.has(injectionKey)) {
274
+ throw new Error(`Error while ${attemptedAction}: Unable to find the specified downgraded module.\n` +
275
+ 'Did you forget to downgrade an Angular module or include it in the AngularJS ' +
276
+ 'application?');
277
+ }
278
+ break;
279
+ default:
280
+ throw new Error(`Error while ${attemptedAction}: Not a valid '@angular/upgrade' application.\n` +
281
+ 'Did you forget to downgrade an Angular module or include it in the AngularJS ' +
282
+ 'application?');
283
+ }
284
+ }
285
+ class Deferred {
286
+ promise;
287
+ resolve;
288
+ reject;
289
+ constructor() {
290
+ this.promise = new Promise((res, rej) => {
291
+ this.resolve = res;
292
+ this.reject = rej;
293
+ });
294
+ }
295
+ }
296
+ /**
297
+ * @return Whether the passed-in component implements the subset of the
298
+ * `ControlValueAccessor` interface needed for AngularJS `ng-model`
299
+ * compatibility.
300
+ */
301
+ function supportsNgModel(component) {
302
+ return (typeof component.writeValue === 'function' && typeof component.registerOnChange === 'function');
303
+ }
304
+ /**
305
+ * Glue the AngularJS `NgModelController` (if it exists) to the component
306
+ * (if it implements the needed subset of the `ControlValueAccessor` interface).
307
+ */
308
+ function hookupNgModel(ngModel, component) {
309
+ if (ngModel && supportsNgModel(component)) {
310
+ ngModel.$render = () => {
311
+ component.writeValue(ngModel.$viewValue);
312
+ };
313
+ component.registerOnChange(ngModel.$setViewValue.bind(ngModel));
314
+ if (typeof component.registerOnTouched === 'function') {
315
+ component.registerOnTouched(ngModel.$setTouched.bind(ngModel));
316
+ }
317
+ }
318
+ }
319
+ /**
320
+ * Test two values for strict equality, accounting for the fact that `NaN !== NaN`.
321
+ */
322
+ function strictEquals(val1, val2) {
323
+ return val1 === val2 || (val1 !== val1 && val2 !== val2);
324
+ }
325
+
326
+ var util = /*#__PURE__*/Object.freeze({
327
+ __proto__: null,
328
+ Deferred: Deferred,
329
+ cleanData: cleanData,
330
+ controllerKey: controllerKey,
331
+ destroyApp: destroyApp,
332
+ directiveNormalize: directiveNormalize,
333
+ getDowngradedModuleCount: getDowngradedModuleCount,
334
+ getTypeName: getTypeName,
335
+ getUpgradeAppType: getUpgradeAppType,
336
+ hookupNgModel: hookupNgModel,
337
+ isFunction: isFunction,
338
+ isNgModuleType: isNgModuleType,
339
+ onError: onError,
340
+ strictEquals: strictEquals,
341
+ validateInjectionKey: validateInjectionKey
342
+ });
343
+
344
+ const INITIAL_VALUE = {
345
+ __UNINITIALIZED__: true,
346
+ };
347
+ class DowngradeComponentAdapter {
348
+ element;
349
+ attrs;
350
+ scope;
351
+ ngModel;
352
+ parentInjector;
353
+ $compile;
354
+ $parse;
355
+ componentFactory;
356
+ wrapCallback;
357
+ unsafelyOverwriteSignalInputs;
358
+ implementsOnChanges = false;
359
+ inputChangeCount = 0;
360
+ inputChanges = {};
361
+ componentScope;
362
+ constructor(element, attrs, scope, ngModel, parentInjector, $compile, $parse, componentFactory, wrapCallback, unsafelyOverwriteSignalInputs) {
363
+ this.element = element;
364
+ this.attrs = attrs;
365
+ this.scope = scope;
366
+ this.ngModel = ngModel;
367
+ this.parentInjector = parentInjector;
368
+ this.$compile = $compile;
369
+ this.$parse = $parse;
370
+ this.componentFactory = componentFactory;
371
+ this.wrapCallback = wrapCallback;
372
+ this.unsafelyOverwriteSignalInputs = unsafelyOverwriteSignalInputs;
373
+ this.componentScope = scope.$new();
374
+ }
375
+ compileContents() {
376
+ const compiledProjectableNodes = [];
377
+ const projectableNodes = this.groupProjectableNodes();
378
+ const linkFns = projectableNodes.map((nodes) => this.$compile(nodes));
379
+ this.element.empty();
380
+ linkFns.forEach((linkFn) => {
381
+ linkFn(this.scope, (clone) => {
382
+ compiledProjectableNodes.push(clone);
383
+ this.element.append(clone);
384
+ });
385
+ });
386
+ return compiledProjectableNodes;
387
+ }
388
+ createComponentAndSetup(projectableNodes, manuallyAttachView = false, propagateDigest = true) {
389
+ const component = this.createComponent(projectableNodes);
390
+ this.setupInputs(manuallyAttachView, propagateDigest, component);
391
+ this.setupOutputs(component.componentRef);
392
+ this.registerCleanup(component.componentRef);
393
+ return component.componentRef;
394
+ }
395
+ createComponent(projectableNodes) {
396
+ const providers = [{ provide: $SCOPE, useValue: this.componentScope }];
397
+ const childInjector = Injector.create({
398
+ providers: providers,
399
+ parent: this.parentInjector,
400
+ name: 'DowngradeComponentAdapter',
401
+ });
402
+ const componentRef = this.componentFactory.create(childInjector, projectableNodes, this.element[0]);
403
+ const viewChangeDetector = componentRef.injector.get(ChangeDetectorRef);
404
+ const changeDetector = componentRef.changeDetectorRef;
405
+ // testability hook is commonly added during component bootstrap in
406
+ // packages/core/src/application_ref.bootstrap()
407
+ // in downgraded application, component creation will take place here as well as adding the
408
+ // testability hook.
409
+ const testability = componentRef.injector.get(Testability, null);
410
+ if (testability) {
411
+ componentRef.injector
412
+ .get(TestabilityRegistry)
413
+ .registerApplication(componentRef.location.nativeElement, testability);
414
+ }
415
+ hookupNgModel(this.ngModel, componentRef.instance);
416
+ return { viewChangeDetector, componentRef, changeDetector };
417
+ }
418
+ setupInputs(manuallyAttachView, propagateDigest = true, { componentRef, changeDetector, viewChangeDetector }) {
419
+ const attrs = this.attrs;
420
+ const inputs = this.componentFactory.inputs || [];
421
+ for (const input of inputs) {
422
+ const inputBinding = new PropertyBinding(input.propName, input.templateName);
423
+ let expr = null;
424
+ if (attrs.hasOwnProperty(inputBinding.attr)) {
425
+ const observeFn = ((prop, isSignal) => {
426
+ let prevValue = INITIAL_VALUE;
427
+ return (currValue) => {
428
+ // Initially, both `$observe()` and `$watch()` will call this function.
429
+ if (!strictEquals(prevValue, currValue)) {
430
+ if (prevValue === INITIAL_VALUE) {
431
+ prevValue = currValue;
432
+ }
433
+ this.updateInput(componentRef, prop, prevValue, currValue, isSignal);
434
+ prevValue = currValue;
435
+ }
436
+ };
437
+ })(inputBinding.prop, input.isSignal);
438
+ attrs.$observe(inputBinding.attr, observeFn);
439
+ // Use `$watch()` (in addition to `$observe()`) in order to initialize the input in time
440
+ // for `ngOnChanges()`. This is necessary if we are already in a `$digest`, which means that
441
+ // `ngOnChanges()` (which is called by a watcher) will run before the `$observe()` callback.
442
+ let unwatch = this.componentScope.$watch(() => {
443
+ unwatch();
444
+ unwatch = null;
445
+ observeFn(attrs[inputBinding.attr]);
446
+ });
447
+ }
448
+ else if (attrs.hasOwnProperty(inputBinding.bindAttr)) {
449
+ expr = attrs[inputBinding.bindAttr];
450
+ }
451
+ else if (attrs.hasOwnProperty(inputBinding.bracketAttr)) {
452
+ expr = attrs[inputBinding.bracketAttr];
453
+ }
454
+ else if (attrs.hasOwnProperty(inputBinding.bindonAttr)) {
455
+ expr = attrs[inputBinding.bindonAttr];
456
+ }
457
+ else if (attrs.hasOwnProperty(inputBinding.bracketParenAttr)) {
458
+ expr = attrs[inputBinding.bracketParenAttr];
459
+ }
460
+ if (expr != null) {
461
+ const watchFn = ((prop, isSignal) => (currValue, prevValue) => this.updateInput(componentRef, prop, prevValue, currValue, isSignal))(inputBinding.prop, input.isSignal);
462
+ this.componentScope.$watch(expr, watchFn);
463
+ }
464
+ }
465
+ // Invoke `ngOnChanges()` and Change Detection (when necessary)
466
+ const detectChanges = () => changeDetector.detectChanges();
467
+ const prototype = this.componentFactory.componentType.prototype;
468
+ this.implementsOnChanges = !!(prototype && prototype.ngOnChanges);
469
+ this.componentScope.$watch(() => this.inputChangeCount, this.wrapCallback(() => {
470
+ // Invoke `ngOnChanges()`
471
+ if (this.implementsOnChanges) {
472
+ const inputChanges = this.inputChanges;
473
+ this.inputChanges = {};
474
+ componentRef.instance.ngOnChanges(inputChanges);
475
+ }
476
+ viewChangeDetector.markForCheck();
477
+ // If opted out of propagating digests, invoke change detection when inputs change.
478
+ if (!propagateDigest) {
479
+ detectChanges();
480
+ }
481
+ }));
482
+ // If not opted out of propagating digests, invoke change detection on every digest
483
+ if (propagateDigest) {
484
+ this.componentScope.$watch(this.wrapCallback(detectChanges));
485
+ }
486
+ // If necessary, attach the view so that it will be dirty-checked.
487
+ // (Allow time for the initial input values to be set and `ngOnChanges()` to be called.)
488
+ if (manuallyAttachView || !propagateDigest) {
489
+ let unwatch = this.componentScope.$watch(() => {
490
+ unwatch();
491
+ unwatch = null;
492
+ const appRef = this.parentInjector.get(ApplicationRef);
493
+ appRef.attachView(componentRef.hostView);
494
+ });
495
+ }
496
+ }
497
+ setupOutputs(componentRef) {
498
+ const attrs = this.attrs;
499
+ const outputs = this.componentFactory.outputs || [];
500
+ for (const output of outputs) {
501
+ const outputBindings = new PropertyBinding(output.propName, output.templateName);
502
+ const bindonAttr = outputBindings.bindonAttr.substring(0, outputBindings.bindonAttr.length - 6);
503
+ const bracketParenAttr = `[(${outputBindings.bracketParenAttr.substring(2, outputBindings.bracketParenAttr.length - 8)})]`;
504
+ // order below is important - first update bindings then evaluate expressions
505
+ if (attrs.hasOwnProperty(bindonAttr)) {
506
+ this.subscribeToOutput(componentRef, outputBindings, attrs[bindonAttr], true);
507
+ }
508
+ if (attrs.hasOwnProperty(bracketParenAttr)) {
509
+ this.subscribeToOutput(componentRef, outputBindings, attrs[bracketParenAttr], true);
510
+ }
511
+ if (attrs.hasOwnProperty(outputBindings.onAttr)) {
512
+ this.subscribeToOutput(componentRef, outputBindings, attrs[outputBindings.onAttr]);
513
+ }
514
+ if (attrs.hasOwnProperty(outputBindings.parenAttr)) {
515
+ this.subscribeToOutput(componentRef, outputBindings, attrs[outputBindings.parenAttr]);
516
+ }
517
+ }
518
+ }
519
+ subscribeToOutput(componentRef, output, expr, isAssignment = false) {
520
+ const getter = this.$parse(expr);
521
+ const setter = getter.assign;
522
+ if (isAssignment && !setter) {
523
+ throw new Error(`Expression '${expr}' is not assignable!`);
524
+ }
525
+ const emitter = componentRef.instance[output.prop];
526
+ if (emitter) {
527
+ const subscription = emitter.subscribe({
528
+ next: isAssignment
529
+ ? (v) => setter(this.scope, v)
530
+ : (v) => getter(this.scope, { '$event': v }),
531
+ });
532
+ componentRef.onDestroy(() => subscription.unsubscribe());
533
+ }
534
+ else {
535
+ throw new Error(`Missing emitter '${output.prop}' on component '${getTypeName(this.componentFactory.componentType)}'!`);
536
+ }
537
+ }
538
+ registerCleanup(componentRef) {
539
+ const testabilityRegistry = componentRef.injector.get(TestabilityRegistry);
540
+ const destroyComponentRef = this.wrapCallback(() => componentRef.destroy());
541
+ let destroyed = false;
542
+ this.element.on('$destroy', () => {
543
+ // The `$destroy` event may have been triggered by the `cleanData()` call in the
544
+ // `componentScope` `$destroy` handler below. In that case, we don't want to call
545
+ // `componentScope.$destroy()` again.
546
+ if (!destroyed)
547
+ this.componentScope.$destroy();
548
+ });
549
+ this.componentScope.$on('$destroy', () => {
550
+ if (!destroyed) {
551
+ destroyed = true;
552
+ testabilityRegistry.unregisterApplication(componentRef.location.nativeElement);
553
+ // The `componentScope` might be getting destroyed, because an ancestor element is being
554
+ // removed/destroyed. If that is the case, jqLite/jQuery would normally invoke `cleanData()`
555
+ // on the removed element and all descendants.
556
+ // https://github.com/angular/angular.js/blob/2e72ea13fa98bebf6ed4b5e3c45eaf5f990ed16f/src/jqLite.js#L349-L355
557
+ // https://github.com/jquery/jquery/blob/6984d1747623dbc5e87fd6c261a5b6b1628c107c/src/manipulation.js#L182
558
+ //
559
+ // Here, however, `destroyComponentRef()` may under some circumstances remove the element
560
+ // from the DOM and therefore it will no longer be a descendant of the removed element when
561
+ // `cleanData()` is called. This would result in a memory leak, because the element's data
562
+ // and event handlers (and all objects directly or indirectly referenced by them) would be
563
+ // retained.
564
+ //
565
+ // To ensure the element is always properly cleaned up, we manually call `cleanData()` on
566
+ // this element and its descendants before destroying the `ComponentRef`.
567
+ cleanData(this.element[0]);
568
+ destroyComponentRef();
569
+ }
570
+ });
571
+ }
572
+ updateInput(componentRef, prop, prevValue, currValue, isSignal) {
573
+ if (this.implementsOnChanges) {
574
+ this.inputChanges[prop] = new SimpleChange(prevValue, currValue, prevValue === currValue);
575
+ }
576
+ this.inputChangeCount++;
577
+ if (isSignal && !this.unsafelyOverwriteSignalInputs) {
578
+ const node = componentRef.instance[prop][_SIGNAL];
579
+ node.applyValueToInputSignal(node, currValue);
580
+ }
581
+ else {
582
+ componentRef.instance[prop] = currValue;
583
+ }
584
+ }
585
+ groupProjectableNodes() {
586
+ let ngContentSelectors = this.componentFactory.ngContentSelectors;
587
+ return groupNodesBySelector(ngContentSelectors, this.element.contents());
588
+ }
589
+ }
590
+ /**
591
+ * Group a set of DOM nodes into `ngContent` groups, based on the given content selectors.
592
+ */
593
+ function groupNodesBySelector(ngContentSelectors, nodes) {
594
+ const projectableNodes = [];
595
+ for (let i = 0, ii = ngContentSelectors.length; i < ii; ++i) {
596
+ projectableNodes[i] = [];
597
+ }
598
+ for (let j = 0, jj = nodes.length; j < jj; ++j) {
599
+ const node = nodes[j];
600
+ const ngContentIndex = findMatchingNgContentIndex(node, ngContentSelectors);
601
+ if (ngContentIndex != null) {
602
+ projectableNodes[ngContentIndex].push(node);
603
+ }
604
+ }
605
+ return projectableNodes;
606
+ }
607
+ function findMatchingNgContentIndex(element, ngContentSelectors) {
608
+ const ngContentIndices = [];
609
+ let wildcardNgContentIndex = -1;
610
+ for (let i = 0; i < ngContentSelectors.length; i++) {
611
+ const selector = ngContentSelectors[i];
612
+ if (selector === '*') {
613
+ wildcardNgContentIndex = i;
614
+ }
615
+ else {
616
+ if (matchesSelector(element, selector)) {
617
+ ngContentIndices.push(i);
618
+ }
619
+ }
620
+ }
621
+ ngContentIndices.sort();
622
+ if (wildcardNgContentIndex !== -1) {
623
+ ngContentIndices.push(wildcardNgContentIndex);
624
+ }
625
+ return ngContentIndices.length ? ngContentIndices[0] : null;
626
+ }
627
+ function matchesSelector(el, selector) {
628
+ const elProto = Element.prototype;
629
+ return el.nodeType === Node.ELEMENT_NODE
630
+ ? // matches is supported by all browsers from 2014 onwards except non-chromium edge
631
+ (elProto.matches ?? elProto.msMatchesSelector).call(el, selector)
632
+ : false;
633
+ }
634
+
635
+ function isThenable(obj) {
636
+ return !!obj && isFunction(obj.then);
637
+ }
638
+ /**
639
+ * Synchronous, promise-like object.
640
+ */
641
+ class SyncPromise {
642
+ value;
643
+ resolved = false;
644
+ callbacks = [];
645
+ static all(valuesOrPromises) {
646
+ const aggrPromise = new SyncPromise();
647
+ let resolvedCount = 0;
648
+ const results = [];
649
+ const resolve = (idx, value) => {
650
+ results[idx] = value;
651
+ if (++resolvedCount === valuesOrPromises.length)
652
+ aggrPromise.resolve(results);
653
+ };
654
+ valuesOrPromises.forEach((p, idx) => {
655
+ if (isThenable(p)) {
656
+ p.then((v) => resolve(idx, v));
657
+ }
658
+ else {
659
+ resolve(idx, p);
660
+ }
661
+ });
662
+ return aggrPromise;
663
+ }
664
+ resolve(value) {
665
+ // Do nothing, if already resolved.
666
+ if (this.resolved)
667
+ return;
668
+ this.value = value;
669
+ this.resolved = true;
670
+ // Run the queued callbacks.
671
+ this.callbacks.forEach((callback) => callback(value));
672
+ this.callbacks.length = 0;
673
+ }
674
+ then(callback) {
675
+ if (this.resolved) {
676
+ callback(this.value);
677
+ }
678
+ else {
679
+ this.callbacks.push(callback);
680
+ }
681
+ }
682
+ }
683
+
684
+ /**
685
+ * @description
686
+ *
687
+ * A helper function that allows an Angular component to be used from AngularJS.
688
+ *
689
+ * *Part of the [upgrade/static](api?query=upgrade%2Fstatic)
690
+ * library for hybrid upgrade apps that support AOT compilation*
691
+ *
692
+ * This helper function returns a factory function to be used for registering
693
+ * an AngularJS wrapper directive for "downgrading" an Angular component.
694
+ *
695
+ * @usageNotes
696
+ * ### Examples
697
+ *
698
+ * Let's assume that you have an Angular component called `ng2Heroes` that needs
699
+ * to be made available in AngularJS templates.
700
+ *
701
+ * {@example upgrade/static/ts/full/module.ts region="ng2-heroes"}
702
+ *
703
+ * We must create an AngularJS [directive](https://docs.angularjs.org/guide/directive)
704
+ * that will make this Angular component available inside AngularJS templates.
705
+ * The `downgradeComponent()` function returns a factory function that we
706
+ * can use to define the AngularJS directive that wraps the "downgraded" component.
707
+ *
708
+ * {@example upgrade/static/ts/full/module.ts region="ng2-heroes-wrapper"}
709
+ *
710
+ * For more details and examples on downgrading Angular components to AngularJS components please
711
+ * visit the [Upgrade guide](https://angular.io/guide/upgrade#using-angular-components-from-angularjs-code).
712
+ *
713
+ * @param info contains information about the Component that is being downgraded:
714
+ *
715
+ * - `component: Type<any>`: The type of the Component that will be downgraded
716
+ * - `downgradedModule?: string`: The name of the downgraded module (if any) that the component
717
+ * "belongs to", as returned by a call to `downgradeModule()`. It is the module, whose
718
+ * corresponding Angular module will be bootstrapped, when the component needs to be instantiated.
719
+ * <br />
720
+ * (This option is only necessary when using `downgradeModule()` to downgrade more than one
721
+ * Angular module.)
722
+ * - `propagateDigest?: boolean`: Whether to perform {@link /api/core/ChangeDetectorRef#detectChanges detectChanges} on the
723
+ * component on every {@link https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest $digest}.
724
+ * If set to `false`, change detection will still be performed when any of the component's inputs changes.
725
+ * (Default: true)
726
+ *
727
+ * @returns a factory function that can be used to register the component in an
728
+ * AngularJS module.
729
+ *
730
+ * @publicApi
731
+ */
732
+ function downgradeComponent(info) {
733
+ const directiveFactory = function ($compile, $injector, $parse) {
734
+ const unsafelyOverwriteSignalInputs = info.unsafelyOverwriteSignalInputs ?? false;
735
+ // When using `downgradeModule()`, we need to handle certain things specially. For example:
736
+ // - We always need to attach the component view to the `ApplicationRef` for it to be
737
+ // dirty-checked.
738
+ // - We need to ensure callbacks to Angular APIs (e.g. change detection) are run inside the
739
+ // Angular zone.
740
+ // NOTE: This is not needed, when using `UpgradeModule`, because `$digest()` will be run
741
+ // inside the Angular zone (except if explicitly escaped, in which case we shouldn't
742
+ // force it back in).
743
+ const isNgUpgradeLite = getUpgradeAppType($injector) === 3 /* UpgradeAppType.Lite */;
744
+ const wrapCallback = !isNgUpgradeLite
745
+ ? (cb) => cb
746
+ : (cb) => () => (NgZone.isInAngularZone() ? cb() : ngZone.run(cb));
747
+ let ngZone;
748
+ // When downgrading multiple modules, special handling is needed wrt injectors.
749
+ const hasMultipleDowngradedModules = isNgUpgradeLite && getDowngradedModuleCount($injector) > 1;
750
+ return {
751
+ restrict: 'E',
752
+ terminal: true,
753
+ require: [REQUIRE_INJECTOR, REQUIRE_NG_MODEL],
754
+ // Controller needs to be set so that `angular-component-router.js` (from beta Angular 2)
755
+ // configuration properties can be made available. See:
756
+ // See G3: javascript/angular2/angular1_router_lib.js
757
+ // https://github.com/angular/angular.js/blob/47bf11ee94664367a26ed8c91b9b586d3dd420f5/src/ng/compile.js#L1670-L1691.
758
+ controller: function () { },
759
+ link: (scope, element, attrs, required) => {
760
+ // We might have to compile the contents asynchronously, because this might have been
761
+ // triggered by `UpgradeNg1ComponentAdapterBuilder`, before the Angular templates have
762
+ // been compiled.
763
+ const ngModel = required[1];
764
+ const parentInjector = required[0];
765
+ let moduleInjector = undefined;
766
+ let ranAsync = false;
767
+ if (!parentInjector || hasMultipleDowngradedModules) {
768
+ const downgradedModule = info.downgradedModule || '';
769
+ const lazyModuleRefKey = `${LAZY_MODULE_REF}${downgradedModule}`;
770
+ const attemptedAction = `instantiating component '${getTypeName(info.component)}'`;
771
+ validateInjectionKey($injector, downgradedModule, lazyModuleRefKey, attemptedAction);
772
+ const lazyModuleRef = $injector.get(lazyModuleRefKey);
773
+ moduleInjector = lazyModuleRef.injector ?? lazyModuleRef.promise;
774
+ }
775
+ // Notes:
776
+ //
777
+ // There are two injectors: `finalModuleInjector` and `finalParentInjector` (they might be
778
+ // the same instance, but that is irrelevant):
779
+ // - `finalModuleInjector` is used to retrieve `ComponentFactoryResolver`, thus it must be
780
+ // on the same tree as the `NgModule` that declares this downgraded component.
781
+ // - `finalParentInjector` is used for all other injection purposes.
782
+ // (Note that Angular knows to only traverse the component-tree part of that injector,
783
+ // when looking for an injectable and then switch to the module injector.)
784
+ //
785
+ // There are basically three cases:
786
+ // - If there is no parent component (thus no `parentInjector`), we bootstrap the downgraded
787
+ // `NgModule` and use its injector as both `finalModuleInjector` and
788
+ // `finalParentInjector`.
789
+ // - If there is a parent component (and thus a `parentInjector`) and we are sure that it
790
+ // belongs to the same `NgModule` as this downgraded component (e.g. because there is only
791
+ // one downgraded module, we use that `parentInjector` as both `finalModuleInjector` and
792
+ // `finalParentInjector`.
793
+ // - If there is a parent component, but it may belong to a different `NgModule`, then we
794
+ // use the `parentInjector` as `finalParentInjector` and this downgraded component's
795
+ // declaring `NgModule`'s injector as `finalModuleInjector`.
796
+ // Note 1: If the `NgModule` is already bootstrapped, we just get its injector (we don't
797
+ // bootstrap again).
798
+ // Note 2: It is possible that (while there are multiple downgraded modules) this
799
+ // downgraded component and its parent component both belong to the same NgModule.
800
+ // In that case, we could have used the `parentInjector` as both
801
+ // `finalModuleInjector` and `finalParentInjector`, but (for simplicity) we are
802
+ // treating this case as if they belong to different `NgModule`s. That doesn't
803
+ // really affect anything, since `parentInjector` has `moduleInjector` as ancestor
804
+ // and trying to resolve `ComponentFactoryResolver` from either one will return
805
+ // the same instance.
806
+ // If there is a parent component, use its injector as parent injector.
807
+ // If this is a "top-level" Angular component, use the module injector.
808
+ const finalParentInjector = parentInjector || moduleInjector;
809
+ // If this is a "top-level" Angular component or the parent component may belong to a
810
+ // different `NgModule`, use the module injector for module-specific dependencies.
811
+ // If there is a parent component that belongs to the same `NgModule`, use its injector.
812
+ const finalModuleInjector = moduleInjector || parentInjector;
813
+ const doDowngrade = (injector, moduleInjector) => {
814
+ // Retrieve `ComponentFactoryResolver` from the injector tied to the `NgModule` this
815
+ // component belongs to.
816
+ const componentFactoryResolver = moduleInjector.get(ComponentFactoryResolver);
817
+ const componentFactory = componentFactoryResolver.resolveComponentFactory(info.component);
818
+ if (!componentFactory) {
819
+ throw new Error(`Expecting ComponentFactory for: ${getTypeName(info.component)}`);
820
+ }
821
+ const injectorPromise = new ParentInjectorPromise(element);
822
+ const facade = new DowngradeComponentAdapter(element, attrs, scope, ngModel, injector, $compile, $parse, componentFactory, wrapCallback, unsafelyOverwriteSignalInputs);
823
+ const projectableNodes = facade.compileContents();
824
+ const componentRef = facade.createComponentAndSetup(projectableNodes, isNgUpgradeLite, info.propagateDigest);
825
+ injectorPromise.resolve(componentRef.injector);
826
+ if (ranAsync) {
827
+ // If this is run async, it is possible that it is not run inside a
828
+ // digest and initial input values will not be detected.
829
+ scope.$evalAsync(() => { });
830
+ }
831
+ };
832
+ const downgradeFn = !isNgUpgradeLite
833
+ ? doDowngrade
834
+ : (pInjector, mInjector) => {
835
+ if (!ngZone) {
836
+ ngZone = pInjector.get(NgZone);
837
+ }
838
+ wrapCallback(() => doDowngrade(pInjector, mInjector))();
839
+ };
840
+ // NOTE:
841
+ // Not using `ParentInjectorPromise.all()` (which is inherited from `SyncPromise`), because
842
+ // Closure Compiler (or some related tool) complains:
843
+ // `TypeError: ...$src$downgrade_component_ParentInjectorPromise.all is not a function`
844
+ SyncPromise.all([finalParentInjector, finalModuleInjector]).then(([pInjector, mInjector]) => downgradeFn(pInjector, mInjector));
845
+ ranAsync = true;
846
+ },
847
+ };
848
+ };
849
+ // bracket-notation because of closure - see #14441
850
+ directiveFactory['$inject'] = [$COMPILE, $INJECTOR, $PARSE];
851
+ return directiveFactory;
852
+ }
853
+ /**
854
+ * Synchronous promise-like object to wrap parent injectors,
855
+ * to preserve the synchronous nature of AngularJS's `$compile`.
856
+ */
857
+ class ParentInjectorPromise extends SyncPromise {
858
+ element;
859
+ injectorKey = controllerKey(INJECTOR_KEY);
860
+ constructor(element) {
861
+ super();
862
+ this.element = element;
863
+ // Store the promise on the element.
864
+ element.data(this.injectorKey, this);
865
+ }
866
+ resolve(injector) {
867
+ // Store the real injector on the element.
868
+ this.element.data(this.injectorKey, injector);
869
+ // Release the element to prevent memory leaks.
870
+ this.element = null;
871
+ // Resolve the promise.
872
+ super.resolve(injector);
873
+ }
874
+ }
875
+
876
+ /**
877
+ * @description
878
+ *
879
+ * A helper function to allow an Angular service to be accessible from AngularJS.
880
+ *
881
+ * *Part of the [upgrade/static](api?query=upgrade%2Fstatic)
882
+ * library for hybrid upgrade apps that support AOT compilation*
883
+ *
884
+ * This helper function returns a factory function that provides access to the Angular
885
+ * service identified by the `token` parameter.
886
+ *
887
+ * @usageNotes
888
+ * ### Examples
889
+ *
890
+ * First ensure that the service to be downgraded is provided in an `NgModule`
891
+ * that will be part of the upgrade application. For example, let's assume we have
892
+ * defined `HeroesService`
893
+ *
894
+ * {@example upgrade/static/ts/full/module.ts region="ng2-heroes-service"}
895
+ *
896
+ * and that we have included this in our upgrade app `NgModule`
897
+ *
898
+ * {@example upgrade/static/ts/full/module.ts region="ng2-module"}
899
+ *
900
+ * Now we can register the `downgradeInjectable` factory function for the service
901
+ * on an AngularJS module.
902
+ *
903
+ * {@example upgrade/static/ts/full/module.ts region="downgrade-ng2-heroes-service"}
904
+ *
905
+ * Inside an AngularJS component's controller we can get hold of the
906
+ * downgraded service via the name we gave when downgrading.
907
+ *
908
+ * {@example upgrade/static/ts/full/module.ts region="example-app"}
909
+ *
910
+ * <div class="docs-alert docs-alert-important">
911
+ *
912
+ * When using `downgradeModule()`, downgraded injectables will not be available until the Angular
913
+ * module that provides them is instantiated. In order to be safe, you need to ensure that the
914
+ * downgraded injectables are not used anywhere _outside_ the part of the app where it is
915
+ * guaranteed that their module has been instantiated.
916
+ *
917
+ * For example, it is _OK_ to use a downgraded service in an upgraded component that is only used
918
+ * from a downgraded Angular component provided by the same Angular module as the injectable, but
919
+ * it is _not OK_ to use it in an AngularJS component that may be used independently of Angular or
920
+ * use it in a downgraded Angular component from a different module.
921
+ *
922
+ * </div>
923
+ *
924
+ * @param token an `InjectionToken` that identifies a service provided from Angular.
925
+ * @param downgradedModule the name of the downgraded module (if any) that the injectable
926
+ * "belongs to", as returned by a call to `downgradeModule()`. It is the module, whose injector will
927
+ * be used for instantiating the injectable.<br />
928
+ * (This option is only necessary when using `downgradeModule()` to downgrade more than one Angular
929
+ * module.)
930
+ *
931
+ * @returns a [factory function](https://docs.angularjs.org/guide/di) that can be
932
+ * used to register the service on an AngularJS module.
933
+ *
934
+ * @publicApi
935
+ */
936
+ function downgradeInjectable(token, downgradedModule = '') {
937
+ const factory = function ($injector) {
938
+ const injectorKey = `${INJECTOR_KEY}${downgradedModule}`;
939
+ const injectableName = isFunction(token) ? getTypeName(token) : String(token);
940
+ const attemptedAction = `instantiating injectable '${injectableName}'`;
941
+ validateInjectionKey($injector, downgradedModule, injectorKey, attemptedAction);
942
+ try {
943
+ const injector = $injector.get(injectorKey);
944
+ return injector.get(token);
945
+ }
946
+ catch (err) {
947
+ throw new Error(`Error while ${attemptedAction}: ${err.message || err}`);
948
+ }
949
+ };
950
+ factory['$inject'] = [$INJECTOR];
951
+ return factory;
952
+ }
953
+
954
+ /**
955
+ * The Trusted Types policy, or null if Trusted Types are not
956
+ * enabled/supported, or undefined if the policy has not been created yet.
957
+ */
958
+ let policy;
959
+ /**
960
+ * Returns the Trusted Types policy, or null if Trusted Types are not
961
+ * enabled/supported. The first call to this function will create the policy.
962
+ */
963
+ function getPolicy() {
964
+ if (policy === undefined) {
965
+ policy = null;
966
+ const windowWithTrustedTypes = window;
967
+ if (windowWithTrustedTypes.trustedTypes) {
968
+ try {
969
+ policy = windowWithTrustedTypes.trustedTypes.createPolicy('angular#unsafe-upgrade', {
970
+ createHTML: (s) => s,
971
+ });
972
+ }
973
+ catch {
974
+ // trustedTypes.createPolicy throws if called with a name that is
975
+ // already registered, even in report-only mode. Until the API changes,
976
+ // catch the error not to break the applications functionally. In such
977
+ // cases, the code will fall back to using strings.
978
+ }
979
+ }
980
+ }
981
+ return policy;
982
+ }
983
+ /**
984
+ * Unsafely promote a legacy AngularJS template to a TrustedHTML, falling back
985
+ * to strings when Trusted Types are not available.
986
+ * @security This is a security-sensitive function; any use of this function
987
+ * must go through security review. In particular, the template string should
988
+ * always be under full control of the application author, as untrusted input
989
+ * can cause an XSS vulnerability.
990
+ */
991
+ function trustedHTMLFromLegacyTemplate(html) {
992
+ return getPolicy()?.createHTML(html) || html;
993
+ }
994
+
995
+ // Constants
996
+ const REQUIRE_PREFIX_RE = /^(\^\^?)?(\?)?(\^\^?)?/;
997
+ // Classes
998
+ class UpgradeHelper {
999
+ name;
1000
+ $injector;
1001
+ element;
1002
+ $element;
1003
+ directive;
1004
+ $compile;
1005
+ $controller;
1006
+ constructor(injector, name, elementRef, directive) {
1007
+ this.name = name;
1008
+ this.$injector = injector.get($INJECTOR);
1009
+ this.$compile = this.$injector.get($COMPILE);
1010
+ this.$controller = this.$injector.get($CONTROLLER);
1011
+ this.element = elementRef.nativeElement;
1012
+ this.$element = element(this.element);
1013
+ this.directive = directive ?? UpgradeHelper.getDirective(this.$injector, name);
1014
+ }
1015
+ static getDirective($injector, name) {
1016
+ const directives = $injector.get(name + 'Directive');
1017
+ if (directives.length > 1) {
1018
+ throw new Error(`Only support single directive definition for: ${name}`);
1019
+ }
1020
+ const directive = directives[0];
1021
+ // AngularJS will transform `link: xyz` to `compile: () => xyz`. So we can only tell there was a
1022
+ // user-defined `compile` if there is no `link`. In other cases, we will just ignore `compile`.
1023
+ if (directive.compile && !directive.link)
1024
+ notSupported(name, 'compile');
1025
+ if (directive.replace)
1026
+ notSupported(name, 'replace');
1027
+ if (directive.terminal)
1028
+ notSupported(name, 'terminal');
1029
+ return directive;
1030
+ }
1031
+ static getTemplate($injector, directive, fetchRemoteTemplate = false, $element) {
1032
+ if (directive.template !== undefined) {
1033
+ return trustedHTMLFromLegacyTemplate(getOrCall(directive.template, $element));
1034
+ }
1035
+ else if (directive.templateUrl) {
1036
+ const $templateCache = $injector.get($TEMPLATE_CACHE);
1037
+ const url = getOrCall(directive.templateUrl, $element);
1038
+ const template = $templateCache.get(url);
1039
+ if (template !== undefined) {
1040
+ return trustedHTMLFromLegacyTemplate(template);
1041
+ }
1042
+ else if (!fetchRemoteTemplate) {
1043
+ throw new Error('loading directive templates asynchronously is not supported');
1044
+ }
1045
+ return new Promise((resolve, reject) => {
1046
+ const $httpBackend = $injector.get($HTTP_BACKEND);
1047
+ $httpBackend('GET', url, null, (status, response) => {
1048
+ if (status === 200) {
1049
+ resolve(trustedHTMLFromLegacyTemplate($templateCache.put(url, response)));
1050
+ }
1051
+ else {
1052
+ reject(`GET component template from '${url}' returned '${status}: ${response}'`);
1053
+ }
1054
+ });
1055
+ });
1056
+ }
1057
+ else {
1058
+ throw new Error(`Directive '${directive.name}' is not a component, it is missing template.`);
1059
+ }
1060
+ }
1061
+ buildController(controllerType, $scope) {
1062
+ // TODO: Document that we do not pre-assign bindings on the controller instance.
1063
+ // Quoted properties below so that this code can be optimized with Closure Compiler.
1064
+ const locals = { '$scope': $scope, '$element': this.$element };
1065
+ const controller = this.$controller(controllerType, locals, null, this.directive.controllerAs);
1066
+ this.$element.data?.(controllerKey(this.directive.name), controller);
1067
+ return controller;
1068
+ }
1069
+ compileTemplate(template) {
1070
+ if (template === undefined) {
1071
+ template = UpgradeHelper.getTemplate(this.$injector, this.directive, false, this.$element);
1072
+ }
1073
+ return this.compileHtml(template);
1074
+ }
1075
+ onDestroy($scope, controllerInstance) {
1076
+ if (controllerInstance && isFunction(controllerInstance.$onDestroy)) {
1077
+ controllerInstance.$onDestroy();
1078
+ }
1079
+ $scope.$destroy();
1080
+ cleanData(this.element);
1081
+ }
1082
+ prepareTransclusion() {
1083
+ const transclude = this.directive.transclude;
1084
+ const contentChildNodes = this.extractChildNodes();
1085
+ const attachChildrenFn = (scope, cloneAttachFn) => {
1086
+ // Since AngularJS v1.5.8, `cloneAttachFn` will try to destroy the transclusion scope if
1087
+ // `$template` is empty. Since the transcluded content comes from Angular, not AngularJS,
1088
+ // there will be no transclusion scope here.
1089
+ // Provide a dummy `scope.$destroy()` method to prevent `cloneAttachFn` from throwing.
1090
+ scope = scope || { $destroy: () => undefined };
1091
+ return cloneAttachFn($template, scope);
1092
+ };
1093
+ let $template = contentChildNodes;
1094
+ if (transclude) {
1095
+ const slots = Object.create(null);
1096
+ if (typeof transclude === 'object') {
1097
+ $template = [];
1098
+ const slotMap = Object.create(null);
1099
+ const filledSlots = Object.create(null);
1100
+ // Parse the element selectors.
1101
+ Object.keys(transclude).forEach((slotName) => {
1102
+ let selector = transclude[slotName];
1103
+ const optional = selector.charAt(0) === '?';
1104
+ selector = optional ? selector.substring(1) : selector;
1105
+ slotMap[selector] = slotName;
1106
+ slots[slotName] = null; // `null`: Defined but not yet filled.
1107
+ filledSlots[slotName] = optional; // Consider optional slots as filled.
1108
+ });
1109
+ // Add the matching elements into their slot.
1110
+ contentChildNodes.forEach((node) => {
1111
+ const slotName = slotMap[directiveNormalize(node.nodeName.toLowerCase())];
1112
+ if (slotName) {
1113
+ filledSlots[slotName] = true;
1114
+ slots[slotName] = slots[slotName] || [];
1115
+ slots[slotName].push(node);
1116
+ }
1117
+ else {
1118
+ $template.push(node);
1119
+ }
1120
+ });
1121
+ // Check for required slots that were not filled.
1122
+ Object.keys(filledSlots).forEach((slotName) => {
1123
+ if (!filledSlots[slotName]) {
1124
+ throw new Error(`Required transclusion slot '${slotName}' on directive: ${this.name}`);
1125
+ }
1126
+ });
1127
+ Object.keys(slots)
1128
+ .filter((slotName) => slots[slotName])
1129
+ .forEach((slotName) => {
1130
+ const nodes = slots[slotName];
1131
+ slots[slotName] = (scope, cloneAttach) => {
1132
+ return cloneAttach(nodes, scope);
1133
+ };
1134
+ });
1135
+ }
1136
+ // Attach `$$slots` to default slot transclude fn.
1137
+ attachChildrenFn.$$slots = slots;
1138
+ // AngularJS v1.6+ ignores empty or whitespace-only transcluded text nodes. But Angular
1139
+ // removes all text content after the first interpolation and updates it later, after
1140
+ // evaluating the expressions. This would result in AngularJS failing to recognize text
1141
+ // nodes that start with an interpolation as transcluded content and use the fallback
1142
+ // content instead.
1143
+ // To avoid this issue, we add a
1144
+ // [zero-width non-joiner character](https://en.wikipedia.org/wiki/Zero-width_non-joiner)
1145
+ // to empty text nodes (which can only be a result of Angular removing their initial content).
1146
+ // NOTE: Transcluded text content that starts with whitespace followed by an interpolation
1147
+ // will still fail to be detected by AngularJS v1.6+
1148
+ $template.forEach((node) => {
1149
+ if (node.nodeType === Node.TEXT_NODE && !node.nodeValue) {
1150
+ node.nodeValue = '\u200C';
1151
+ }
1152
+ });
1153
+ }
1154
+ return attachChildrenFn;
1155
+ }
1156
+ resolveAndBindRequiredControllers(controllerInstance) {
1157
+ const directiveRequire = this.getDirectiveRequire();
1158
+ const requiredControllers = this.resolveRequire(directiveRequire);
1159
+ if (controllerInstance && this.directive.bindToController && isMap(directiveRequire)) {
1160
+ const requiredControllersMap = requiredControllers;
1161
+ Object.keys(requiredControllersMap).forEach((key) => {
1162
+ controllerInstance[key] = requiredControllersMap[key];
1163
+ });
1164
+ }
1165
+ return requiredControllers;
1166
+ }
1167
+ compileHtml(html) {
1168
+ this.element.innerHTML = html;
1169
+ return this.$compile(this.element.childNodes);
1170
+ }
1171
+ extractChildNodes() {
1172
+ const childNodes = [];
1173
+ let childNode;
1174
+ while ((childNode = this.element.firstChild)) {
1175
+ childNode.remove();
1176
+ childNodes.push(childNode);
1177
+ }
1178
+ return childNodes;
1179
+ }
1180
+ getDirectiveRequire() {
1181
+ const require = this.directive.require || (this.directive.controller && this.directive.name);
1182
+ if (isMap(require)) {
1183
+ Object.entries(require).forEach(([key, value]) => {
1184
+ const match = value.match(REQUIRE_PREFIX_RE);
1185
+ const name = value.substring(match[0].length);
1186
+ if (!name) {
1187
+ require[key] = match[0] + key;
1188
+ }
1189
+ });
1190
+ }
1191
+ return require;
1192
+ }
1193
+ resolveRequire(require) {
1194
+ if (!require) {
1195
+ return null;
1196
+ }
1197
+ else if (Array.isArray(require)) {
1198
+ return require.map((req) => this.resolveRequire(req));
1199
+ }
1200
+ else if (typeof require === 'object') {
1201
+ const value = {};
1202
+ Object.keys(require).forEach((key) => (value[key] = this.resolveRequire(require[key])));
1203
+ return value;
1204
+ }
1205
+ else if (typeof require === 'string') {
1206
+ const match = require.match(REQUIRE_PREFIX_RE);
1207
+ const inheritType = match[1] || match[3];
1208
+ const name = require.substring(match[0].length);
1209
+ const isOptional = !!match[2];
1210
+ const searchParents = !!inheritType;
1211
+ const startOnParent = inheritType === '^^';
1212
+ const ctrlKey = controllerKey(name);
1213
+ const elem = startOnParent ? this.$element.parent() : this.$element;
1214
+ const value = searchParents ? elem.inheritedData(ctrlKey) : elem.data(ctrlKey);
1215
+ if (!value && !isOptional) {
1216
+ throw new Error(`Unable to find required '${require}' in upgraded directive '${this.name}'.`);
1217
+ }
1218
+ return value;
1219
+ }
1220
+ else {
1221
+ throw new Error(`Unrecognized 'require' syntax on upgraded directive '${this.name}': ${require}`);
1222
+ }
1223
+ }
1224
+ }
1225
+ function getOrCall(property, ...args) {
1226
+ return isFunction(property) ? property(...args) : property;
1227
+ }
1228
+ // NOTE: Only works for `typeof T !== 'object'`.
1229
+ function isMap(value) {
1230
+ return value && !Array.isArray(value) && typeof value === 'object';
1231
+ }
1232
+ function notSupported(name, feature) {
1233
+ throw new Error(`Upgraded directive '${name}' contains unsupported feature: '${feature}'.`);
1234
+ }
1235
+
1236
+ var upgrade_helper = /*#__PURE__*/Object.freeze({
1237
+ __proto__: null,
1238
+ UpgradeHelper: UpgradeHelper
1239
+ });
1240
+
1241
+ export { $SCOPE as $, setAngularLib as A, angular1 as B, COMPILER_KEY as C, Deferred as D, constants as E, upgrade_helper as F, util as G, INJECTOR_KEY as I, LAZY_MODULE_REF as L, NG_ZONE_KEY as N, UpgradeHelper as U, VERSION as V, $INJECTOR as a, bootstrap as b, controllerKey as c, downgradeComponent as d, element as e, downgradeInjectable as f, UPGRADE_APP_TYPE_KEY as g, $ROOT_SCOPE as h, isFunction as i, $$TESTABILITY as j, $COMPILE as k, destroyApp as l, module_ as m, UPGRADE_MODULE_NAME as n, onError as o, $PROVIDE as p, DOWNGRADED_MODULE_COUNT_KEY as q, getDowngradedModuleCount as r, strictEquals as s, trustedHTMLFromLegacyTemplate as t, isNgModuleType as u, $DELEGATE as v, $INTERVAL as w, getAngularJSGlobal as x, getAngularLib as y, setAngularJSGlobal as z };
1242
+ //# sourceMappingURL=upgrade_helper-BOLCivYz.mjs.map