@angular/upgrade 21.0.0-next.0 → 21.0.0-next.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.
@@ -1,886 +1,20 @@
1
1
  /**
2
- * @license Angular v21.0.0-next.0
2
+ * @license Angular v21.0.0-next.2
3
3
  * (c) 2010-2025 Google LLC. https://angular.io/
4
4
  * License: MIT
5
5
  */
6
6
 
7
- import { UpgradeHelper, trustedHTMLFromLegacyTemplate, isFunction, strictEquals, downgradeComponent, onError, controllerKey, downgradeInjectable, Deferred, destroyApp } from './upgrade_helper.mjs';
8
- export { VERSION } from './upgrade_helper.mjs';
9
- import { __decorate, __metadata } from 'tslib';
10
- import * as i0 from '@angular/core';
11
- import { Inject, Injector, ElementRef, Directive, EventEmitter, NgZone, Compiler, NgModule, resolveForwardRef, Testability } from '@angular/core';
12
- import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
13
- import { $SCOPE, bootstrap, element, INJECTOR_KEY, $INJECTOR, module_, UPGRADE_APP_TYPE_KEY, LAZY_MODULE_REF, NG_ZONE_KEY, COMPILER_KEY, $ROOT_SCOPE, $$TESTABILITY, $COMPILE } from './constants.mjs';
7
+ import { Version } from '@angular/core';
14
8
 
