Browse Source

fix all lint errors

pull/9837/head
mehmet-erim 5 years ago
parent
commit
682d8ab184
  1. 1
      npm/ng-packs/nx/ng-packs/.eslintignore
  2. 7
      npm/ng-packs/nx/ng-packs/.eslintrc.json
  3. 5
      npm/ng-packs/nx/ng-packs/.prettierrc
  4. 2
      npm/ng-packs/nx/ng-packs/apps/dev-app/.eslintrc.json
  5. 1
      npm/ng-packs/nx/ng-packs/package.json
  6. 2
      npm/ng-packs/nx/ng-packs/packages/account/src/lib/components/manage-profile/manage-profile.component.html
  7. 4
      npm/ng-packs/nx/ng-packs/packages/account/src/lib/models/account.ts
  8. 19
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/abstracts/ng-model.component.ts
  9. 6
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/autofocus.directive.ts
  10. 20
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/debounce.directive.ts
  11. 85
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/for.directive.ts
  12. 19
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/form-submit.directive.ts
  13. 17
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/replaceable-template.directive.ts
  14. 26
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/stop-propagation.directive.ts
  15. 3
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/visibility.directive.ts
  16. 29
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/dtos.ts
  17. 10
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/replaceable-components.ts
  18. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/utility.ts
  19. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/proxy/volo/abp/asp-net-core/mvc/application-configurations/object-extending/models.ts
  20. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/proxy/volo/abp/http/modeling/models.ts
  21. 8
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/list.service.ts
  22. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/routes.service.ts
  23. 15
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/track-by.service.ts
  24. 57
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/config-state.service.spec.ts
  25. 72
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/permission.guard.spec.ts
  26. 6
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/replaceable-template.directive.spec.ts
  27. 2
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/routes.service.spec.ts
  28. 40
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/utils/rxjs-utils.ts
  29. 1
      npm/ng-packs/nx/ng-packs/packages/core/src/lib/utils/tree-utils.ts
  30. 3
      npm/ng-packs/nx/ng-packs/packages/feature-management/src/lib/directives/free-text-input.directive.ts
  31. 1
      npm/ng-packs/nx/ng-packs/packages/feature-management/src/lib/proxy/validation/string-values/models.ts
  32. 12
      npm/ng-packs/nx/ng-packs/packages/identity/src/lib/proxy/identity/models.ts
  33. 15
      npm/ng-packs/nx/ng-packs/packages/schematics/.eslintrc.json
  34. 3
      npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/api/index.ts
  35. 3
      npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/proxy-index/index.ts
  36. 3
      npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/proxy-remove/index.ts
  37. 2
      npm/ng-packs/nx/ng-packs/packages/schematics/src/models/method.ts
  38. 2
      npm/ng-packs/nx/ng-packs/packages/schematics/src/models/util.ts
  39. 247
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/ast-utils.ts
  40. 571
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/config.ts
  41. 58
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/find-module.ts
  42. 1
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/workspace-models.ts
  43. 4
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/enum.ts
  44. 2
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/generics.ts
  45. 1
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/model.ts
  46. 1
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/source.ts
  47. 3
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/text.ts
  48. 1
      npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/workspace.ts
  49. 11
      npm/ng-packs/nx/ng-packs/packages/tenant-management/src/lib/proxy/models.ts
  50. 6
      npm/ng-packs/nx/ng-packs/packages/theme-basic/src/lib/components/account-layout/auth-wrapper/auth-wrapper.component.ts
  51. 6
      npm/ng-packs/nx/ng-packs/packages/theme-basic/src/lib/components/account-layout/tenant-box/tenant-box.component.ts
  52. 11
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/button/button.component.ts
  53. 4
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/chart/chart.component.ts
  54. 8
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/loading/loading.component.ts
  55. 6
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/table-empty-message/table-empty-message.component.ts
  56. 2
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/directives/ngx-datatable-default.directive.ts
  57. 2
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/directives/ngx-datatable-list.directive.ts
  58. 63
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts
  59. 1
      npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/tests/breadcrumb.component.spec.ts

1
npm/ng-packs/nx/ng-packs/.eslintignore

@ -0,0 +1 @@
*.d.ts

7
npm/ng-packs/nx/ng-packs/.eslintrc.json

@ -20,11 +20,14 @@
}
]
}
},
},
{
"files": ["*.ts", "*.tsx"],
"extends": ["plugin:@nrwl/nx/typescript"],
"rules": {}
"rules": {
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-empty-function": ["warn"]
}
},
{
"files": ["*.js", "*.jsx"],

5
npm/ng-packs/nx/ng-packs/.prettierrc

@ -1,3 +1,6 @@
{
"singleQuote": true
"printWidth": 100,
"singleQuote": true,
"trailingComma": "all",
"arrowParens": "avoid"
}

2
npm/ng-packs/nx/ng-packs/apps/dev-app/.eslintrc.json

@ -21,7 +21,7 @@
"error",
{
"type": "element",
"prefix": "abp",
"prefix": "app",
"style": "kebab-case"
}
]

1
npm/ng-packs/nx/ng-packs/package.json

@ -11,6 +11,7 @@
"test": "ng test --detect-open-handles=true --run-in-band=true --watch-all=true",
"test:all": "nx run-many --target=test --all",
"lint": "nx workspace-lint && ng lint",
"lint:all": "nx run-many --target=lint --all",
"e2e": "ng e2e",
"affected:apps": "nx affected:apps",
"affected:libs": "nx affected:libs",

2
npm/ng-packs/nx/ng-packs/packages/account/src/lib/components/manage-profile/manage-profile.component.html

@ -1,6 +1,6 @@
<div id="AbpContentToolbar"></div>
<div class="card border-0 shadow-sm min-h-400" [abpLoading]="!(profile$ | async)">
<div class="card border-0 shadow-sm min-h-400" [abpLoading]="(profile$ | async)?.userName">
<div class="card-body">
<div class="row">
<div class="col-12 col-md-3">

4
npm/ng-packs/nx/ng-packs/packages/account/src/lib/models/account.ts

@ -1,12 +1,10 @@
import { TemplateRef } from '@angular/core';
/* eslint-disable @typescript-eslint/no-empty-interface */
export namespace Account {
//tslint:disable
export interface TenantBoxComponentInputs {}
export interface TenantBoxComponentOutputs {}
export interface PersonalSettingsComponentInputs {}
export interface PersonalSettingsComponentOutputs {}
export interface ChangePasswordComponentInputs {}
export interface ChangePasswordComponentOutputs {}
// tslint:enable
}

19
npm/ng-packs/nx/ng-packs/packages/core/src/lib/abstracts/ng-model.component.ts

@ -1,14 +1,16 @@
import { ControlValueAccessor } from '@angular/forms';
import { ChangeDetectorRef, Component, Injector, Input } from '@angular/core';
import { ControlValueAccessor } from '@angular/forms';
// Not an abstract class on purpose. Do not change!
// tslint:disable-next-line: use-component-selector
@Component({ template: '' })
export class AbstractNgModelComponent<T = any, U = T> implements ControlValueAccessor {
export class AbstractNgModelComponent<T = any, U = T>
implements ControlValueAccessor
{
protected _value: T;
protected cdRef: ChangeDetectorRef;
onChange: (value: T) => {};
onTouched: () => {};
onChange: (value: T) => void;
onTouched: () => void;
@Input()
disabled: boolean;
@ -17,16 +19,17 @@ export class AbstractNgModelComponent<T = any, U = T> implements ControlValueAcc
readonly: boolean;
@Input()
valueFn: (value: U, previousValue?: T) => T = value => (value as any) as T;
valueFn: (value: U, previousValue?: T) => T = (value) => value as any as T;
@Input()
valueLimitFn: (value: T, previousValue?: T) => any = value => false;
valueLimitFn: (value: T, previousValue?: T) => any = (value) => false;
@Input()
set value(value: T) {
value = this.valueFn((value as any) as U, this._value);
value = this.valueFn(value as any as U, this._value);
if (this.valueLimitFn(value, this._value) !== false || this.readonly) return;
if (this.valueLimitFn(value, this._value) !== false || this.readonly)
return;
this._value = value;
this.notifyValueChange();

6
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/autofocus.directive.ts

@ -1,8 +1,8 @@
import { Directive, ElementRef, Input, AfterViewInit } from '@angular/core';
import { AfterViewInit, Directive, ElementRef, Input } from '@angular/core';
@Directive({
// tslint:disable-next-line: directive-selector
selector: '[autofocus]'
// eslint-disable-next-line @angular-eslint/directive-selector
selector: '[autofocus]',
})
export class AutofocusDirective implements AfterViewInit {
@Input('autofocus')

20
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/debounce.directive.ts

@ -1,10 +1,17 @@
import { Directive, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
import {
Directive,
ElementRef,
EventEmitter,
Input,
OnInit,
Output,
} from '@angular/core';
import { fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { SubscriptionService } from '../services/subscription.service';
@Directive({
// tslint:disable-next-line: directive-selector
// eslint-disable-next-line @angular-eslint/directive-selector
selector: '[input.debounce]',
providers: [SubscriptionService],
})
@ -13,10 +20,15 @@ export class InputEventDebounceDirective implements OnInit {
@Output('input.debounce') readonly debounceEvent = new EventEmitter<Event>();
constructor(private el: ElementRef, private subscription: SubscriptionService) {}
constructor(
private el: ElementRef,
private subscription: SubscriptionService
) {}
ngOnInit(): void {
const input$ = fromEvent(this.el.nativeElement, 'input').pipe(debounceTime(this.debounce));
const input$ = fromEvent(this.el.nativeElement, 'input').pipe(
debounceTime(this.debounce)
);
this.subscription.addOne(input$, (event: Event) => {
this.debounceEvent.emit(event);

85
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/for.directive.ts

@ -11,23 +11,32 @@ import {
TrackByFunction,
ViewContainerRef,
} from '@angular/core';
import compare from 'just-compare';
import clone from 'just-clone';
import compare from 'just-compare';
export type CompareFn<T = any> = (value: T, comparison: T) => boolean;
class AbpForContext {
constructor(public $implicit: any, public index: number, public count: number, public list: any[]) {}
constructor(
public $implicit: any,
public index: number,
public count: number,
public list: any[]
) {}
}
class RecordView {
constructor(public record: IterableChangeRecord<any>, public view: EmbeddedViewRef<AbpForContext>) {}
constructor(
public record: IterableChangeRecord<any>,
public view: EmbeddedViewRef<AbpForContext>
) {}
}
@Directive({
selector: '[abpFor]',
})
export class ForDirective implements OnChanges {
// eslint-disable-next-line @angular-eslint/no-input-rename
@Input('abpForOf')
items: any[];
@ -61,36 +70,46 @@ export class ForDirective implements OnChanges {
}
get trackByFn(): TrackByFunction<any> {
return this.trackBy || ((index: number, item: any) => (item as any).id || index);
return (
this.trackBy || ((index: number, item: any) => (item as any).id || index)
);
}
constructor(
private tempRef: TemplateRef<AbpForContext>,
private vcRef: ViewContainerRef,
private differs: IterableDiffers,
private differs: IterableDiffers
) {}
private iterateOverAppliedOperations(changes: IterableChanges<any>) {
const rw: RecordView[] = [];
changes.forEachOperation((record: IterableChangeRecord<any>, previousIndex: number, currentIndex: number) => {
if (record.previousIndex == null) {
const view = this.vcRef.createEmbeddedView(
this.tempRef,
new AbpForContext(null, -1, -1, this.items),
currentIndex,
);
rw.push(new RecordView(record, view));
} else if (currentIndex == null) {
this.vcRef.remove(previousIndex);
} else {
const view = this.vcRef.get(previousIndex);
this.vcRef.move(view, currentIndex);
rw.push(new RecordView(record, view as EmbeddedViewRef<AbpForContext>));
changes.forEachOperation(
(
record: IterableChangeRecord<any>,
previousIndex: number,
currentIndex: number
) => {
if (record.previousIndex == null) {
const view = this.vcRef.createEmbeddedView(
this.tempRef,
new AbpForContext(null, -1, -1, this.items),
currentIndex
);
rw.push(new RecordView(record, view));
} else if (currentIndex == null) {
this.vcRef.remove(previousIndex);
} else {
const view = this.vcRef.get(previousIndex);
this.vcRef.move(view, currentIndex);
rw.push(
new RecordView(record, view as EmbeddedViewRef<AbpForContext>)
);
}
}
});
);
for (let i = 0, l = rw.length; i < l; i++) {
rw[i].view.context.$implicit = rw[i].record.item;
@ -106,7 +125,9 @@ export class ForDirective implements OnChanges {
}
changes.forEachIdentityChange((record: IterableChangeRecord<any>) => {
const viewRef = this.vcRef.get(record.currentIndex) as EmbeddedViewRef<AbpForContext>;
const viewRef = this.vcRef.get(
record.currentIndex
) as EmbeddedViewRef<AbpForContext>;
viewRef.context.$implicit = record.item;
});
}
@ -143,7 +164,13 @@ export class ForDirective implements OnChanges {
private sortItems(items: any[]) {
if (this.orderBy) {
items.sort((a, b) => (a[this.orderBy] > b[this.orderBy] ? 1 : a[this.orderBy] < b[this.orderBy] ? -1 : 0));
items.sort((a, b) =>
a[this.orderBy] > b[this.orderBy]
? 1
: a[this.orderBy] < b[this.orderBy]
? -1
: 0
);
} else {
items.sort();
}
@ -155,8 +182,14 @@ export class ForDirective implements OnChanges {
const compareFn = this.compareFn;
if (typeof this.filterBy !== 'undefined' && typeof this.filterVal !== 'undefined' && this.filterVal !== '') {
items = items.filter(item => compareFn(item[this.filterBy], this.filterVal));
if (
typeof this.filterBy !== 'undefined' &&
typeof this.filterVal !== 'undefined' &&
this.filterVal !== ''
) {
items = items.filter((item) =>
compareFn(item[this.filterBy], this.filterVal)
);
}
switch (this.orderDir) {

19
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/form-submit.directive.ts

@ -16,7 +16,7 @@ import { SubscriptionService } from '../services/subscription.service';
type Controls = { [key: string]: FormControl } | FormGroup[];
@Directive({
// tslint:disable-next-line: directive-selector
// eslint-disable-next-line @angular-eslint/directive-selector
selector: 'form[ngSubmit][formGroup]',
providers: [SubscriptionService],
})
@ -35,7 +35,7 @@ export class FormSubmitDirective implements OnInit {
@Self() private formGroupDirective: FormGroupDirective,
private host: ElementRef<HTMLFormElement>,
private cdRef: ChangeDetectorRef,
private subscription: SubscriptionService,
private subscription: SubscriptionService
) {}
ngOnInit() {
@ -44,16 +44,19 @@ export class FormSubmitDirective implements OnInit {
this.executedNgSubmit = true;
});
const keyup$ = fromEvent(this.host.nativeElement as HTMLElement, 'keyup').pipe(
const keyup$ = fromEvent(
this.host.nativeElement as HTMLElement,
'keyup'
).pipe(
debounceTime(this.debounce),
filter(event => !(event.target instanceof HTMLTextAreaElement)),
filter((event: KeyboardEvent) => event && event.key === 'Enter'),
filter((event) => !(event.target instanceof HTMLTextAreaElement)),
filter((event: KeyboardEvent) => event && event.key === 'Enter')
);
this.subscription.addOne(keyup$, () => {
if (!this.executedNgSubmit) {
this.host.nativeElement.dispatchEvent(
new Event('submit', { bubbles: true, cancelable: true }),
new Event('submit', { bubbles: true, cancelable: true })
);
}
@ -73,13 +76,13 @@ export class FormSubmitDirective implements OnInit {
function setDirty(controls: Controls) {
if (Array.isArray(controls)) {
controls.forEach(group => {
controls.forEach((group) => {
setDirty(group.controls as { [key: string]: FormControl });
});
return;
}
Object.keys(controls).forEach(key => {
Object.keys(controls).forEach((key) => {
controls[key].markAsDirty();
controls[key].updateValueAndValidity();
});

17
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/replaceable-template.directive.ts

@ -19,15 +19,18 @@ import { ReplaceableComponents } from '../models/replaceable-components';
import { ReplaceableComponentsService } from '../services/replaceable-components.service';
import { SubscriptionService } from '../services/subscription.service';
@Directive({ selector: '[abpReplaceableTemplate]', providers: [SubscriptionService] })
@Directive({
selector: '[abpReplaceableTemplate]',
providers: [SubscriptionService],
})
export class ReplaceableTemplateDirective implements OnInit, OnChanges {
@Input('abpReplaceableTemplate')
data: ReplaceableComponents.ReplaceableTemplateDirectiveInput<any, any>;
providedData = { inputs: {}, outputs: {} } as ReplaceableComponents.ReplaceableTemplateData<
any,
any
>;
providedData = {
inputs: {},
outputs: {},
} as ReplaceableComponents.ReplaceableTemplateData<any, any>;
context = {} as any;
@ -106,7 +109,7 @@ export class ReplaceableTemplateDirective implements OnInit, OnChanges {
if (this.data.inputs) {
for (const key in this.data.inputs) {
if (this.data.inputs.hasOwnProperty(key)) {
if (Object.prototype.hasOwnProperty.call(this.data.inputs, key)) {
if (!compare(this.defaultComponentRef[key], this.data.inputs[key].value)) {
this.defaultComponentRef[key] = this.data.inputs[key].value;
}
@ -116,7 +119,7 @@ export class ReplaceableTemplateDirective implements OnInit, OnChanges {
if (this.data.outputs) {
for (const key in this.data.outputs) {
if (this.data.outputs.hasOwnProperty(key)) {
if (Object.prototype.hasOwnProperty.call(this.data.outputs, key)) {
if (!this.defaultComponentSubscriptions[key]) {
this.defaultComponentSubscriptions[key] = this.defaultComponentRef[key].subscribe(
value => {

26
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/stop-propagation.directive.ts

@ -1,21 +1,33 @@
import { Directive, ElementRef, EventEmitter, OnInit, Output } from '@angular/core';
import {
Directive,
ElementRef,
EventEmitter,
OnInit,
Output,
} from '@angular/core';
import { fromEvent } from 'rxjs';
import { SubscriptionService } from '../services/subscription.service';
@Directive({
// tslint:disable-next-line: directive-selector
// eslint-disable-next-line @angular-eslint/directive-selector
selector: '[click.stop]',
providers: [SubscriptionService],
})
export class StopPropagationDirective implements OnInit {
@Output('click.stop') readonly stopPropEvent = new EventEmitter<MouseEvent>();
constructor(private el: ElementRef, private subscription: SubscriptionService) {}
constructor(
private el: ElementRef,
private subscription: SubscriptionService
) {}
ngOnInit(): void {
this.subscription.addOne(fromEvent(this.el.nativeElement, 'click'), (event: MouseEvent) => {
event.stopPropagation();
this.stopPropEvent.emit(event);
});
this.subscription.addOne(
fromEvent(this.el.nativeElement, 'click'),
(event: MouseEvent) => {
event.stopPropagation();
this.stopPropEvent.emit(event);
}
);
}
}

3
npm/ng-packs/nx/ng-packs/packages/core/src/lib/directives/visibility.directive.ts

@ -22,8 +22,7 @@ export class VisibilityDirective implements AfterViewInit {
this.focusedElement = this.elRef.nativeElement;
}
let observer: MutationObserver;
observer = new MutationObserver(mutations => {
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (!mutation.target) return;

29
npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/dtos.ts

@ -5,7 +5,7 @@ export class ListResultDto<T> {
constructor(initialValues: Partial<ListResultDto<T>> = {}) {
for (const key in initialValues) {
if (initialValues.hasOwnProperty(key)) {
if (Object.prototype.hasOwnProperty.call(initialValues, key)) {
this[key] = initialValues[key];
}
}
@ -25,7 +25,10 @@ export class LimitedResultRequestDto {
constructor(initialValues: Partial<LimitedResultRequestDto> = {}) {
for (const key in initialValues) {
if (initialValues.hasOwnProperty(key) && initialValues[key] !== undefined) {
if (
Object.prototype.hasOwnProperty.call(initialValues, key) &&
initialValues[key] !== undefined
) {
this[key] = initialValues[key];
}
}
@ -53,7 +56,7 @@ export class EntityDto<TKey = string> {
constructor(initialValues: Partial<EntityDto<TKey>> = {}) {
for (const key in initialValues) {
if (initialValues.hasOwnProperty(key)) {
if (Object.prototype.hasOwnProperty.call(initialValues, key)) {
this[key] = initialValues[key];
}
}
@ -71,7 +74,7 @@ export class CreationAuditedEntityDto<TPrimaryKey = string> extends EntityDto<TP
export class CreationAuditedEntityWithUserDto<
TUserDto,
TPrimaryKey = string
TPrimaryKey = string,
> extends CreationAuditedEntityDto<TPrimaryKey> {
creator?: TUserDto;
@ -93,7 +96,7 @@ export class AuditedEntityDto<TPrimaryKey = string> extends CreationAuditedEntit
export class AuditedEntityWithUserDto<
TUserDto,
TPrimaryKey = string
TPrimaryKey = string,
> extends AuditedEntityDto<TPrimaryKey> {
creator?: TUserDto;
lastModifier?: TUserDto;
@ -115,7 +118,7 @@ export class FullAuditedEntityDto<TPrimaryKey = string> extends AuditedEntityDto
export class FullAuditedEntityWithUserDto<
TUserDto,
TPrimaryKey = string
TPrimaryKey = string,
> extends FullAuditedEntityDto<TPrimaryKey> {
creator?: TUserDto;
lastModifier?: TUserDto;
@ -131,7 +134,7 @@ export class ExtensibleObject {
constructor(initialValues: Partial<ExtensibleObject> = {}) {
for (const key in initialValues) {
if (initialValues.hasOwnProperty(key)) {
if (Object.prototype.hasOwnProperty.call(initialValues, key)) {
this[key] = initialValues[key];
}
}
@ -147,7 +150,7 @@ export class ExtensibleEntityDto<TKey = string> extends ExtensibleObject {
}
export class ExtensibleCreationAuditedEntityDto<
TPrimaryKey = string
TPrimaryKey = string,
> extends ExtensibleEntityDto<TPrimaryKey> {
creationTime: Date | string;
creatorId?: string;
@ -158,7 +161,7 @@ export class ExtensibleCreationAuditedEntityDto<
}
export class ExtensibleAuditedEntityDto<
TPrimaryKey = string
TPrimaryKey = string,
> extends ExtensibleCreationAuditedEntityDto<TPrimaryKey> {
lastModificationTime?: Date | string;
lastModifierId?: string;
@ -170,7 +173,7 @@ export class ExtensibleAuditedEntityDto<
export class ExtensibleAuditedEntityWithUserDto<
TPrimaryKey = string,
TUserDto = any
TUserDto = any,
> extends ExtensibleAuditedEntityDto<TPrimaryKey> {
creator: TUserDto;
lastModifier: TUserDto;
@ -182,7 +185,7 @@ export class ExtensibleAuditedEntityWithUserDto<
export class ExtensibleCreationAuditedEntityWithUserDto<
TPrimaryKey = string,
TUserDto = any
TUserDto = any,
> extends ExtensibleCreationAuditedEntityDto<TPrimaryKey> {
creator: TUserDto;
@ -194,7 +197,7 @@ export class ExtensibleCreationAuditedEntityWithUserDto<
}
export class ExtensibleFullAuditedEntityDto<
TPrimaryKey = string
TPrimaryKey = string,
> extends ExtensibleAuditedEntityDto<TPrimaryKey> {
isDeleted: boolean;
deleterId?: string;
@ -207,7 +210,7 @@ export class ExtensibleFullAuditedEntityDto<
export class ExtensibleFullAuditedEntityWithUserDto<
TPrimaryKey = string,
TUserDto = any
TUserDto = any,
> extends ExtensibleFullAuditedEntityDto<TPrimaryKey> {
creator: TUserDto;
lastModifier: TUserDto;

10
npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/replaceable-components.ts

@ -1,6 +1,6 @@
import { Type, EventEmitter } from '@angular/core';
import { EventEmitter, Type } from '@angular/core';
import { Subject } from 'rxjs';
import { ABP } from './common';
import { Subject, BehaviorSubject } from 'rxjs';
export namespace ReplaceableComponents {
export interface State {
@ -14,7 +14,7 @@ export namespace ReplaceableComponents {
export interface ReplaceableTemplateDirectiveInput<
I,
O extends { [K in keyof O]: EventEmitter<any> | Subject<any> }
O extends { [K in keyof O]: EventEmitter<any> | Subject<any> },
> {
inputs: { -readonly [K in keyof I]: { value: I[K]; twoWay?: boolean } };
outputs: { -readonly [K in keyof O]: (value: ABP.ExtractFromOutput<O[K]>) => void };
@ -23,7 +23,7 @@ export namespace ReplaceableComponents {
export interface ReplaceableTemplateData<
I,
O extends { [K in keyof O]: EventEmitter<any> | Subject<any> }
O extends { [K in keyof O]: EventEmitter<any> | Subject<any> },
> {
inputs: ReplaceableTemplateInputs<I>;
outputs: ReplaceableTemplateOutputs<O>;
@ -35,7 +35,7 @@ export namespace ReplaceableComponents {
};
export type ReplaceableTemplateOutputs<
T extends { [K in keyof T]: EventEmitter<any> | Subject<any> }
T extends { [K in keyof T]: EventEmitter<any> | Subject<any> },
> = {
[K in keyof T]: (value: ABP.ExtractFromOutput<T[K]>) => void;
};

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/models/utility.ts

@ -10,6 +10,7 @@ export type DeepPartial<T> = Partible<T> extends never
type Partible<T> = T extends Primitive | Array<any> | Node
? never
: {
// eslint-disable-next-line @typescript-eslint/ban-types
[K in keyof T]: T[K] extends Function ? never : T[K];
} extends T
? T

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/proxy/volo/abp/asp-net-core/mvc/application-configurations/object-extending/models.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
export interface EntityExtensionDto {
properties: Record<string, ExtensionPropertyDto>;

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/proxy/volo/abp/http/modeling/models.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
export interface ActionApiDescriptionModel {
uniqueName?: string;

8
npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/list.service.ts

@ -82,6 +82,8 @@ export class ListService<QueryParamsType = ABP.PageQueryParams> implements OnDes
private destroy$ = new Subject();
private delay: MonoTypeOperatorFunction<QueryParamsType>;
get isLoading$(): Observable<boolean> {
return this._isLoading$.asObservable();
}
@ -95,8 +97,6 @@ export class ListService<QueryParamsType = ABP.PageQueryParams> implements OnDes
this.next();
};
private delay: MonoTypeOperatorFunction<QueryParamsType>;
constructor(injector: Injector) {
const delay = injector.get(LIST_QUERY_DEBOUNCE_TIME, 300);
this.delay = delay ? debounceTime(delay) : tap();
@ -131,12 +131,12 @@ export class ListService<QueryParamsType = ABP.PageQueryParams> implements OnDes
}
private next() {
this._query$.next(({
this._query$.next({
filter: this._filter || undefined,
maxResultCount: this._maxResultCount,
skipCount: this._page * this._maxResultCount,
sorting: this._sortOrder ? `${this._sortKey} ${this._sortOrder}` : undefined,
} as any) as QueryParamsType);
} as any as QueryParamsType);
}
}

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/routes.service.ts

@ -6,6 +6,7 @@ import { BaseTreeNode, createTreeFromList, TreeNode } from '../utils/tree-utils'
import { ConfigStateService } from './config-state.service';
import { PermissionService } from './permission.service';
// eslint-disable-next-line @typescript-eslint/ban-types
export abstract class AbstractTreeService<T extends object> {
abstract id: string;
abstract parentId: string;

15
npm/ng-packs/nx/ng-packs/packages/core/src/lib/services/track-by.service.ts

@ -1,11 +1,18 @@
import { Injectable, TrackByFunction } from '@angular/core';
import { O } from 'ts-toolbelt';
export const trackBy = <T = any>(key: keyof T): TrackByFunction<T> => (_, item) => item[key];
export const trackBy =
<T = any>(key: keyof T): TrackByFunction<T> =>
(_, item) =>
item[key];
export const trackByDeep = <T = any>(
...keys: T extends object ? O.Paths<T> : never
): TrackByFunction<T> => (_, item) => keys.reduce((acc, key) => acc[key], item);
export const trackByDeep =
<T = any>(
// eslint-disable-next-line @typescript-eslint/ban-types
...keys: T extends object ? O.Paths<T> : never
): TrackByFunction<T> =>
(_, item) =>
keys.reduce((acc, key) => acc[key], item);
@Injectable({
providedIn: 'root',

57
npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/config-state.service.spec.ts

@ -1,4 +1,4 @@
import { CoreTestingModule } from '@abp/ng.core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { createServiceFactory, SpectatorService } from '@ngneat/spectator/jest';
import { Store } from '@ngxs/store';
import {
@ -107,7 +107,7 @@ describe('ConfigState', () => {
const createService = createServiceFactory({
service: ConfigStateService,
imports: [CoreTestingModule.withConfig()],
imports: [HttpClientTestingModule],
providers: [
{ provide: CORE_OPTIONS, useValue: { skipGetAppConfiguration: true } },
{ provide: Store, useValue: {} },
@ -124,35 +124,29 @@ describe('ConfigState', () => {
describe('#getAll', () => {
it('should return CONFIG_STATE_DATA', () => {
expect(configState.getAll()).toEqual(CONFIG_STATE_DATA);
configState
.getAll$()
.subscribe((data) => expect(data).toEqual(CONFIG_STATE_DATA));
configState.getAll$().subscribe(data => expect(data).toEqual(CONFIG_STATE_DATA));
});
});
describe('#getOne', () => {
it('should return one property', () => {
expect(configState.getOne('localization')).toEqual(
CONFIG_STATE_DATA.localization
);
expect(configState.getOne('localization')).toEqual(CONFIG_STATE_DATA.localization);
configState
.getOne$('localization')
.subscribe((localization) =>
expect(localization).toEqual(CONFIG_STATE_DATA.localization)
);
.subscribe(localization => expect(localization).toEqual(CONFIG_STATE_DATA.localization));
});
});
describe('#getDeep', () => {
it('should return deeper', () => {
expect(configState.getDeep('localization.languages')).toEqual(
CONFIG_STATE_DATA.localization.languages
CONFIG_STATE_DATA.localization.languages,
);
configState
.getDeep$('localization.languages')
.subscribe((languages) =>
expect(languages).toEqual(CONFIG_STATE_DATA.localization.languages)
.subscribe(languages =>
expect(languages).toEqual(CONFIG_STATE_DATA.localization.languages),
);
expect(configState.getDeep('test')).toBeFalsy();
@ -162,30 +156,22 @@ describe('ConfigState', () => {
describe('#getFeature', () => {
it('should return a setting', () => {
expect(configState.getFeature('Chat.Enable')).toEqual(
CONFIG_STATE_DATA.features.values['Chat.Enable']
CONFIG_STATE_DATA.features.values['Chat.Enable'],
);
configState
.getFeature$('Chat.Enable')
.subscribe((data) =>
expect(data).toEqual(CONFIG_STATE_DATA.features.values['Chat.Enable'])
);
.subscribe(data => expect(data).toEqual(CONFIG_STATE_DATA.features.values['Chat.Enable']));
});
});
describe('#getSetting', () => {
it('should return a setting', () => {
expect(
configState.getSetting('Abp.Localization.DefaultLanguage')
).toEqual(
CONFIG_STATE_DATA.setting.values['Abp.Localization.DefaultLanguage']
expect(configState.getSetting('Abp.Localization.DefaultLanguage')).toEqual(
CONFIG_STATE_DATA.setting.values['Abp.Localization.DefaultLanguage'],
);
configState
.getSetting$('Abp.Localization.DefaultLanguage')
.subscribe((data) => {
expect(data).toEqual(
CONFIG_STATE_DATA.setting.values['Abp.Localization.DefaultLanguage']
);
});
configState.getSetting$('Abp.Localization.DefaultLanguage').subscribe(data => {
expect(data).toEqual(CONFIG_STATE_DATA.setting.values['Abp.Localization.DefaultLanguage']);
});
});
});
@ -196,14 +182,9 @@ describe('ConfigState', () => {
${'Localization'} | ${{ 'Abp.Localization.DefaultLanguage': 'en' }}
${'X'} | ${{}}
${'localization'} | ${{}}
`(
'should return $expected when keyword is given as $keyword',
({ keyword, expected }) => {
expect(configState.getSettings(keyword)).toEqual(expected);
configState
.getSettings$(keyword)
.subscribe((data) => expect(data).toEqual(expected));
}
);
`('should return $expected when keyword is given as $keyword', ({ keyword, expected }) => {
expect(configState.getSettings(keyword)).toEqual(expected);
configState.getSettings$(keyword).subscribe(data => expect(data).toEqual(expected));
});
});
});

72
npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/permission.guard.spec.ts

@ -1,12 +1,8 @@
import { CoreTestingModule } from '@abp/ng.core/testing';
import { APP_BASE_HREF } from '@angular/common';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Component } from '@angular/core';
import { RouterModule } from '@angular/router';
import {
createServiceFactory,
SpectatorService,
SpyObject,
} from '@ngneat/spectator/jest';
import { createServiceFactory, SpectatorService, SpyObject } from '@ngneat/spectator/jest';
import { Actions, Store } from '@ngxs/store';
import { of } from 'rxjs';
import { RestOccurError } from '../actions';
@ -30,7 +26,7 @@ describe('PermissionGuard', () => {
mocks: [PermissionService, Store],
declarations: [DummyComponent],
imports: [
CoreTestingModule.withConfig(),
HttpClientTestingModule,
RouterModule.forRoot(
[
{
@ -41,7 +37,7 @@ describe('PermissionGuard', () => {
},
},
],
{ relativeLinkResolution: 'legacy' }
{ relativeLinkResolution: 'legacy' },
),
],
providers: [
@ -69,34 +65,30 @@ describe('PermissionGuard', () => {
permissionService = spectator.inject(PermissionService);
});
it('should return true when the grantedPolicy is true', (done) => {
it('should return true when the grantedPolicy is true', done => {
permissionService.getGrantedPolicy$.andReturn(of(true));
const spy = jest.spyOn(store, 'dispatch');
guard
.canActivate({ data: { requiredPolicy: 'test' } } as any, null)
.subscribe((res) => {
expect(res).toBe(true);
expect(spy.mock.calls).toHaveLength(0);
done();
});
guard.canActivate({ data: { requiredPolicy: 'test' } } as any, null).subscribe(res => {
expect(res).toBe(true);
expect(spy.mock.calls).toHaveLength(0);
done();
});
});
it('should return false and dispatch RestOccurError when the grantedPolicy is false', (done) => {
it('should return false and dispatch RestOccurError when the grantedPolicy is false', done => {
permissionService.getGrantedPolicy$.andReturn(of(false));
const spy = jest.spyOn(store, 'dispatch');
guard
.canActivate({ data: { requiredPolicy: 'test' } } as any, null)
.subscribe((res) => {
expect(res).toBe(false);
expect(spy.mock.calls[0][0] instanceof RestOccurError).toBeTruthy();
expect((spy.mock.calls[0][0] as RestOccurError).payload).toEqual({
status: 403,
});
done();
guard.canActivate({ data: { requiredPolicy: 'test' } } as any, null).subscribe(res => {
expect(res).toBe(false);
expect(spy.mock.calls[0][0] instanceof RestOccurError).toBeTruthy();
expect((spy.mock.calls[0][0] as RestOccurError).payload).toEqual({
status: 403,
});
done();
});
});
it('should check the requiredPolicy from RoutesService', (done) => {
it('should check the requiredPolicy from RoutesService', done => {
routes.add([
{
path: '/test',
@ -104,29 +96,23 @@ describe('PermissionGuard', () => {
requiredPolicy: 'TestPolicy',
},
]);
permissionService.getGrantedPolicy$.mockImplementation((policy) =>
of(policy === 'TestPolicy')
);
guard
.canActivate({ data: {} } as any, { url: 'test' } as any)
.subscribe((result) => {
expect(result).toBe(true);
done();
});
permissionService.getGrantedPolicy$.mockImplementation(policy => of(policy === 'TestPolicy'));
guard.canActivate({ data: {} } as any, { url: 'test' } as any).subscribe(result => {
expect(result).toBe(true);
done();
});
});
it('should return Observable<true> if RoutesService does not have requiredPolicy for given URL', (done) => {
it('should return Observable<true> if RoutesService does not have requiredPolicy for given URL', done => {
routes.add([
{
path: '/test',
name: 'Test',
},
]);
guard
.canActivate({ data: {} } as any, { url: 'test' } as any)
.subscribe((result) => {
expect(result).toBe(true);
done();
});
guard.canActivate({ data: {} } as any, { url: 'test' } as any).subscribe(result => {
expect(result).toBe(true);
done();
});
});
});

6
npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/replaceable-template.directive.spec.ts

@ -1,4 +1,4 @@
import { Component, EventEmitter, Inject, Input, OnInit, Optional, Output } from '@angular/core';
import { Component, EventEmitter, Inject, Input, Optional, Output } from '@angular/core';
import { Router } from '@angular/router';
import { createDirectiveFactory, SpectatorDirective } from '@ngneat/spectator/jest';
import { BehaviorSubject } from 'rxjs';
@ -11,7 +11,7 @@ import { ReplaceableComponentsService } from '../services/replaceable-components
template: ' <p>default</p> ',
exportAs: 'abpDefaultComponent',
})
class DefaultComponent implements OnInit {
class DefaultComponent {
@Input()
oneWay;
@ -24,8 +24,6 @@ class DefaultComponent implements OnInit {
@Output()
readonly someOutput = new EventEmitter<string>();
ngOnInit() {}
setTwoWay(value) {
this.twoWay = value;
this.twoWayChange.emit(value);

2
npm/ng-packs/nx/ng-packs/packages/core/src/lib/tests/routes.service.spec.ts

@ -1,7 +1,7 @@
import { Subject } from 'rxjs';
import { take } from 'rxjs/operators';
import { RoutesService } from '../services';
import { DummyInjector, mockActions } from './utils/common.utils';
import { DummyInjector } from './utils/common.utils';
import { mockPermissionService } from './utils/permission-service.spec.utils';
const updateStream$ = new Subject();

40
npm/ng-packs/nx/ng-packs/packages/core/src/lib/utils/rxjs-utils.ts

@ -9,24 +9,24 @@ function isFunction(value) {
/**
* @deprecated no longer working, please use SubscriptionService (https://docs.abp.io/en/abp/latest/UI/Angular/Subscription-Service) instead.
*/
export const takeUntilDestroy = (componentInstance, destroyMethodName = 'ngOnDestroy') => <T>(
source: Observable<T>,
) => {
const originalDestroy = componentInstance[destroyMethodName];
if (isFunction(originalDestroy) === false) {
throw new Error(
`${componentInstance.constructor.name} is using untilDestroyed but doesn't implement ${destroyMethodName}`,
);
}
if (!componentInstance['__takeUntilDestroy']) {
componentInstance['__takeUntilDestroy'] = new Subject();
export const takeUntilDestroy =
(componentInstance, destroyMethodName = 'ngOnDestroy') =>
<T>(source: Observable<T>) => {
const originalDestroy = componentInstance[destroyMethodName];
if (isFunction(originalDestroy) === false) {
throw new Error(
`${componentInstance.constructor.name} is using untilDestroyed but doesn't implement ${destroyMethodName}`,
);
}
if (!componentInstance['__takeUntilDestroy']) {
componentInstance['__takeUntilDestroy'] = new Subject();
componentInstance[destroyMethodName] = function() {
// tslint:disable-next-line: no-unused-expression
isFunction(originalDestroy) && originalDestroy.apply(this, arguments);
componentInstance['__takeUntilDestroy'].next(true);
componentInstance['__takeUntilDestroy'].complete();
};
}
return source.pipe(takeUntil<T>(componentInstance['__takeUntilDestroy']));
};
componentInstance[destroyMethodName] = function () {
// eslint-disable-next-line prefer-rest-params
isFunction(originalDestroy) && originalDestroy.apply(this, arguments);
componentInstance['__takeUntilDestroy'].next(true);
componentInstance['__takeUntilDestroy'].complete();
};
}
return source.pipe(takeUntil<T>(componentInstance['__takeUntilDestroy']));
};

1
npm/ng-packs/nx/ng-packs/packages/core/src/lib/utils/tree-utils.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
export class BaseTreeNode<T extends object> {
children: TreeNode<T>[] = [];
isLeaf = true;

3
npm/ng-packs/nx/ng-packs/packages/feature-management/src/lib/directives/free-text-input.directive.ts

@ -1,4 +1,4 @@
import { Directive, Input, HostBinding } from '@angular/core';
import { Directive, HostBinding, Input } from '@angular/core';
// TODO: improve this type
export interface FreeTextType {
@ -20,6 +20,7 @@ export const INPUT_TYPES = {
})
export class FreeTextInputDirective {
_feature: FreeTextType;
// eslint-disable-next-line @angular-eslint/no-input-rename
@Input('abpFeatureManagementFreeText') set feature(val: FreeTextType) {
this._feature = val;
this.setInputType();

1
npm/ng-packs/nx/ng-packs/packages/feature-management/src/lib/proxy/validation/string-values/models.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
export interface IStringValueType {
name: string;

12
npm/ng-packs/nx/ng-packs/packages/identity/src/lib/proxy/identity/models.ts

@ -1,4 +1,9 @@
import type { ExtensibleEntityDto, ExtensibleFullAuditedEntityDto, ExtensibleObject, PagedAndSortedResultRequestDto } from '@abp/ng.core';
import type {
ExtensibleEntityDto,
ExtensibleFullAuditedEntityDto,
ExtensibleObject,
PagedAndSortedResultRequestDto,
} from '@abp/ng.core';
export interface ChangePasswordInput {
currentPassword: string;
@ -9,9 +14,8 @@ export interface GetIdentityUsersInput extends PagedAndSortedResultRequestDto {
filter: string;
}
// tslint:disable-next-line: no-empty-interface
export interface IdentityRoleCreateDto extends IdentityRoleCreateOrUpdateDtoBase {
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface IdentityRoleCreateDto extends IdentityRoleCreateOrUpdateDtoBase {}
export interface IdentityRoleCreateOrUpdateDtoBase extends ExtensibleObject {
name: string;

15
npm/ng-packs/nx/ng-packs/packages/schematics/.eslintrc.json

@ -27,10 +27,23 @@
]
}
},
{
"files": ["*.ts", "*.tsx"],
"extends": ["plugin:@nrwl/nx/typescript"],
"rules": {
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-empty-function": ["warn"]
}
},
{
"files": ["*.js", "*.jsx"],
"extends": ["plugin:@nrwl/nx/javascript"],
"rules": {}
},
{
"files": ["*.html"],
"extends": ["plugin:@nrwl/nx/angular-template"],
"rules": {}
}
]
}
}

3
npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/api/index.ts

@ -31,7 +31,7 @@ import {
} from '../../utils';
import * as cases from '../../utils/text';
export default function(schema: GenerateProxySchema) {
export default function (schema: GenerateProxySchema) {
const params = removeDefaultPlaceholders(schema);
const moduleName = params.module || 'app';
@ -40,6 +40,7 @@ export default function(schema: GenerateProxySchema) {
const getRootNamespace = createRootNamespaceGetter(params);
const solution = await getRootNamespace(tree);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const target = await resolveProject(tree, params.target!);
const targetPath = buildDefaultPath(target.definition);
const readProxyConfig = createProxyConfigReader(targetPath);

3
npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/proxy-index/index.ts

@ -6,10 +6,11 @@ import {
resolveProject,
} from '../../utils';
export default function(schema: { target?: string }) {
export default function (schema: { target?: string }) {
const params = removeDefaultPlaceholders(schema);
return async (host: Tree, _context: SchematicContext) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const target = await resolveProject(host, params.target!);
const targetPath = buildDefaultPath(target.definition);

3
npm/ng-packs/nx/ng-packs/packages/schematics/src/commands/proxy-remove/index.ts

@ -13,11 +13,12 @@ import {
resolveProject,
} from '../../utils';
export default function(schema: GenerateProxySchema) {
export default function (schema: GenerateProxySchema) {
const params = removeDefaultPlaceholders(schema);
const moduleName = params.module || 'app';
return async (host: Tree, _context: SchematicContext) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const target = await resolveProject(host, params.target!);
const targetPath = buildDefaultPath(target.definition);

2
npm/ng-packs/nx/ng-packs/packages/schematics/src/models/method.ts

@ -3,6 +3,7 @@ import { camel } from '../utils/text';
import { ParameterInBody } from './api-definition';
import { Property } from './model';
import { Omissible } from './util';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const shouldQuote = require('should-quote');
export class Method {
@ -60,6 +61,7 @@ export class Body {
this.body = value;
break;
case eBindingSourceId.Path:
// eslint-disable-next-line no-case-declarations
const regex = new RegExp('{(' + paramName + '|' + camelName + '|' + name + ')}', 'g');
this.url = this.url.replace(regex, '${' + value + '}');
break;

2
npm/ng-packs/nx/ng-packs/packages/schematics/src/models/util.ts

@ -9,7 +9,7 @@ type ExcludeKeys<Type, Excluded> = Exclude<
never
>;
// tslint:disable-next-line: ban-types
// eslint-disable-next-line @typescript-eslint/ban-types
type ExcludeMethods<Type> = Pick<Type, ExcludeKeys<Type, Function>>;
// Options (methods will be omitted, given keys will become optional)

247
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/ast-utils.ts

@ -8,7 +8,6 @@
import * as ts from 'typescript';
import { Change, InsertChange, NoopChange } from './change';
/**
* Add Import `import { symbolName } from fileName` if the import doesn't exit
* already. Assumes fileToEdit can be resolved and accessed.
@ -18,15 +17,21 @@ import { Change, InsertChange, NoopChange } from './change';
* @param isDefault (if true, import follows style for importing default exports)
* @return Change
*/
export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolName: string,
fileName: string, isDefault = false): Change {
export function insertImport(
source: ts.SourceFile,
fileToEdit: string,
symbolName: string,
fileName: string,
isDefault = false,
): Change {
const rootNode = source;
const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);
// get nodes that map to import statements from the file fileName
const relevantImports = allImports.filter(node => {
// StringLiteral of the ImportDeclaration is the import file (fileName in this case).
const importFiles = node.getChildren()
const importFiles = node
.getChildren()
.filter(ts.isStringLiteral)
.map(n => n.text);
@ -64,8 +69,7 @@ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolNa
}
// no such import declaration exists
const useStrict = findNodes(rootNode, ts.isStringLiteral)
.filter((n) => n.text === 'use strict');
const useStrict = findNodes(rootNode, ts.isStringLiteral).filter(n => n.text === 'use strict');
let fallbackPos = 0;
if (useStrict.length > 0) {
fallbackPos = useStrict[0].end;
@ -75,7 +79,8 @@ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolNa
// if there are no imports or 'use strict' statement, insert import at beginning of file
const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;
const separator = insertAtBeginning ? '' : ';\n';
const toInsert = `${separator}import ${open}${symbolName}${close}` +
const toInsert =
`${separator}import ${open}${symbolName}${close}` +
` from '${fileName}'${insertAtBeginning ? ';\n' : ''}`;
return insertAfterLastOccurrence(
@ -87,7 +92,6 @@ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolNa
);
}
/**
* Find all nodes from the AST in the subtree of node of SyntaxKind kind.
* @param node
@ -97,7 +101,12 @@ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolNa
* the last child even when node of kind has been found.
* @return all nodes of kind, or [] if none is found
*/
export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max?: number, recursive?: boolean): ts.Node[];
export function findNodes(
node: ts.Node,
kind: ts.SyntaxKind,
max?: number,
recursive?: boolean,
): ts.Node[];
/**
* Find all nodes from the AST in the subtree that satisfy a type guard.
@ -108,7 +117,12 @@ export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max?: number, recu
* the last child even when node of kind has been found.
* @return all nodes that satisfy the type guard, or [] if none is found
*/
export function findNodes<T extends ts.Node>(node: ts.Node, guard: (node: ts.Node) => node is T, max?: number, recursive?: boolean): T[];
export function findNodes<T extends ts.Node>(
node: ts.Node,
guard: (node: ts.Node) => node is T,
max?: number,
recursive?: boolean,
): T[];
export function findNodes<T extends ts.Node>(
node: ts.Node,
@ -132,7 +146,7 @@ export function findNodes<T extends ts.Node>(
}
if (max > 0 && (recursive || !test(node))) {
for (const child of node.getChildren()) {
findNodes(child, test, max).forEach((node) => {
findNodes(child, test, max).forEach(node => {
if (max > 0) {
arr.push(node);
}
@ -148,7 +162,6 @@ export function findNodes<T extends ts.Node>(
return arr;
}
/**
* Get all the nodes from a source.
* @param sourceFile The source file object.
@ -186,7 +199,6 @@ export function findNode(node: ts.Node, kind: ts.SyntaxKind, text: string): ts.N
return foundNode;
}
/**
* Helper for sorting nodes.
* @return function to sort nodes in increasing order of position in sourceFile
@ -195,7 +207,6 @@ function nodesByPosition(first: ts.Node, second: ts.Node): number {
return first.getStart() - second.getStart();
}
/**
* Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`
* or after the last of occurence of `syntaxKind` if the last occurence is a sub child
@ -209,11 +220,13 @@ function nodesByPosition(first: ts.Node, second: ts.Node): number {
* @return Change instance
* @throw Error if toInsert is first occurence but fall back is not set
*/
export function insertAfterLastOccurrence(nodes: ts.Node[],
toInsert: string,
file: string,
fallbackPos: number,
syntaxKind?: ts.SyntaxKind): Change {
export function insertAfterLastOccurrence(
nodes: ts.Node[],
toInsert: string,
file: string,
fallbackPos: number,
syntaxKind?: ts.SyntaxKind,
): Change {
let lastItem: ts.Node | undefined;
for (const node of nodes) {
if (!lastItem || lastItem.getStart() < node.getStart()) {
@ -231,7 +244,6 @@ export function insertAfterLastOccurrence(nodes: ts.Node[],
return new InsertChange(file, lastItemPosition, toInsert);
}
export function getContentOfKeyLiteral(_source: ts.SourceFile, node: ts.Node): string | null {
if (node.kind == ts.SyntaxKind.Identifier) {
return (node as ts.Identifier).text;
@ -242,9 +254,10 @@ export function getContentOfKeyLiteral(_source: ts.SourceFile, node: ts.Node): s
}
}
function _angularImportsFromNode(node: ts.ImportDeclaration,
_sourceFile: ts.SourceFile): {[name: string]: string} {
function _angularImportsFromNode(
node: ts.ImportDeclaration,
_sourceFile: ts.SourceFile,
): { [name: string]: string } {
const ms = node.moduleSpecifier;
let modulePath: string;
switch (ms.kind) {
@ -275,8 +288,8 @@ function _angularImportsFromNode(node: ts.ImportDeclaration,
const namedImports = nb as ts.NamedImports;
return namedImports.elements
.map((is: ts.ImportSpecifier) => is.propertyName ? is.propertyName.text : is.name.text)
.reduce((acc: {[name: string]: string}, curr: string) => {
.map((is: ts.ImportSpecifier) => (is.propertyName ? is.propertyName.text : is.name.text))
.reduce((acc: { [name: string]: string }, curr: string) => {
acc[curr] = modulePath;
return acc;
@ -291,11 +304,13 @@ function _angularImportsFromNode(node: ts.ImportDeclaration,
}
}
export function getDecoratorMetadata(source: ts.SourceFile, identifier: string,
module: string): ts.Node[] {
export function getDecoratorMetadata(
source: ts.SourceFile,
identifier: string,
module: string,
): ts.Node[] {
const angularImports = findNodes(source, ts.isImportDeclaration)
.map((node) => _angularImportsFromNode(node, source))
.map(node => _angularImportsFromNode(node, source))
.reduce((acc, current) => {
for (const key of Object.keys(current)) {
acc[key] = current[key];
@ -306,8 +321,10 @@ export function getDecoratorMetadata(source: ts.SourceFile, identifier: string,
return getSourceNodes(source)
.filter(node => {
return node.kind == ts.SyntaxKind.Decorator
&& (node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression;
return (
node.kind == ts.SyntaxKind.Decorator &&
(node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression
);
})
.map(node => (node as ts.Decorator).expression as ts.CallExpression)
.filter(expr => {
@ -326,17 +343,18 @@ export function getDecoratorMetadata(source: ts.SourceFile, identifier: string,
const id = paExpr.name.text;
const moduleId = (paExpr.expression as ts.Identifier).text;
return id === identifier && (angularImports[moduleId + '.'] === module);
return id === identifier && angularImports[moduleId + '.'] === module;
}
return false;
})
.filter(expr => expr.arguments[0]
&& expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression)
.filter(
expr => expr.arguments[0] && expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression,
)
.map(expr => expr.arguments[0] as ts.ObjectLiteralExpression);
}
function findClassDeclarationParent(node: ts.Node): ts.ClassDeclaration|undefined {
function findClassDeclarationParent(node: ts.Node): ts.ClassDeclaration | undefined {
if (ts.isClassDeclaration(node)) {
return node;
}
@ -350,7 +368,7 @@ function findClassDeclarationParent(node: ts.Node): ts.ClassDeclaration|undefine
* @param source source file containing one or more @NgModule
* @returns the name of the first @NgModule, or `undefined` if none is found
*/
export function getFirstNgModuleName(source: ts.SourceFile): string|undefined {
export function getFirstNgModuleName(source: ts.SourceFile): string | undefined {
// First, find the @NgModule decorators.
const ngModulesMetadata = getDecoratorMetadata(source, 'NgModule', '@angular/core');
if (ngModulesMetadata.length === 0) {
@ -372,14 +390,17 @@ export function getMetadataField(
node: ts.ObjectLiteralExpression,
metadataField: string,
): ts.ObjectLiteralElement[] {
return node.properties
.filter(ts.isPropertyAssignment)
// Filter out every fields that's not "metadataField". Also handles string literals
// (but not expressions).
.filter(({ name }) => {
return (ts.isIdentifier(name) || ts.isStringLiteral(name))
&& name.getText() === metadataField;
});
return (
node.properties
.filter(ts.isPropertyAssignment)
// Filter out every fields that's not "metadataField". Also handles string literals
// (but not expressions).
.filter(({ name }) => {
return (
(ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.getText() === metadataField
);
})
);
}
export function addSymbolToNgModuleMetadata(
@ -390,7 +411,7 @@ export function addSymbolToNgModuleMetadata(
importPath: string | null = null,
): Change[] {
const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');
let node: any = nodes[0]; // tslint:disable-line:no-any
let node: any = nodes[0]; // tslint:disable-line:no-any
// Find the decorator declaration.
if (!node) {
@ -398,10 +419,7 @@ export function addSymbolToNgModuleMetadata(
}
// Get all the children property assignment of object literals.
const matchingProperties = getMetadataField(
node as ts.ObjectLiteralExpression,
metadataField,
);
const matchingProperties = getMetadataField(node as ts.ObjectLiteralExpression, metadataField);
// Get the last node of the array literal.
if (!matchingProperties) {
@ -459,6 +477,7 @@ export function addSymbolToNgModuleMetadata(
}
if (Array.isArray(node)) {
// eslint-disable-next-line @typescript-eslint/ban-types
const nodeArray = node as {} as Array<ts.Node>;
const symbolsArray = nodeArray.map(node => node.getText());
if (symbolsArray.includes(symbolName)) {
@ -513,47 +532,66 @@ export function addSymbolToNgModuleMetadata(
* Custom function to insert a declaration (component, pipe, directive)
* into NgModule declarations. It also imports the component.
*/
export function addDeclarationToModule(source: ts.SourceFile,
modulePath: string, classifiedName: string,
importPath: string): Change[] {
export function addDeclarationToModule(
source: ts.SourceFile,
modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(
source, modulePath, 'declarations', classifiedName, importPath);
source,
modulePath,
'declarations',
classifiedName,
importPath,
);
}
/**
* Custom function to insert an NgModule into NgModule imports. It also imports the module.
*/
export function addImportToModule(source: ts.SourceFile,
modulePath: string, classifiedName: string,
importPath: string): Change[] {
export function addImportToModule(
source: ts.SourceFile,
modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(source, modulePath, 'imports', classifiedName, importPath);
}
/**
* Custom function to insert a provider into NgModule. It also imports it.
*/
export function addProviderToModule(source: ts.SourceFile,
modulePath: string, classifiedName: string,
importPath: string): Change[] {
export function addProviderToModule(
source: ts.SourceFile,
modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(source, modulePath, 'providers', classifiedName, importPath);
}
/**
* Custom function to insert an export into NgModule. It also imports it.
*/
export function addExportToModule(source: ts.SourceFile,
modulePath: string, classifiedName: string,
importPath: string): Change[] {
export function addExportToModule(
source: ts.SourceFile,
modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(source, modulePath, 'exports', classifiedName, importPath);
}
/**
* Custom function to insert an export into NgModule. It also imports it.
*/
export function addBootstrapToModule(source: ts.SourceFile,
modulePath: string, classifiedName: string,
importPath: string): Change[] {
export function addBootstrapToModule(
source: ts.SourceFile,
modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(source, modulePath, 'bootstrap', classifiedName, importPath);
}
@ -561,33 +599,41 @@ export function addBootstrapToModule(source: ts.SourceFile,
* Custom function to insert an entryComponent into NgModule. It also imports it.
* @deprecated - Since version 9.0.0 with Ivy, entryComponents is no longer necessary.
*/
export function addEntryComponentToModule(source: ts.SourceFile,
modulePath: string, classifiedName: string,
importPath: string): Change[] {
export function addEntryComponentToModule(
source: ts.SourceFile,
modulePath: string,
classifiedName: string,
importPath: string,
): Change[] {
return addSymbolToNgModuleMetadata(
source, modulePath,
'entryComponents', classifiedName, importPath,
source,
modulePath,
'entryComponents',
classifiedName,
importPath,
);
}
/**
* Determine if an import already exists.
*/
export function isImported(source: ts.SourceFile,
classifiedName: string,
importPath: string): boolean {
export function isImported(
source: ts.SourceFile,
classifiedName: string,
importPath: string,
): boolean {
const allNodes = getSourceNodes(source);
const matchingNodes = allNodes
.filter(ts.isImportDeclaration)
.filter(
(imp) => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath,
imp => ts.isStringLiteral(imp.moduleSpecifier) && imp.moduleSpecifier.text === importPath,
)
.filter((imp) => {
.filter(imp => {
if (!imp.importClause) {
return false;
}
const nodes = findNodes(imp.importClause, ts.isImportSpecifier).filter(
(n) => n.getText() === classifiedName,
n => n.getText() === classifiedName,
);
return nodes.length > 0;
@ -611,11 +657,11 @@ export function getEnvironmentExportName(source: ts.SourceFile): string | null {
allNodes
.filter(ts.isImportDeclaration)
.filter(
(declaration) =>
declaration =>
declaration.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral &&
declaration.importClause !== undefined,
)
.map((declaration) =>
.map(declaration =>
// If `importClause` property is defined then the first
// child will be `NamedImports` object (or `namedBindings`).
(declaration.importClause as ts.ImportClause).getChildAt(0),
@ -623,8 +669,8 @@ export function getEnvironmentExportName(source: ts.SourceFile): string | null {
// Find those `NamedImports` object that contains `environment` keyword
// in its text. E.g. `{ environment as env }`.
.filter(ts.isNamedImports)
.filter((namedImports) => namedImports.getText().includes('environment'))
.forEach((namedImports) => {
.filter(namedImports => namedImports.getText().includes('environment'))
.forEach(namedImports => {
for (const specifier of namedImports.elements) {
// `propertyName` is defined if the specifier
// has an aliased import.
@ -682,8 +728,7 @@ export function addRouteDeclarationToModule(
if (!scopeConfigMethodArgs.length) {
const { line } = source.getLineAndCharacterOfPosition(routerModuleExpr.getStart());
throw new Error(
`The router module method doesn't have arguments ` +
`at line ${line} in ${fileToAdd}`,
`The router module method doesn't have arguments ` + `at line ${line} in ${fileToAdd}`,
);
}
@ -698,22 +743,24 @@ export function addRouteDeclarationToModule(
const routesVarName = routesArg.getText();
let routesVar;
if (routesArg.kind === ts.SyntaxKind.Identifier) {
routesVar = source.statements
.filter(ts.isVariableStatement)
.find((v) => {
return v.declarationList.declarations[0].name.getText() === routesVarName;
});
routesVar = source.statements.filter(ts.isVariableStatement).find(v => {
return v.declarationList.declarations[0].name.getText() === routesVarName;
});
}
if (!routesVar) {
const { line } = source.getLineAndCharacterOfPosition(routesArg.getStart());
throw new Error(
`No route declaration array was found that corresponds ` +
`to router module at line ${line} in ${fileToAdd}`,
`to router module at line ${line} in ${fileToAdd}`,
);
}
routesArr = findNodes(routesVar, ts.SyntaxKind.ArrayLiteralExpression, 1)[0] as ts.ArrayLiteralExpression;
routesArr = findNodes(
routesVar,
ts.SyntaxKind.ArrayLiteralExpression,
1,
)[0] as ts.ArrayLiteralExpression;
}
const occurrencesCount = routesArr.elements.length;
@ -724,16 +771,16 @@ export function addRouteDeclarationToModule(
if (occurrencesCount > 0) {
const lastRouteLiteral = [...routesArr.elements].pop() as ts.Expression;
const lastRouteIsWildcard = ts.isObjectLiteralExpression(lastRouteLiteral)
&& lastRouteLiteral
.properties
.some(n => (
ts.isPropertyAssignment(n)
&& ts.isIdentifier(n.name)
&& n.name.text === 'path'
&& ts.isStringLiteral(n.initializer)
&& n.initializer.text === '**'
));
const lastRouteIsWildcard =
ts.isObjectLiteralExpression(lastRouteLiteral) &&
lastRouteLiteral.properties.some(
n =>
ts.isPropertyAssignment(n) &&
ts.isIdentifier(n.name) &&
n.name.text === 'path' &&
ts.isStringLiteral(n.initializer) &&
n.initializer.text === '**',
);
const indentation = text.match(/\r?\n(\r?)\s*/) || [];
const routeText = `${indentation[0] || ' '}${routeLiteral}`;

571
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/config.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
/**
* @license
* Copyright Google Inc. All Rights Reserved.
@ -31,20 +32,23 @@ export interface AppConfig {
/**
* List of application assets.
*/
assets?: (string | {
/**
* The pattern to match.
*/
glob?: string;
/**
* The dir to search within.
*/
input?: string;
/**
* The output path (relative to the outDir).
*/
output?: string;
})[];
assets?: (
| string
| {
/**
* The pattern to match.
*/
glob?: string;
/**
* The dir to search within.
*/
input?: string;
/**
* The output path (relative to the outDir).
*/
output?: string;
}
)[];
/**
* URL where files will be deployed.
*/
@ -56,7 +60,7 @@ export interface AppConfig {
/**
* The runtime platform of the app.
*/
platform?: ('browser' | 'server');
platform?: 'browser' | 'server';
/**
* The name of the start HTML file.
*/
@ -92,26 +96,32 @@ export interface AppConfig {
/**
* Global styles to be included in the build.
*/
styles?: (string | {
input?: string;
[name: string]: any; // tslint:disable-line:no-any
})[];
styles?: (
| string
| {
input?: string;
[name: string]: any; // tslint:disable-line:no-any
}
)[];
/**
* Options to pass to style preprocessors
*/
stylePreprocessorOptions?: {
/**
* Paths to include. Paths will be resolved to project root.
*/
includePaths?: string[];
/**
* Paths to include. Paths will be resolved to project root.
*/
includePaths?: string[];
};
/**
* Global scripts to be included in the build.
*/
scripts?: (string | {
input: string;
[name: string]: any; // tslint:disable-line:no-any
})[];
scripts?: (
| string
| {
input: string;
[name: string]: any; // tslint:disable-line:no-any
}
)[];
/**
* Source file for environment config.
*/
@ -120,7 +130,7 @@ export interface AppConfig {
* Name and corresponding file for environment config.
*/
environments?: {
[name: string]: any; // tslint:disable-line:no-any
[name: string]: any; // tslint:disable-line:no-any
};
appShell?: {
app: string;
@ -130,7 +140,7 @@ export interface AppConfig {
/**
* The type of budget
*/
type?: ('bundle' | 'initial' | 'allScript' | 'all' | 'anyScript' | 'any' | 'anyComponentStyle');
type?: 'bundle' | 'initial' | 'allScript' | 'all' | 'anyScript' | 'any' | 'anyComponentStyle';
/**
* The name of the bundle
*/
@ -172,14 +182,14 @@ export interface CliConfig {
* The global configuration of the project.
*/
project?: {
/**
* The name of the project.
*/
name?: string;
/**
* Whether or not this project was ejected.
*/
ejected?: boolean;
/**
* The name of the project.
*/
name?: string;
/**
* Whether or not this project was ejected.
*/
ejected?: boolean;
};
/**
* Properties of the different applications in this project.
@ -189,278 +199,278 @@ export interface CliConfig {
* Configuration for end-to-end tests.
*/
e2e?: {
protractor?: {
/**
* Path to the config file.
*/
config?: string;
};
protractor?: {
/**
* Path to the config file.
*/
config?: string;
};
};
/**
* Properties to be passed to TSLint.
*/
lint?: {
/**
* File glob(s) to lint.
*/
files?: (string | string[]);
/**
* Location of the tsconfig.json project file.
* Will also use as files to lint if 'files' property not present.
*/
project: string;
/**
* Location of the tslint.json configuration.
*/
tslintConfig?: string;
/**
* File glob(s) to ignore.
*/
exclude?: (string | string[]);
/**
* File glob(s) to lint.
*/
files?: string | string[];
/**
* Location of the tsconfig.json project file.
* Will also use as files to lint if 'files' property not present.
*/
project: string;
/**
* Location of the tslint.json configuration.
*/
tslintConfig?: string;
/**
* File glob(s) to ignore.
*/
exclude?: string | string[];
}[];
/**
* Configuration for unit tests.
*/
test?: {
karma?: {
/**
* Path to the karma config file.
*/
config?: string;
};
codeCoverage?: {
/**
* Globs to exclude from code coverage.
*/
exclude?: string[];
};
karma?: {
/**
* Path to the karma config file.
*/
config?: string;
};
codeCoverage?: {
/**
* Globs to exclude from code coverage.
*/
exclude?: string[];
};
};
/**
* Specify the default values for generating.
*/
defaults?: {
/**
* The file extension to be used for style files.
*/
styleExt?: string;
/**
* How often to check for file updates.
*/
poll?: number;
/**
* Use lint to fix files after generation
*/
lintFix?: boolean;
/**
* Options for generating a class.
*/
class?: {
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a component.
*/
component?: {
/**
* The file extension to be used for style files.
* Flag to indicate if a directory is created.
*/
styleExt?: string;
flat?: boolean;
/**
* How often to check for file updates.
* Specifies if a spec file is generated.
*/
spec?: boolean;
/**
* Specifies if the style will be in the ts file.
*/
inlineStyle?: boolean;
/**
* Specifies if the template will be in the ts file.
*/
inlineTemplate?: boolean;
/**
* Specifies the view encapsulation strategy.
*/
viewEncapsulation?: 'Emulated' | 'Native' | 'None';
/**
* Specifies the change detection strategy.
*/
changeDetection?: 'Default' | 'OnPush';
};
/**
* Options for generating a directive.
*/
directive?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a guard.
*/
guard?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating an interface.
*/
interface?: {
/**
* Prefix to apply to interface names. (i.e. I)
*/
prefix?: string;
};
/**
* Options for generating a module.
*/
module?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a pipe.
*/
pipe?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a service.
*/
service?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Properties to be passed to the build command.
*/
build?: {
/**
* Output sourcemaps.
*/
sourcemaps?: boolean;
/**
* Base url for the application being built.
*/
baseHref?: string;
/**
* The ssl key used by the server.
*/
progress?: boolean;
/**
* Enable and define the file watching poll time period (milliseconds).
*/
poll?: number;
/**
* Use lint to fix files after generation
*/
lintFix?: boolean;
/**
* Options for generating a class.
*/
class?: {
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a component.
*/
component?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
/**
* Specifies if the style will be in the ts file.
*/
inlineStyle?: boolean;
/**
* Specifies if the template will be in the ts file.
*/
inlineTemplate?: boolean;
/**
* Specifies the view encapsulation strategy.
*/
viewEncapsulation?: ('Emulated' | 'Native' | 'None');
/**
* Specifies the change detection strategy.
*/
changeDetection?: ('Default' | 'OnPush');
};
/**
* Options for generating a directive.
*/
directive?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a guard.
*/
guard?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating an interface.
*/
interface?: {
/**
* Prefix to apply to interface names. (i.e. I)
*/
prefix?: string;
};
/**
* Options for generating a module.
*/
module?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a pipe.
*/
pipe?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Options for generating a service.
*/
service?: {
/**
* Flag to indicate if a directory is created.
*/
flat?: boolean;
/**
* Specifies if a spec file is generated.
*/
spec?: boolean;
};
/**
* Properties to be passed to the build command.
*/
build?: {
/**
* Output sourcemaps.
*/
sourcemaps?: boolean;
/**
* Base url for the application being built.
*/
baseHref?: string;
/**
* The ssl key used by the server.
*/
progress?: boolean;
/**
* Enable and define the file watching poll time period (milliseconds).
*/
poll?: number;
/**
* Delete output path before build.
*/
deleteOutputPath?: boolean;
/**
* Do not use the real path when resolving modules.
*/
preserveSymlinks?: boolean;
/**
* Show circular dependency warnings on builds.
*/
showCircularDependencies?: boolean;
/**
* Use a separate bundle containing code used across multiple bundles.
*/
commonChunk?: boolean;
/**
* Use file name for lazy loaded chunks.
*/
namedChunks?: boolean;
};
/**
* Properties to be passed to the serve command.
*/
serve?: {
/**
* The port the application will be served on.
*/
port?: number;
/**
* The host the application will be served on.
*/
host?: string;
/**
* Enables ssl for the application.
*/
ssl?: boolean;
/**
* The ssl key used by the server.
*/
sslKey?: string;
/**
* The ssl certificate used by the server.
*/
sslCert?: string;
/**
* Proxy configuration file.
*/
proxyConfig?: string;
};
/**
* Properties about schematics.
*/
schematics?: {
/**
* The schematics collection to use.
*/
collection?: string;
/**
* The new app schematic.
*/
newApp?: string;
};
* Delete output path before build.
*/
deleteOutputPath?: boolean;
/**
* Do not use the real path when resolving modules.
*/
preserveSymlinks?: boolean;
/**
* Show circular dependency warnings on builds.
*/
showCircularDependencies?: boolean;
/**
* Use a separate bundle containing code used across multiple bundles.
*/
commonChunk?: boolean;
/**
* Use file name for lazy loaded chunks.
*/
namedChunks?: boolean;
};
/**
* Properties to be passed to the serve command.
*/
serve?: {
/**
* The port the application will be served on.
*/
port?: number;
/**
* The host the application will be served on.
*/
host?: string;
/**
* Enables ssl for the application.
*/
ssl?: boolean;
/**
* The ssl key used by the server.
*/
sslKey?: string;
/**
* The ssl certificate used by the server.
*/
sslCert?: string;
/**
* Proxy configuration file.
*/
proxyConfig?: string;
};
/**
* Properties about schematics.
*/
schematics?: {
/**
* The schematics collection to use.
*/
collection?: string;
/**
* The new app schematic.
*/
newApp?: string;
};
};
/**
* Specify which package manager tool to use.
*/
packageManager?: ('npm' | 'cnpm' | 'yarn' | 'default');
packageManager?: 'npm' | 'cnpm' | 'yarn' | 'default';
/**
* Allow people to disable console warnings.
*/
warnings?: {
versionMismatch?: boolean;
versionMismatch?: boolean;
};
}
export function getWorkspacePath(host: Tree): string {
const possibleFiles = [ '/angular.json', '/.angular.json' ];
const possibleFiles = ['/angular.json', '/.angular.json'];
const path = possibleFiles.filter(path => host.exists(path))[0];
return path;
@ -483,7 +493,6 @@ export function addProjectToWorkspace<TProjectType extends ProjectType = Project
project: WorkspaceProject<TProjectType>,
): Rule {
return (_host: Tree, _context: SchematicContext) => {
if (workspace.projects[name]) {
throw new Error(`Project '${name}' already exists in workspace.`);
}
@ -501,9 +510,9 @@ export function addProjectToWorkspace<TProjectType extends ProjectType = Project
}
export function updateWorkspaceSchema(workspace: WorkspaceSchema): Rule {
return (host: Tree, _context: SchematicContext) => {
host.overwrite(getWorkspacePath(host), JSON.stringify(workspace, null, 2));
};
return (host: Tree, _context: SchematicContext) => {
host.overwrite(getWorkspacePath(host), JSON.stringify(workspace, null, 2));
};
}
export const configPath = '/.angular-cli.json';
@ -528,5 +537,5 @@ export function getAppFromConfig(config: CliConfig, appIndexOrName: string): App
return config.apps[parseInt(appIndexOrName)];
}
return config.apps.filter((app) => app.name === appIndexOrName)[0];
return config.apps.filter(app => app.name === appIndexOrName)[0];
}

58
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/find-module.ts

@ -5,23 +5,16 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
dirname,
join,
normalize, NormalizedRoot,
Path,
relative
} from '@angular-devkit/core';
import { dirname, join, normalize, NormalizedRoot, Path, relative } from '@angular-devkit/core';
import { DirEntry, Tree } from '@angular-devkit/schematics';
export interface ModuleOptions {
project?: string; // added this
project?: string; // added this
module?: string;
name: string;
flat?: boolean;
path?: string;
route?: string; // added this
route?: string; // added this
selector?: string; // added this
skipImport?: boolean;
moduleExt?: string;
@ -35,7 +28,7 @@ export const ROUTING_MODULE_EXT = '-routing.module.ts';
* Find the module referred by a set of options passed to the schematics.
*/
export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path | undefined {
if (options.hasOwnProperty('skipImport') && options.skipImport) {
if (Object.prototype.hasOwnProperty.call(options, 'skipImport') && options.skipImport) {
return undefined;
}
@ -51,9 +44,7 @@ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path
const componentPath = normalize(`/${options.path}/${options.name}`);
const moduleBaseName = normalize(modulePath).split('/').pop();
const candidateSet = new Set<Path>([
normalize(options.path || '/'),
]);
const candidateSet = new Set<Path>([normalize(options.path || '/')]);
for (let dir = modulePath; dir != NormalizedRoot; dir = dirname(dir)) {
candidateSet.add(dir);
@ -64,11 +55,9 @@ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path
const candidatesDirs = [...candidateSet].sort((a, b) => b.length - a.length);
for (const c of candidatesDirs) {
const candidateFiles = [
'',
`${moduleBaseName}.ts`,
`${moduleBaseName}${moduleExt}`,
].map(x => join(c, x));
const candidateFiles = ['', `${moduleBaseName}.ts`, `${moduleBaseName}${moduleExt}`].map(x =>
join(c, x),
);
for (const sc of candidateFiles) {
if (host.exists(sc)) {
@ -78,8 +67,8 @@ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path
}
throw new Error(
`Specified module '${options.module}' does not exist.\n`
+ `Looked in the following directories:\n ${candidatesDirs.join('\n ')}`,
`Specified module '${options.module}' does not exist.\n` +
`Looked in the following directories:\n ${candidatesDirs.join('\n ')}`,
);
}
}
@ -87,9 +76,12 @@ export function findModuleFromOptions(host: Tree, options: ModuleOptions): Path
/**
* Function to find the "closest" module to a generated file's path.
*/
export function findModule(host: Tree, generateDir: string,
moduleExt = MODULE_EXT, routingModuleExt = ROUTING_MODULE_EXT): Path {
export function findModule(
host: Tree,
generateDir: string,
moduleExt = MODULE_EXT,
routingModuleExt = ROUTING_MODULE_EXT,
): Path {
let dir: DirEntry | null = host.getDir('/' + generateDir);
let foundRoutingModule = false;
@ -103,16 +95,18 @@ export function findModule(host: Tree, generateDir: string,
return join(dir.path, filteredMatches[0]);
} else if (filteredMatches.length > 1) {
throw new Error(
'More than one module matches. Use the skip-import option to skip importing ' +
'the component into the closest module or use the module option to specify a module.');
'More than one module matches. Use the skip-import option to skip importing ' +
'the component into the closest module or use the module option to specify a module.',
);
}
dir = dir.parent;
}
const errorMsg = foundRoutingModule ? 'Could not find a non Routing NgModule.'
+ `\nModules with suffix '${routingModuleExt}' are strictly reserved for routing.`
+ '\nUse the skip-import option to skip importing in NgModule.'
const errorMsg = foundRoutingModule
? 'Could not find a non Routing NgModule.' +
`\nModules with suffix '${routingModuleExt}' are strictly reserved for routing.` +
'\nUse the skip-import option to skip importing in NgModule.'
: 'Could not find an NgModule. Use the skip-import option to skip importing in NgModule.';
throw new Error(errorMsg);
@ -133,8 +127,10 @@ export function buildRelativePath(from: string, to: string): string {
fromParts.pop();
const toFileName = toParts.pop();
const relativePath = relative(normalize(fromParts.join('/') || '/'),
normalize(toParts.join('/') || '/'));
const relativePath = relative(
normalize(fromParts.join('/') || '/'),
normalize(toParts.join('/') || '/'),
);
let pathPrefix = '';
// Set the path prefix for same dir or child dir, parent dir starts with `..`

1
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/angular/workspace-models.ts

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/ban-types */
/**
* @license
* Copyright Google Inc. All Rights Reserved.

4
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/enum.ts

@ -3,6 +3,7 @@ import { Exception } from '../enums';
import { Type } from '../models';
import { interpolate } from './common';
import { parseNamespace } from './namespace';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const shouldQuote = require('should-quote');
export interface EnumGeneratorParams {
@ -33,13 +34,14 @@ export function createImportRefToEnumMapper({ solution, types }: EnumGeneratorPa
throw new SchematicsException(interpolate(Exception.NoTypeDefinition, ref));
const namespace = parseNamespace(solution, ref);
const members = enumNames!.map((key, i) => ({
const members = enumNames.map((key, i) => ({
key: shouldQuote(key) ? `'${key}'` : key,
value: enumValues[i],
}));
return {
namespace,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
name: ref.split('.').pop()!,
members,
};

2
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/generics.ts

@ -58,9 +58,9 @@ export class GenericsCollector {
}
export function generateRefWithPlaceholders(sourceType: string) {
// eslint-disable-next-line prefer-const
let { identifier, generics } = extractGenerics(sourceType);
identifier = identifier;
generics = generics.map((_, i) => `T${i}`);
return generics.length ? `${identifier}<${generics}>` : identifier;

1
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/model.ts

@ -17,6 +17,7 @@ import {
extendsSelf,
removeTypeModifiers,
} from './type';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const shouldQuote = require('should-quote');
export interface ModelGeneratorParams {

1
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/source.ts

@ -1,3 +1,4 @@
/* eslint-disable no-empty */
import { SchematicsException, Tree } from '@angular-devkit/schematics';
import got from 'got';
import {

3
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/text.ts

@ -1,3 +1,4 @@
/* eslint-disable no-useless-escape */
import { strings } from '@angular-devkit/core';
export const lower = (text: string) => text.toLowerCase();
@ -11,7 +12,7 @@ export const dir = (text: string) =>
strings.dasherize(text.replace(/\./g, '/').replace(/\/\//g, '/'));
export const quote = (value: number | string) =>
typeof value === 'string' ? `'${value.replace(/'/g, '\\\'')}'` : value;
typeof value === 'string' ? `'${value.replace(/'/g, "\\'")}'` : value;
function _(text: string): string {
return text.replace(/\./g, '_');

1
npm/ng-packs/nx/ng-packs/packages/schematics/src/utils/workspace.ts

@ -1,3 +1,4 @@
/* eslint-disable no-empty */
import { strings, workspaces } from '@angular-devkit/core';
import { SchematicsException, Tree } from '@angular-devkit/schematics';
import { Exception } from '../enums';

11
npm/ng-packs/nx/ng-packs/packages/tenant-management/src/lib/proxy/models.ts

@ -1,4 +1,8 @@
import type { ExtensibleEntityDto, ExtensibleObject, PagedAndSortedResultRequestDto } from '@abp/ng.core';
import type {
ExtensibleEntityDto,
ExtensibleObject,
PagedAndSortedResultRequestDto,
} from '@abp/ng.core';
export interface GetTenantsInput extends PagedAndSortedResultRequestDto {
filter: string;
@ -17,6 +21,5 @@ export interface TenantDto extends ExtensibleEntityDto<string> {
name: string;
}
// tslint:disable-next-line: no-empty-interface
export interface TenantUpdateDto extends TenantCreateOrUpdateDtoBase {
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface TenantUpdateDto extends TenantCreateOrUpdateDtoBase {}

6
npm/ng-packs/nx/ng-packs/packages/theme-basic/src/lib/components/account-layout/auth-wrapper/auth-wrapper.component.ts

@ -1,13 +1,11 @@
import { Component, OnInit } from '@angular/core';
import { AuthWrapperService } from '@abp/ng.account.core';
import { Component } from '@angular/core';
@Component({
selector: 'abp-auth-wrapper',
templateUrl: './auth-wrapper.component.html',
providers: [AuthWrapperService],
})
export class AuthWrapperComponent implements OnInit {
export class AuthWrapperComponent {
constructor(public service: AuthWrapperService) {}
ngOnInit(): void {}
}

6
npm/ng-packs/nx/ng-packs/packages/theme-basic/src/lib/components/account-layout/tenant-box/tenant-box.component.ts

@ -1,13 +1,11 @@
import { Component, OnInit } from '@angular/core';
import { TenantBoxService } from '@abp/ng.account.core';
import { Component } from '@angular/core';
@Component({
selector: 'abp-tenant-box',
templateUrl: './tenant-box.component.html',
providers: [TenantBoxService],
})
export class TenantBoxComponent implements OnInit {
export class TenantBoxComponent {
constructor(public service: TenantBoxService) {}
ngOnInit(): void {}
}

11
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/button/button.component.ts

@ -1,14 +1,15 @@
/* eslint-disable @angular-eslint/no-output-native */
import { ABP } from '@abp/ng.core';
import {
Component,
ElementRef,
EventEmitter,
Input,
OnInit,
Output,
ViewChild,
ElementRef,
Renderer2,
OnInit,
ViewChild,
} from '@angular/core';
import { ABP } from '@abp/ng.core';
@Component({
selector: 'abp-button',
@ -49,13 +50,11 @@ export class ButtonComponent implements OnInit {
@Input()
attributes: ABP.Dictionary<string>;
// tslint:disable
@Output() readonly click = new EventEmitter<MouseEvent>();
@Output() readonly focus = new EventEmitter<FocusEvent>();
@Output() readonly blur = new EventEmitter<FocusEvent>();
// tslint:enable
@Output() readonly abpClick = new EventEmitter<MouseEvent>();

4
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/chart/chart.component.ts

@ -1,12 +1,12 @@
import {
AfterViewInit,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Output,
ChangeDetectorRef,
} from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { chartJsLoaded$ } from '../../utils/widget-utils';
@ -29,7 +29,7 @@ export class ChartComponent implements AfterViewInit, OnDestroy {
@Input() responsive = true;
// tslint:disable-next-line: no-output-on-prefix
// eslint-disable-next-line @angular-eslint/no-output-on-prefix
@Output() readonly onDataSelect: EventEmitter<any> = new EventEmitter();
@Output() readonly initialized = new BehaviorSubject(this);

8
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/loading/loading.component.ts

@ -1,4 +1,4 @@
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'abp-loading',
@ -33,8 +33,4 @@ import { Component, OnInit, ViewEncapsulation } from '@angular/core';
`,
],
})
export class LoadingComponent implements OnInit {
constructor() {}
ngOnInit() {}
}
export class LoadingComponent {}

6
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/components/table-empty-message/table-empty-message.component.ts

@ -1,13 +1,13 @@
import { Component, OnInit, Input } from '@angular/core';
import { Component, Input } from '@angular/core';
@Component({
// tslint:disable-next-line: component-selector
// eslint-disable-next-line @angular-eslint/component-selector
selector: '[abp-table-empty-message]',
template: `
<td class="text-center" [attr.colspan]="colspan">
{{ emptyMessage | abpLocalization }}
</td>
`
`,
})
export class TableEmptyMessageComponent {
@Input()

2
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/directives/ngx-datatable-default.directive.ts

@ -5,7 +5,7 @@ import { fromEvent, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
@Directive({
// tslint:disable-next-line
// eslint-disable-next-line @angular-eslint/directive-selector
selector: 'ngx-datatable[default]',
exportAs: 'ngxDatatableDefault',
})

2
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/directives/ngx-datatable-list.directive.ts

@ -19,7 +19,7 @@ import {
} from '../tokens/ngx-datatable-messages.token';
@Directive({
// tslint:disable-next-line
// eslint-disable-next-line @angular-eslint/directive-selector
selector: 'ngx-datatable[list]',
exportAs: 'ngxDatatableList',
})

63
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts

@ -1,9 +1,4 @@
import {
AuthService,
LocalizationParam,
RestOccurError,
RouterEvents,
} from '@abp/ng.core';
import { AuthService, LocalizationParam, RestOccurError, RouterEvents } from '@abp/ng.core';
import { HttpErrorResponse } from '@angular/common/http';
import {
ApplicationRef,
@ -32,8 +27,7 @@ export const DEFAULT_ERROR_MESSAGES = {
},
defaultError401: {
title: 'You are not authenticated!',
details:
'You should be authenticated (sign in) in order to perform this operation.',
details: 'You should be authenticated (sign in) in order to perform this operation.',
},
defaultError403: {
title: 'You are not authorized!',
@ -76,9 +70,8 @@ export const DEFAULT_ERROR_LOCALIZATIONS = {
export class ErrorHandler {
componentRef: ComponentRef<HttpErrorWrapperComponent>;
protected httpErrorHandler = this.injector.get(
HTTP_ERROR_HANDLER,
(_, err: HttpErrorResponse) => throwError(err)
protected httpErrorHandler = this.injector.get(HTTP_ERROR_HANDLER, (_, err: HttpErrorResponse) =>
throwError(err),
);
constructor(
@ -88,7 +81,7 @@ export class ErrorHandler {
protected cfRes: ComponentFactoryResolver,
protected rendererFactory: RendererFactory2,
protected injector: Injector,
@Inject('HTTP_ERROR_CONFIG') protected httpErrorConfig: HttpErrorConfig
@Inject('HTTP_ERROR_CONFIG') protected httpErrorConfig: HttpErrorConfig,
) {
this.listenToRestError();
this.listenToRouterError();
@ -116,21 +109,21 @@ export class ErrorHandler {
this.actions
.pipe(
ofActionSuccessful(RestOccurError),
map((action) => action.payload),
map(action => action.payload),
filter(this.filterRestErrors),
switchMap(this.executeErrorHandler)
switchMap(this.executeErrorHandler),
)
.subscribe();
}
private executeErrorHandler = (error) => {
private executeErrorHandler = error => {
const returnValue = this.httpErrorHandler(this.injector, error);
return (returnValue instanceof Observable ? returnValue : of(null)).pipe(
catchError((err) => {
catchError(err => {
this.handleError(err);
return of(null);
})
}),
);
};
@ -140,10 +133,7 @@ export class ErrorHandler {
defaultValue: DEFAULT_ERROR_MESSAGES.defaultError.title,
};
if (
err instanceof HttpErrorResponse &&
err.headers.get('_AbpErrorFormat')
) {
if (err instanceof HttpErrorResponse && err.headers.get('_AbpErrorFormat')) {
const confirmation$ = this.showError(null, null, body);
if (err.status === 401) {
@ -164,7 +154,7 @@ export class ErrorHandler {
{
key: DEFAULT_ERROR_LOCALIZATIONS.defaultError401.details,
defaultValue: DEFAULT_ERROR_MESSAGES.defaultError401.details,
}
},
).subscribe(() => this.navigateToLogin());
break;
case 403:
@ -191,7 +181,7 @@ export class ErrorHandler {
{
key: DEFAULT_ERROR_LOCALIZATIONS.defaultError404.title,
defaultValue: DEFAULT_ERROR_MESSAGES.defaultError404.title,
}
},
);
break;
case 500:
@ -228,7 +218,7 @@ export class ErrorHandler {
{
key: DEFAULT_ERROR_LOCALIZATIONS.defaultError.title,
defaultValue: DEFAULT_ERROR_MESSAGES.defaultError.title,
}
},
);
break;
}
@ -258,7 +248,7 @@ export class ErrorHandler {
protected showError(
message?: LocalizationParam,
title?: LocalizationParam,
body?: any
body?: any,
): Observable<Confirmation.Status> {
if (body) {
if (body.details) {
@ -298,28 +288,23 @@ export class ErrorHandler {
for (const key in instance) {
/* istanbul ignore else */
if (this.componentRef.instance.hasOwnProperty(key)) {
if (Object.prototype.hasOwnProperty.call(this.componentRef.instance, key)) {
this.componentRef.instance[key] = instance[key];
}
}
this.componentRef.instance.hideCloseIcon =
this.httpErrorConfig.errorScreen.hideCloseIcon;
this.componentRef.instance.hideCloseIcon = this.httpErrorConfig.errorScreen.hideCloseIcon;
const appRef = this.injector.get(ApplicationRef);
if (this.canCreateCustomError(instance.status as ErrorScreenErrorCodes)) {
this.componentRef.instance.cfRes = this.cfRes;
this.componentRef.instance.appRef = appRef;
this.componentRef.instance.injector = this.injector;
this.componentRef.instance.customComponent =
this.httpErrorConfig.errorScreen.component;
this.componentRef.instance.customComponent = this.httpErrorConfig.errorScreen.component;
}
appRef.attachView(this.componentRef.hostView);
renderer.appendChild(
host,
(this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0]
);
renderer.appendChild(host, (this.componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0]);
const destroy$ = new Subject<void>();
this.componentRef.instance.destroy$ = destroy$;
@ -339,19 +324,13 @@ export class ErrorHandler {
protected filterRestErrors = ({ status }: HttpErrorResponse): boolean => {
if (typeof status !== 'number') return false;
return (
this.httpErrorConfig.skipHandledErrorCodes.findIndex(
(code) => code === status
) < 0
);
return this.httpErrorConfig.skipHandledErrorCodes.findIndex(code => code === status) < 0;
};
protected filterRouteErrors = (navigationError: NavigationError): boolean => {
return (
navigationError.error?.message?.indexOf('Cannot match') > -1 &&
this.httpErrorConfig.skipHandledErrorCodes.findIndex(
(code) => code === 404
) < 0
this.httpErrorConfig.skipHandledErrorCodes.findIndex(code => code === 404) < 0
);
};
}

1
npm/ng-packs/nx/ng-packs/packages/theme-shared/src/lib/tests/breadcrumb.component.spec.ts

@ -9,6 +9,7 @@ import { HttpClient } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { createRoutingFactory, SpectatorRouting, SpyObject } from '@ngneat/spectator/jest';
import { Store } from '@ngxs/store';
// eslint-disable-next-line @nrwl/nx/enforce-module-boundaries
import { mockRoutesService } from '../../../../core/src/lib/tests/routes.service.spec';
import { BreadcrumbComponent } from '../components/breadcrumb/breadcrumb.component';

Loading…
Cancel
Save