15
- const CAMEL_CASE = /([A-Z])/g;
16
- const INITIAL_VALUE = {
17
- __UNINITIALIZED__: true,
18
- };
19
- const NOT_SUPPORTED = 'NOT_SUPPORTED';
20
- function getInputPropertyMapName(name) {
21
- return `input_${name}`;
22
- }
23
- function getOutputPropertyMapName(name) {
24
- return `output_${name}`;
25
- }
26
- class UpgradeNg1ComponentAdapterBuilder {
27
- name;
28
- type;
29
- inputs = [];
30
- inputsRename = [];
31
- outputs = [];
32
- outputsRename = [];
33
- propertyOutputs = [];
34
- checkProperties = [];
35
- propertyMap = {};
36
- directive = null;
37
- template;
38
- constructor(name) {
39
- this.name = name;
40
- const selector = name.replace(CAMEL_CASE, (all, next) => '-' + next.toLowerCase());
41
- const self = this;
42
- let MyClass = class MyClass extends UpgradeNg1ComponentAdapter {
43
- constructor(scope, injector, elementRef) {
44
- super(new UpgradeHelper(injector, name, elementRef, self.directive || undefined), scope, self.template, self.inputs, self.outputs, self.propertyOutputs, self.checkProperties, self.propertyMap);
45
- }
46
- static ctorParameters = () => [
47
- { type: undefined, decorators: [{ type: Inject, args: [$SCOPE,] }] },
48
- { type: Injector },
49
- { type: ElementRef }
50
- ];
51
- };
52
- MyClass = __decorate([
53
- Directive({
54
- jit: true,
55
- selector: selector,
56
- inputs: this.inputsRename,
57
- outputs: this.outputsRename,
58
- standalone: false,
59
- }),
60
- __metadata("design:paramtypes", [Object, Injector, ElementRef])
61
- ], MyClass);
62
- this.type = MyClass;
63
- }
64
- extractBindings() {
65
- const btcIsObject = typeof this.directive.bindToController === 'object';
66
- if (btcIsObject && Object.keys(this.directive.scope).length) {
67
- throw new Error(`Binding definitions on scope and controller at the same time are not supported.`);
68
- }
69
- const context = btcIsObject ? this.directive.bindToController : this.directive.scope;
70
- if (typeof context == 'object') {
71
- Object.keys(context).forEach((propName) => {
72
- const definition = context[propName];
73
- const bindingType = definition.charAt(0);
74
- const bindingOptions = definition.charAt(1);
75
- const attrName = definition.substring(bindingOptions === '?' ? 2 : 1) || propName;
76
- // QUESTION: What about `=*`? Ignore? Throw? Support?
77
- const inputName = getInputPropertyMapName(attrName);
78
- const inputNameRename = `${inputName}: ${attrName}`;
79
- const outputName = getOutputPropertyMapName(attrName);
80
- const outputNameRename = `${outputName}: ${attrName}`;
81
- const outputNameRenameChange = `${outputNameRename}Change`;
82
- switch (bindingType) {
83
- case '@':
84
- case '<':
85
- this.inputs.push(inputName);
86
- this.inputsRename.push(inputNameRename);
87
- this.propertyMap[inputName] = propName;
88
- break;
89
- case '=':
90
- this.inputs.push(inputName);
91
- this.inputsRename.push(inputNameRename);
92
- this.propertyMap[inputName] = propName;
93
- this.outputs.push(outputName);
94
- this.outputsRename.push(outputNameRenameChange);
95
- this.propertyMap[outputName] = propName;
96
- this.checkProperties.push(propName);
97
- this.propertyOutputs.push(outputName);
98
- break;
99
- case '&':
100
- this.outputs.push(outputName);
101
- this.outputsRename.push(outputNameRename);
102
- this.propertyMap[outputName] = propName;
103
- break;
104
- default:
105
- let json = JSON.stringify(context);
106
- throw new Error(`Unexpected mapping '${bindingType}' in '${json}' in '${this.name}' directive.`);
107
- }
108
- });
109
- }
110
- }
111
- /**
112
- * Upgrade ng1 components into Angular.
113
- */
114
- static resolve(exportedComponents, $injector) {
115
- const promises = Object.entries(exportedComponents).map(([name, exportedComponent]) => {
116
- exportedComponent.directive = UpgradeHelper.getDirective($injector, name);
117
- exportedComponent.extractBindings();
118
- return Promise.resolve(UpgradeHelper.getTemplate($injector, exportedComponent.directive, true)).then((template) => (exportedComponent.template = template));
119
- });
120
- return Promise.all(promises);
121
- }
122
- }
123
- class UpgradeNg1ComponentAdapter {
124
- helper;
125
- template;
126
- inputs;
127
- outputs;
128
- propOuts;
129
- checkProperties;
130
- propertyMap;
131
- controllerInstance = null;
132
- destinationObj = null;
133
- checkLastValues = [];
134
- directive;
135
- element;
136
- $element = null;
137
- componentScope;
138
- constructor(helper, scope, template, inputs, outputs, propOuts, checkProperties, propertyMap) {
139
- this.helper = helper;
140
- this.template = template;
141
- this.inputs = inputs;
142
- this.outputs = outputs;
143
- this.propOuts = propOuts;
144
- this.checkProperties = checkProperties;
145
- this.propertyMap = propertyMap;
146
- this.directive = helper.directive;
147
- this.element = helper.element;
148
- this.$element = helper.$element;
149
- this.componentScope = scope.$new(!!this.directive.scope);
150
- const controllerType = this.directive.controller;
151
- if (this.directive.bindToController && controllerType) {
152
- this.controllerInstance = this.helper.buildController(controllerType, this.componentScope);
153
- this.destinationObj = this.controllerInstance;
154
- }
155
- else {
156
- this.destinationObj = this.componentScope;
157
- }
158
- for (const input of this.inputs) {
159
- this[input] = null;
160
- }
161
- for (const output of this.outputs) {
162
- const emitter = (this[output] = new EventEmitter());
163
- if (this.propOuts.indexOf(output) === -1) {
164
- this.setComponentProperty(output, ((emitter) => (value) => emitter.emit(value))(emitter));
165
- }
166
- }
167
- this.checkLastValues.push(...Array(propOuts.length).fill(INITIAL_VALUE));
168
- }
169
- ngOnInit() {
170
- // Collect contents, insert and compile template
171
- const attachChildNodes = this.helper.prepareTransclusion();
172
- const linkFn = this.helper.compileTemplate(trustedHTMLFromLegacyTemplate(this.template));
173
- // Instantiate controller (if not already done so)
174
- const controllerType = this.directive.controller;
175
- const bindToController = this.directive.bindToController;
176
- if (controllerType && !bindToController) {
177
- this.controllerInstance = this.helper.buildController(controllerType, this.componentScope);
178
- }
179
- // Require other controllers
180
- const requiredControllers = this.helper.resolveAndBindRequiredControllers(this.controllerInstance);
181
- // Hook: $onInit
182
- if (this.controllerInstance && isFunction(this.controllerInstance.$onInit)) {
183
- this.controllerInstance.$onInit();
184
- }
185
- // Linking
186
- const link = this.directive.link;
187
- const preLink = typeof link == 'object' && link.pre;
188
- const postLink = typeof link == 'object' ? link.post : link;
189
- const attrs = NOT_SUPPORTED;
190
- const transcludeFn = NOT_SUPPORTED;
191
- if (preLink) {
192
- preLink(this.componentScope, this.$element, attrs, requiredControllers, transcludeFn);
193
- }
194
- linkFn(this.componentScope, null, { parentBoundTranscludeFn: attachChildNodes });
195
- if (postLink) {
196
- postLink(this.componentScope, this.$element, attrs, requiredControllers, transcludeFn);
197
- }
198
- // Hook: $postLink
199
- if (this.controllerInstance && isFunction(this.controllerInstance.$postLink)) {
200
- this.controllerInstance.$postLink();
201
- }
202
- }
203
- ngOnChanges(changes) {
204
- const ng1Changes = {};
205
- Object.keys(changes).forEach((propertyMapName) => {
206
- const change = changes[propertyMapName];
207
- this.setComponentProperty(propertyMapName, change.currentValue);
208
- ng1Changes[this.propertyMap[propertyMapName]] = change;
209
- });
210
- if (isFunction(this.destinationObj.$onChanges)) {
211
- this.destinationObj.$onChanges(ng1Changes);
212
- }
213
- }
214
- ngDoCheck() {
215
- const destinationObj = this.destinationObj;
216
- const lastValues = this.checkLastValues;
217
- const checkProperties = this.checkProperties;
218
- const propOuts = this.propOuts;
219
- checkProperties.forEach((propName, i) => {
220
- const value = destinationObj[propName];
221
- const last = lastValues[i];
222
- if (!strictEquals(last, value)) {
223
- const eventEmitter = this[propOuts[i]];
224
- eventEmitter.emit((lastValues[i] = value));
225
- }
226
- });
227
- if (this.controllerInstance && isFunction(this.controllerInstance.$doCheck)) {
228
- this.controllerInstance.$doCheck();
229
- }
230
- }
231
- ngOnDestroy() {
232
- this.helper.onDestroy(this.componentScope, this.controllerInstance);
233
- }
234
- setComponentProperty(name, value) {
235
- this.destinationObj[this.propertyMap[name]] = value;
236
- }
237
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.2.0-next.2", ngImport: i0, type: UpgradeNg1ComponentAdapter, deps: "invalid", target: i0.ɵɵFactoryTarget.Directive });
238
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "20.2.0-next.2", type: UpgradeNg1ComponentAdapter, isStandalone: true, usesOnChanges: true, ngImport: i0 });
239
- }
240
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.2.0-next.2", ngImport: i0, type: UpgradeNg1ComponentAdapter, decorators: [{
241
- type: Directive
242
- }], ctorParameters: () => [{ type: UpgradeHelper }, { type: undefined }, { type: undefined }, { type: undefined }, { type: undefined }, { type: undefined }, { type: undefined }, { type: undefined }] });
243
-
244
- let upgradeCount = 0;
245
9
  /**
246
- * Use `UpgradeAdapter` to allow AngularJS and Angular to coexist in a single application.
247
- *
248
- * The `UpgradeAdapter` allows:
249
- * 1. creation of Angular component from AngularJS component directive
250
- * (See {@link UpgradeAdapter#upgradeNg1Component})
251
- * 2. creation of AngularJS directive from Angular component.
252
- * (See {@link UpgradeAdapter#downgradeNg2Component})
253
- * 3. Bootstrapping of a hybrid Angular application which contains both of the frameworks
254
- * coexisting in a single application.
255
- *
256
- * @usageNotes
257
- * ### Mental Model
258
- *
259
- * When reasoning about how a hybrid application works it is useful to have a mental model which
260
- * describes what is happening and explains what is happening at the lowest level.
261
- *
262
- * 1. There are two independent frameworks running in a single application, each framework treats
263
- * the other as a black box.
264
- * 2. Each DOM element on the page is owned exactly by one framework. Whichever framework
265
- * instantiated the element is the owner. Each framework only updates/interacts with its own
266
- * DOM elements and ignores others.
267
- * 3. AngularJS directives always execute inside AngularJS framework codebase regardless of
268
- * where they are instantiated.
269
- * 4. Angular components always execute inside Angular framework codebase regardless of
270
- * where they are instantiated.
271
- * 5. An AngularJS component can be upgraded to an Angular component. This creates an
272
- * Angular directive, which bootstraps the AngularJS component directive in that location.
273
- * 6. An Angular component can be downgraded to an AngularJS component directive. This creates
274
- * an AngularJS directive, which bootstraps the Angular component in that location.
275
- * 7. Whenever an adapter component is instantiated the host element is owned by the framework
276
- * doing the instantiation. The other framework then instantiates and owns the view for that
277
- * component. This implies that component bindings will always follow the semantics of the
278
- * instantiation framework. The syntax is always that of Angular syntax.
279
- * 8. AngularJS is always bootstrapped first and owns the bottom most view.
280
- * 9. The new application is running in Angular zone, and therefore it no longer needs calls to
281
- * `$apply()`.
282
- *
283
- * ### Example
284
- *
285
- * ```ts
286
- * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions);
287
- * const module = angular.module('myExample', []);
288
- * module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component));
289
- *
290
- * module.directive('ng1Hello', function() {
291
- * return {
292
- * scope: { title: '=' },
293
- * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
294
- * };
295
- * });
296
- *
297
- *
298
- * @Component({
299
- * selector: 'ng2-comp',
300
- * inputs: ['name'],
301
- * template: 'ng2[<ng1-hello [title]="name">transclude</ng1-hello>](<ng-content></ng-content>)',
302
- * directives:
303
- * })
304
- * class Ng2Component {
305
- * }
306
- *
307
- * @NgModule({
308
- * declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')],
309
- * imports: [BrowserModule]
310
- * })
311
- * class MyNg2Module {}
312
- *
313
- *
314
- * document.body.innerHTML = '<ng2-comp name="World">project</ng2-comp>';
315
- *
316
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
317
- * expect(document.body.textContent).toEqual(
318
- * "ng2[ng1[Hello World!](transclude)](project)");
319
- * });
320
- *
321
- * ```
322
- *
323
- * @deprecated Deprecated since v5. Use `upgrade/static` instead, which also supports
324
- * [Ahead-of-Time compilation](tools/cli/aot-compiler).
325
- * @publicApi
10
+ * @module
11
+ * @description
12
+ * Entry point for all public APIs of the upgrade package.
326
13
  */
327
- class UpgradeAdapter {
328
- ng2AppModule;
329
- compilerOptions;
330
- idPrefix = `NG2_UPGRADE_${upgradeCount++}_`;
331
- downgradedComponents = [];
332
- /**
333
- * An internal map of ng1 components which need to up upgraded to ng2.
334
- *
335
- * We can't upgrade until injector is instantiated and we can retrieve the component metadata.
336
- * For this reason we keep a list of components to upgrade until ng1 injector is bootstrapped.
337
- *
338
- * @internal
339
- */
340
- ng1ComponentsToBeUpgraded = {};
341
- upgradedProviders = [];
342
- moduleRef = null;
343
- constructor(ng2AppModule, compilerOptions) {
344
- this.ng2AppModule = ng2AppModule;
345
- this.compilerOptions = compilerOptions;
346
- if (!ng2AppModule) {
347
- throw new Error('UpgradeAdapter cannot be instantiated without an NgModule of the Angular app.');
348
- }
349
- }
350
- /**
351
- * Allows Angular Component to be used from AngularJS.
352
- *
353
- * Use `downgradeNg2Component` to create an AngularJS Directive Definition Factory from
354
- * Angular Component. The adapter will bootstrap Angular component from within the
355
- * AngularJS template.
356
- *
357
- * @usageNotes
358
- * ### Mental Model
359
- *
360
- * 1. The component is instantiated by being listed in AngularJS template. This means that the
361
- * host element is controlled by AngularJS, but the component's view will be controlled by
362
- * Angular.
363
- * 2. Even thought the component is instantiated in AngularJS, it will be using Angular
364
- * syntax. This has to be done, this way because we must follow Angular components do not
365
- * declare how the attributes should be interpreted.
366
- * 3. `ng-model` is controlled by AngularJS and communicates with the downgraded Angular component
367
- * by way of the `ControlValueAccessor` interface from @angular/forms. Only components that
368
- * implement this interface are eligible.
369
- *
370
- * ### Supported Features
371
- *
372
- * - Bindings:
373
- * - Attribute: `<comp name="World">`
374
- * - Interpolation: `<comp greeting="Hello {{name}}!">`
375
- * - Expression: `<comp [name]="username">`
376
- * - Event: `<comp (close)="doSomething()">`
377
- * - ng-model: `<comp ng-model="name">`
378
- * - Content projection: yes
379
- *
380
- * ### Example
381
- *
382
- * ```angular-ts
383
- * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
384
- * const module = angular.module('myExample', []);
385
- * module.directive('greet', adapter.downgradeNg2Component(Greeter));
386
- *
387
- * @Component({
388
- * selector: 'greet',
389
- * template: '{{salutation()}} {{name()}}! - <ng-content></ng-content>'
390
- * })
391
- * class Greeter {
392
- * salutation = input.required<string>();
393
- * name: input.required<string>();
394
- * }
395
- *
396
- * @NgModule({
397
- * declarations: [Greeter],
398
- * imports: [BrowserModule]
399
- * })
400
- * class MyNg2Module {}
401
- *
402
- * document.body.innerHTML =
403
- * 'ng1 template: <greet salutation="Hello" [name]="world">text</greet>';
404
- *
405
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
406
- * expect(document.body.textContent).toEqual("ng1 template: Hello world! - text");
407
- * });
408
- * ```
409
- */
410
- downgradeNg2Component(component) {
411
- this.downgradedComponents.push(component);
412
- return downgradeComponent({ component });
413
- }
414
- /**
415
- * Allows AngularJS Component to be used from Angular.
416
- *
417
- * Use `upgradeNg1Component` to create an Angular component from AngularJS Component
418
- * directive. The adapter will bootstrap AngularJS component from within the Angular
419
- * template.
420
- *
421
- * @usageNotes
422
- * ### Mental Model
423
- *
424
- * 1. The component is instantiated by being listed in Angular template. This means that the
425
- * host element is controlled by Angular, but the component's view will be controlled by
426
- * AngularJS.
427
- *
428
- * ### Supported Features
429
- *
430
- * - Bindings:
431
- * - Attribute: `<comp name="World">`
432
- * - Interpolation: `<comp greeting="Hello {{name}}!">`
433
- * - Expression: `<comp [name]="username">`
434
- * - Event: `<comp (close)="doSomething()">`
435
- * - Transclusion: yes
436
- * - Only some of the features of
437
- * [Directive Definition Object](https://docs.angularjs.org/api/ng/service/$compile) are
438
- * supported:
439
- * - `compile`: not supported because the host element is owned by Angular, which does
440
- * not allow modifying DOM structure during compilation.
441
- * - `controller`: supported. (NOTE: injection of `$attrs` and `$transclude` is not supported.)
442
- * - `controllerAs`: supported.
443
- * - `bindToController`: supported.
444
- * - `link`: supported. (NOTE: only pre-link function is supported.)
445
- * - `name`: supported.
446
- * - `priority`: ignored.
447
- * - `replace`: not supported.
448
- * - `require`: supported.
449
- * - `restrict`: must be set to 'E'.
450
- * - `scope`: supported.
451
- * - `template`: supported.
452
- * - `templateUrl`: supported.
453
- * - `terminal`: ignored.
454
- * - `transclude`: supported.
455
- *
456
- *
457
- * ### Example
458
- *
459
- * ```angular-ts
460
- * const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module));
461
- * const module = angular.module('myExample', []);
462
- *
463
- * module.directive('greet', function() {
464
- * return {
465
- * scope: {salutation: '=', name: '=' },
466
- * template: '{{salutation}} {{name}}! - <span ng-transclude></span>'
467
- * };
468
- * });
469
- *
470
- * module.directive('ng2', adapter.downgradeNg2Component(Ng2Component));
471
- *
472
- * @Component({
473
- * selector: 'ng2',
474
- * template: 'ng2 template: <greet salutation="Hello" [name]="world">text</greet>'
475
- * })
476
- * class Ng2Component {
477
- * }
478
- *
479
- * @NgModule({
480
- * declarations: [Ng2Component, adapter.upgradeNg1Component('greet')],
481
- * imports: [BrowserModule]
482
- * })
483
- * class MyNg2Module {}
484
- *
485
- * document.body.innerHTML = '<ng2></ng2>';
486
- *
487
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
488
- * expect(document.body.textContent).toEqual("ng2 template: Hello world! - text");
489
- * });
490
- * ```
491
- */
492
- upgradeNg1Component(name) {
493
- if (this.ng1ComponentsToBeUpgraded.hasOwnProperty(name)) {
494
- return this.ng1ComponentsToBeUpgraded[name].type;
495
- }
496
- else {
497
- return (this.ng1ComponentsToBeUpgraded[name] = new UpgradeNg1ComponentAdapterBuilder(name))
498
- .type;
499
- }
500
- }
501
- /**
502
- * Registers the adapter's AngularJS upgrade module for unit testing in AngularJS.
503
- * Use this instead of `angular.mock.module()` to load the upgrade module into
504
- * the AngularJS testing injector.
505
- *
506
- * @usageNotes
507
- * ### Example
508
- *
509
- * ```ts
510
- * const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
511
- *
512
- * // configure the adapter with upgrade/downgrade components and services
513
- * upgradeAdapter.downgradeNg2Component(MyComponent);
514
- *
515
- * let upgradeAdapterRef: UpgradeAdapterRef;
516
- * let $compile, $rootScope;
517
- *
518
- * // We must register the adapter before any calls to `inject()`
519
- * beforeEach(() => {
520
- * upgradeAdapterRef = upgradeAdapter.registerForNg1Tests(['heroApp']);
521
- * });
522
- *
523
- * beforeEach(inject((_$compile_, _$rootScope_) => {
524
- * $compile = _$compile_;
525
- * $rootScope = _$rootScope_;
526
- * }));
527
- *
528
- * it("says hello", (done) => {
529
- * upgradeAdapterRef.ready(() => {
530
- * const element = $compile("<my-component></my-component>")($rootScope);
531
- * $rootScope.$apply();
532
- * expect(element.html()).toContain("Hello World");
533
- * done();
534
- * })
535
- * });
536
- *
537
- * ```
538
- *
539
- * @param modules any AngularJS modules that the upgrade module should depend upon
540
- * @returns an `UpgradeAdapterRef`, which lets you register a `ready()` callback to
541
- * run assertions once the Angular components are ready to test through AngularJS.
542
- */
543
- registerForNg1Tests(modules) {
544
- const windowNgMock = window['angular'].mock;
545
- if (!windowNgMock || !windowNgMock.module) {
546
- throw new Error("Failed to find 'angular.mock.module'.");
547
- }
548
- const { ng1Module, ng2BootstrapDeferred } = this.declareNg1Module(modules);
549
- windowNgMock.module(ng1Module.name);
550
- const upgrade = new UpgradeAdapterRef();
551
- ng2BootstrapDeferred.promise.then((ng1Injector) => {
552
- // @ts-expect-error
553
- upgrade._bootstrapDone(this.moduleRef, ng1Injector);
554
- }, onError);
555
- return upgrade;
556
- }
557
- /**
558
- * Bootstrap a hybrid AngularJS / Angular application.
559
- *
560
- * This `bootstrap` method is a direct replacement (takes same arguments) for AngularJS
561
- * [`bootstrap`](https://docs.angularjs.org/api/ng/function/angular.bootstrap) method. Unlike
562
- * AngularJS, this bootstrap is asynchronous.
563
- *
564
- * @usageNotes
565
- * ### Example
566
- *
567
- * ```angular-ts
568
- * const adapter = new UpgradeAdapter(MyNg2Module);
569
- * const module = angular.module('myExample', []);
570
- * module.directive('ng2', adapter.downgradeNg2Component(Ng2));
571
- *
572
- * module.directive('ng1', function() {
573
- * return {
574
- * scope: { title: '=' },
575
- * template: 'ng1[Hello {{title}}!](<span ng-transclude></span>)'
576
- * };
577
- * });
578
- *
579
- *
580
- * @Component({
581
- * selector: 'ng2',
582
- * inputs: ['name'],
583
- * template: 'ng2[<ng1 [title]="name">transclude</ng1>](<ng-content></ng-content>)'
584
- * })
585
- * class Ng2 {
586
- * }
587
- *
588
- * @NgModule({
589
- * declarations: [Ng2, adapter.upgradeNg1Component('ng1')],
590
- * imports: [BrowserModule]
591
- * })
592
- * class MyNg2Module {}
593
- *
594
- * document.body.innerHTML = '<ng2 name="World">project</ng2>';
595
- *
596
- * adapter.bootstrap(document.body, ['myExample']).ready(function() {
597
- * expect(document.body.textContent).toEqual(
598
- * "ng2[ng1[Hello World!](transclude)](project)");
599
- * });
600
- * ```
601
- */
602
- bootstrap(element$1, modules, config) {
603
- const { ng1Module, ng2BootstrapDeferred, ngZone } = this.declareNg1Module(modules);
604
- const upgrade = new UpgradeAdapterRef();
605
- // Make sure resumeBootstrap() only exists if the current bootstrap is deferred
606
- const windowAngular = window['angular'];
607
- windowAngular.resumeBootstrap = undefined;
608
- ngZone.run(() => {
609
- bootstrap(element$1, [ng1Module.name], config);
610
- });
611
- const ng1BootstrapPromise = new Promise((resolve) => {
612
- if (windowAngular.resumeBootstrap) {
613
- const originalResumeBootstrap = windowAngular.resumeBootstrap;
614
- windowAngular.resumeBootstrap = function () {
615
- windowAngular.resumeBootstrap = originalResumeBootstrap;
616
- const r = windowAngular.resumeBootstrap.apply(this, arguments);
617
- resolve();
618
- return r;
619
- };
620
- }
621
- else {
622
- resolve();
623
- }
624
- });
625
- Promise.all([ng2BootstrapDeferred.promise, ng1BootstrapPromise]).then(([ng1Injector]) => {
626
- element(element$1).data(controllerKey(INJECTOR_KEY), this.moduleRef.injector);
627
- this.moduleRef.injector.get(NgZone).run(() => {
628
- // @ts-expect-error
629
- upgrade._bootstrapDone(this.moduleRef, ng1Injector);
630
- });
631
- }, onError);
632
- return upgrade;
633
- }
634
- /**
635
- * Allows AngularJS service to be accessible from Angular.
636
- *
637
- * @usageNotes
638
- * ### Example
639
- *
640
- * ```ts
641
- * class Login { ... }
642
- * class Server { ... }
643
- *
644
- * @Injectable()
645
- * class Example {
646
- * constructor(@Inject('server') server, login: Login) {
647
- * ...
648
- * }
649
- * }
650
- *
651
- * const module = angular.module('myExample', []);
652
- * module.service('server', Server);
653
- * module.service('login', Login);
654
- *
655
- * const adapter = new UpgradeAdapter(MyNg2Module);
656
- * adapter.upgradeNg1Provider('server');
657
- * adapter.upgradeNg1Provider('login', {asToken: Login});
658
- *
659
- * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
660
- * const example: Example = ref.ng2Injector.get(Example);
661
- * });
662
- *
663
- * ```
664
- */
665
- upgradeNg1Provider(name, options) {
666
- const token = (options && options.asToken) || name;
667
- this.upgradedProviders.push({
668
- provide: token,
669
- useFactory: ($injector) => $injector.get(name),
670
- deps: [$INJECTOR],
671
- });
672
- }
673
- /**
674
- * Allows Angular service to be accessible from AngularJS.
675
- *
676
- * @usageNotes
677
- * ### Example
678
- *
679
- * ```ts
680
- * class Example {
681
- * }
682
- *
683
- * const adapter = new UpgradeAdapter(MyNg2Module);
684
- *
685
- * const module = angular.module('myExample', []);
686
- * module.factory('example', adapter.downgradeNg2Provider(Example));
687
- *
688
- * adapter.bootstrap(document.body, ['myExample']).ready((ref) => {
689
- * const example: Example = ref.ng1Injector.get('example');
690
- * });
691
- *
692
- * ```
693
- */
694
- downgradeNg2Provider(token) {
695
- return downgradeInjectable(token);
696
- }
697
- /**
698
- * Declare the AngularJS upgrade module for this adapter without bootstrapping the whole
699
- * hybrid application.
700
- *
701
- * This method is automatically called by `bootstrap()` and `registerForNg1Tests()`.
702
- *
703
- * @param modules The AngularJS modules that this upgrade module should depend upon.
704
- * @returns The AngularJS upgrade module that is declared by this method
705
- *
706
- * @usageNotes
707
- * ### Example
708
- *
709
- * ```ts
710
- * const upgradeAdapter = new UpgradeAdapter(MyNg2Module);
711
- * upgradeAdapter.declareNg1Module(['heroApp']);
712
- * ```
713
- */
714
- declareNg1Module(modules = []) {
715
- const delayApplyExps = [];
716
- let original$applyFn;
717
- let rootScopePrototype;
718
- const upgradeAdapter = this;
719
- const ng1Module = module_(this.idPrefix, modules);
720
- const platformRef = platformBrowserDynamic();
721
- const ngZone = new NgZone({
722
- enableLongStackTrace: Zone.hasOwnProperty('longStackTraceZoneSpec'),
723
- });
724
- const ng2BootstrapDeferred = new Deferred();
725
- ng1Module
726
- .constant(UPGRADE_APP_TYPE_KEY, 1 /* UpgradeAppType.Dynamic */)
727
- .factory(INJECTOR_KEY, () => this.moduleRef.injector.get(Injector))
728
- .factory(LAZY_MODULE_REF, [
729
- INJECTOR_KEY,
730
- (injector) => ({ injector }),
731
- ])
732
- .constant(NG_ZONE_KEY, ngZone)
733
- .factory(COMPILER_KEY, () => this.moduleRef.injector.get(Compiler))
734
- .config([
735
- '$provide',
736
- '$injector',
737
- (provide, ng1Injector) => {
738
- provide.decorator($ROOT_SCOPE, [
739
- '$delegate',
740
- function (rootScopeDelegate) {
741
- // Capture the root apply so that we can delay first call to $apply until we
742
- // bootstrap Angular and then we replay and restore the $apply.
743
- rootScopePrototype = rootScopeDelegate.constructor.prototype;
744
- if (rootScopePrototype.hasOwnProperty('$apply')) {
745
- original$applyFn = rootScopePrototype.$apply;
746
- rootScopePrototype.$apply = (exp) => delayApplyExps.push(exp);
747
- }
748
- else {
749
- throw new Error("Failed to find '$apply' on '$rootScope'!");
750
- }
751
- return rootScopeDelegate;
752
- },
753
- ]);
754
- if (ng1Injector.has($$TESTABILITY)) {
755
- provide.decorator($$TESTABILITY, [
756
- '$delegate',
757
- function (testabilityDelegate) {
758
- const originalWhenStable = testabilityDelegate.whenStable;
759
- // Cannot use arrow function below because we need the context
760
- const newWhenStable = function (callback) {
761
- originalWhenStable.call(this, function () {
762
- const ng2Testability = upgradeAdapter.moduleRef.injector.get(Testability);
763
- if (ng2Testability.isStable()) {
764
- callback.apply(this, arguments);
765
- }
766
- else {
767
- ng2Testability.whenStable(newWhenStable.bind(this, callback));
768
- }
769
- });
770
- };
771
- testabilityDelegate.whenStable = newWhenStable;
772
- return testabilityDelegate;
773
- },
774
- ]);
775
- }
776
- },
777
- ]);
778
- ng1Module.run([
779
- '$injector',
780
- '$rootScope',
781
- (ng1Injector, rootScope) => {
782
- UpgradeNg1ComponentAdapterBuilder.resolve(this.ng1ComponentsToBeUpgraded, ng1Injector)
783
- .then(() => {
784
- // At this point we have ng1 injector and we have prepared
785
- // ng1 components to be upgraded, we now can bootstrap ng2.
786
- let DynamicNgUpgradeModule = class DynamicNgUpgradeModule {
787
- ngDoBootstrap() { }
788
- };
789
- DynamicNgUpgradeModule = __decorate([
790
- NgModule({
791
- jit: true,
792
- providers: [
793
- { provide: $INJECTOR, useFactory: () => ng1Injector },
794
- { provide: $COMPILE, useFactory: () => ng1Injector.get($COMPILE) },
795
- this.upgradedProviders,
796
- ],
797
- imports: [resolveForwardRef(this.ng2AppModule)],
798
- })
799
- ], DynamicNgUpgradeModule);
800
- platformRef
801
- .bootstrapModule(DynamicNgUpgradeModule, [this.compilerOptions, { ngZone }])
802
- .then((ref) => {
803
- this.moduleRef = ref;
804
- ngZone.run(() => {
805
- if (rootScopePrototype) {
806
- rootScopePrototype.$apply = original$applyFn; // restore original $apply
807
- while (delayApplyExps.length) {
808
- rootScope.$apply(delayApplyExps.shift());
809
- }
810
- rootScopePrototype = null;
811
- }
812
- });
813
- })
814
- .then(() => ng2BootstrapDeferred.resolve(ng1Injector), onError)
815
- .then(() => {
816
- let subscription = ngZone.onMicrotaskEmpty.subscribe({
817
- next: () => {
818
- if (rootScope.$$phase) {
819
- if (typeof ngDevMode === 'undefined' || ngDevMode) {
820
- console.warn('A digest was triggered while one was already in progress. This may mean that something is triggering digests outside the Angular zone.');
821
- }
822
- return rootScope.$evalAsync(() => { });
823
- }
824
- return rootScope.$digest();
825
- },
826
- });
827
- rootScope.$on('$destroy', () => {
828
- subscription.unsubscribe();
829
- });
830
- // Destroy the AngularJS app once the Angular `PlatformRef` is destroyed.
831
- // This does not happen in a typical SPA scenario, but it might be useful for
832
- // other use-cases where disposing of an Angular/AngularJS app is necessary
833
- // (such as Hot Module Replacement (HMR)).
834
- // See https://github.com/angular/angular/issues/39935.
835
- platformRef.onDestroy(() => destroyApp(ng1Injector));
836
- });
837
- })
838
- .catch((e) => ng2BootstrapDeferred.reject(e));
839
- },
840
- ]);
841
- return { ng1Module, ng2BootstrapDeferred, ngZone };
842
- }
843
- }
844
14
  /**
845
- * Use `UpgradeAdapterRef` to control a hybrid AngularJS / Angular application.
846
- *
847
- * @deprecated Deprecated since v5. Use `upgrade/static` instead, which also supports
848
- * [Ahead-of-Time compilation](tools/cli/aot-compiler).
849
15
  * @publicApi
850
16
  */
851
- class UpgradeAdapterRef {
852
- /* @internal */
853
- _readyFn = null;
854
- ng1RootScope = null;
855
- ng1Injector = null;
856
- ng2ModuleRef = null;
857
- ng2Injector = null;
858
- /* @internal */
859
- _bootstrapDone(ngModuleRef, ng1Injector) {
860
- this.ng2ModuleRef = ngModuleRef;
861
- this.ng2Injector = ngModuleRef.injector;
862
- this.ng1Injector = ng1Injector;
863
- this.ng1RootScope = ng1Injector.get($ROOT_SCOPE);
864
- this._readyFn && this._readyFn(this);
865
- }
866
- /**
867
- * Register a callback function which is notified upon successful hybrid AngularJS / Angular
868
- * application has been bootstrapped.
869
- *
870
- * The `ready` callback function is invoked inside the Angular zone, therefore it does not
871
- * require a call to `$apply()`.
872
- */
873
- ready(fn) {
874
- this._readyFn = fn;
875
- }
876
- /**
877
- * Dispose of running hybrid AngularJS / Angular application.
878
- */
879
- dispose() {
880
- this.ng1Injector.get($ROOT_SCOPE).$destroy();
881
- this.ng2ModuleRef.destroy();
882
- }
883
- }
17
+ const VERSION = new Version('21.0.0-next.2');
884
18
 
885
- export { UpgradeAdapter, UpgradeAdapterRef };
19
+ export { VERSION };
886
20
  //# sourceMappingURL=upgrade.mjs.map