@seniorsistemas/platform-components 7.2.0 → 7.2.1-develop-c3823f83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/esm2022/modules/advanced-filter/advanced-filter.module.mjs +32 -35
  2. package/esm2022/modules/advanced-filter/components/advanced-filter/advanced-filter.component.mjs +33 -9
  3. package/esm2022/modules/advanced-filter/components/form-filter/form-filter.component.mjs +132 -85
  4. package/esm2022/modules/advanced-filter/locale/fallback.mjs +1 -46
  5. package/esm2022/modules/advanced-filter/services/advanced-filter.service.mjs +110 -31
  6. package/esm2022/modules/advanced-filter/services/calendar-options.service.mjs +13 -64
  7. package/esm2022/modules/advanced-filter/utils/filter-value/index.mjs +7 -11
  8. package/esm2022/modules/advanced-filter/utils/form-field/index.mjs +10 -9
  9. package/esm2022/modules/spotlight/component/spotlight.component.mjs +7 -8
  10. package/esm2022/modules/spotlight/spotlight.module.mjs +7 -14
  11. package/esm2022/modules/translations/translations.module.mjs +4 -4
  12. package/fesm2022/seniorsistemas-platform-components.mjs +336 -296
  13. package/fesm2022/seniorsistemas-platform-components.mjs.map +1 -1
  14. package/modules/advanced-filter/advanced-filter.module.d.ts +10 -11
  15. package/modules/advanced-filter/components/advanced-filter/advanced-filter.component.d.ts +9 -1
  16. package/modules/advanced-filter/components/form-filter/form-filter.component.d.ts +13 -5
  17. package/modules/advanced-filter/locale/fallback.d.ts +0 -45
  18. package/modules/advanced-filter/services/advanced-filter.service.d.ts +20 -0
  19. package/modules/advanced-filter/services/calendar-options.service.d.ts +8 -12
  20. package/modules/spotlight/spotlight.module.d.ts +5 -6
  21. package/modules/translations/translations.module.d.ts +1 -1
  22. package/package.json +12 -2
  23. package/schematics/collection.json +10 -0
  24. package/schematics/migrations/migrate-v8/index.d.ts +57 -0
  25. package/schematics/migrations/migrate-v8/index.js +281 -0
  26. package/schematics/migrations/migrate-v8/index.js.map +1 -0
  27. package/schematics/migrations/migrate-v8/schema.json +17 -0
  28. package/schematics/migrations.json +11 -0
@@ -3,21 +3,20 @@ import * as i1 from "./components/advanced-filter/advanced-filter.component";
3
3
  import * as i2 from "./components/form-filter/form-filter.component";
4
4
  import * as i3 from "./pipes/map-values.pipe";
5
5
  import * as i4 from "./pipes/translate.pipe";
6
- import * as i5 from "primeng/dialog";
7
- import * as i6 from "@seniorsistemas/angular-components/button";
8
- import * as i7 from "primeng/button";
9
- import * as i8 from "primeng/tabview";
10
- import * as i9 from "@angular/common";
11
- import * as i10 from "@angular/forms";
12
- import * as i11 from "@seniorsistemas/angular-components/dynamic-form";
13
- import * as i12 from "primeng/toast";
6
+ import * as i5 from "@seniorsistemas/angular-components/badge";
7
+ import * as i6 from "@seniorsistemas/angular-components/dialog";
8
+ import * as i7 from "@seniorsistemas/angular-components/template";
9
+ import * as i8 from "@seniorsistemas/angular-components/button";
10
+ import * as i9 from "@seniorsistemas/angular-components/tabs";
11
+ import * as i10 from "@angular/common";
12
+ import * as i11 from "@angular/forms";
13
+ import * as i12 from "@seniorsistemas/angular-components/dynamic-form";
14
14
  import * as i13 from "@seniorsistemas/angular-components/empty-state";
15
- import * as i14 from "primeng/tooltip";
16
- import * as i15 from "../translations/translations.module";
15
+ import * as i14 from "../translations/translations.module";
17
16
  export declare class AppRoutingModule {
18
17
  }
19
18
  export declare class AdvancedFilterModule {
20
19
  static ɵfac: i0.ɵɵFactoryDeclaration<AdvancedFilterModule, never>;
21
- static ɵmod: i0.ɵɵNgModuleDeclaration<AdvancedFilterModule, [typeof i1.AdvancedFilterComponent, typeof i2.FormFilterComponent, typeof i3.MapValuesPipe, typeof i4.TranslatePipe], [typeof i5.DialogModule, typeof i6.ButtonModule, typeof i7.ButtonModule, typeof i8.TabViewModule, typeof i9.CommonModule, typeof i10.FormsModule, typeof i10.ReactiveFormsModule, typeof i11.DynamicFormModule, typeof i12.ToastModule, typeof i13.EmptyStateModule, typeof i14.TooltipModule, typeof i15.TranslationsModule], [typeof i1.AdvancedFilterComponent, typeof i2.FormFilterComponent]>;
20
+ static ɵmod: i0.ɵɵNgModuleDeclaration<AdvancedFilterModule, [typeof i1.AdvancedFilterComponent, typeof i2.FormFilterComponent, typeof i3.MapValuesPipe, typeof i4.TranslatePipe], [typeof i5.BadgeComponent, typeof i6.DialogComponent, typeof i7.TemplateDirective, typeof i8.ButtonComponent, typeof i9.TabsComponent, typeof i9.TabItemComponent, typeof i10.CommonModule, typeof i11.FormsModule, typeof i11.ReactiveFormsModule, typeof i12.DynamicFormComponent, typeof i13.EmptyStateComponent, typeof i14.TranslationsModule], [typeof i1.AdvancedFilterComponent, typeof i2.FormFilterComponent]>;
22
21
  static ɵinj: i0.ɵɵInjectorDeclaration<AdvancedFilterModule>;
23
22
  }
@@ -17,9 +17,16 @@ export declare class AdvancedFilterComponent implements OnInit, OnDestroy {
17
17
  isMobile: boolean;
18
18
  tabViewOrientation: string;
19
19
  totalFiltersActive: number;
20
- showDialog: boolean;
21
20
  error: boolean;
22
21
  currentTicket: string;
22
+ private _showDialog;
23
+ private hideTimeout?;
24
+ /**
25
+ * Visibilidade do diálogo de filtros. Qualquer transição (pelo usuário ou programática) dispara os
26
+ * mesmos efeitos que o antigo p-dialog disparava em `onShow`/`onHide`.
27
+ */
28
+ get showDialog(): boolean;
29
+ set showDialog(value: boolean);
23
30
  modalComponent: FormFilterComponent;
24
31
  filterButtonRef: ElementRef;
25
32
  mobileButtonActions: {
@@ -39,6 +46,7 @@ export declare class AdvancedFilterComponent implements OnInit, OnDestroy {
39
46
  applyFilters(): void;
40
47
  onApplyFilters(): void;
41
48
  toggleDialog(): void;
49
+ onDialogShow(): void;
42
50
  onDialogHide(): void;
43
51
  focusFirstField(): void;
44
52
  updateTotalFiltersActive(event: number): void;
@@ -19,12 +19,13 @@ export declare class FormFilterComponent implements OnInit, OnDestroy {
19
19
  formFilters: FormFilter[];
20
20
  oldFormFilters: FormFilter[];
21
21
  actualFormFilters: any[];
22
+ private readonly lastSuggestions;
22
23
  general: TabView;
23
24
  totalFiltersActive: number;
24
25
  isMobile: boolean;
25
26
  tabViewOrientation: string;
26
27
  error: boolean;
27
- activeIndex: number;
28
+ activeIndex: string | number;
28
29
  errorMessages: {
29
30
  min: any;
30
31
  max: any;
@@ -67,6 +68,8 @@ export declare class FormFilterComponent implements OnInit, OnDestroy {
67
68
  */
68
69
  private createTabs;
69
70
  private updateFilterValue;
71
+ private normalizeSearchValue;
72
+ private resolveSearchItem;
70
73
  private cleanFieldAndSetDefaultValue;
71
74
  private createChildArray;
72
75
  private createField;
@@ -79,12 +82,17 @@ export declare class FormFilterComponent implements OnInit, OnDestroy {
79
82
  private updateNonCommaOperatorState;
80
83
  private getEntitySearchUrl;
81
84
  private addSuggestionFields;
82
- private getDependenciesValues;
83
- private IsEmpty;
84
85
  /**
85
- * Return format to specify for integer type field
86
+ * Verifica se um item já selecionado corresponde a uma sugestão retornada pela busca.
87
+ * A comparação primária é pelo keyValue. Para filtros salvos em formato antigo — onde o
88
+ * keyValue foi gravado com o displayValue (ou o item é uma string pura) e portanto não casa
89
+ * com o id atual das sugestões — é feito fallback pela comparação de displayValue.
86
90
  */
87
- private optionsInteger;
91
+ private isSameSuggestion;
92
+ private getSuggestionKey;
93
+ private getSuggestionDisplay;
94
+ private getDependenciesValues;
95
+ private IsEmpty;
88
96
  static ɵfac: i0.ɵɵFactoryDeclaration<FormFilterComponent, never>;
89
97
  static ɵcmp: i0.ɵɵComponentDeclaration<FormFilterComponent, "s-app-form-filter", never, { "showMessages": { "alias": "showMessages"; "required": false; }; "contextId": { "alias": "contextId"; "required": false; }; }, { "totalFiltersActiveOutput": "totalFiltersActiveOutput"; "errorOutput": "errorOutput"; "showDialogOutput": "showDialogOutput"; "closeModalOutput": "closeModalOutput"; }, never, never, false, never>;
90
98
  }
@@ -21,51 +21,6 @@ export declare const fallback: {
21
21
  'platform.filter_service.hour_format': string;
22
22
  'platform.filter_service.clear': string;
23
23
  'platform.filter_service.today': string;
24
- 'platform.filter_service.name_january': string;
25
- 'platform.filter_service.name_february': string;
26
- 'platform.filter_service.name_march': string;
27
- 'platform.filter_service.name_april': string;
28
- 'platform.filter_service.name_may': string;
29
- 'platform.filter_service.name_june': string;
30
- 'platform.filter_service.name_july': string;
31
- 'platform.filter_service.name_august': string;
32
- 'platform.filter_service.name_september': string;
33
- 'platform.filter_service.name_october': string;
34
- 'platform.filter_service.name_november': string;
35
- 'platform.filter_service.name_december': string;
36
- 'platform.filter_service.short_january': string;
37
- 'platform.filter_service.short_february': string;
38
- 'platform.filter_service.short_march': string;
39
- 'platform.filter_service.short_april': string;
40
- 'platform.filter_service.short_may': string;
41
- 'platform.filter_service.short_june': string;
42
- 'platform.filter_service.short_july': string;
43
- 'platform.filter_service.short_august': string;
44
- 'platform.filter_service.short_september': string;
45
- 'platform.filter_service.short_october': string;
46
- 'platform.filter_service.short_november': string;
47
- 'platform.filter_service.short_december': string;
48
- 'platform.filter_service.name_sunday': string;
49
- 'platform.filter_service.name_monday': string;
50
- 'platform.filter_service.name_tuesday': string;
51
- 'platform.filter_service.name_wednesday': string;
52
- 'platform.filter_service.name_thursday': string;
53
- 'platform.filter_service.name_friday': string;
54
- 'platform.filter_service.name_saturday': string;
55
- 'platform.filter_service.min_sunday': string;
56
- 'platform.filter_service.min_monday': string;
57
- 'platform.filter_service.min_tuesday': string;
58
- 'platform.filter_service.min_wednesday': string;
59
- 'platform.filter_service.min_thursday': string;
60
- 'platform.filter_service.min_friday': string;
61
- 'platform.filter_service.min_saturday': string;
62
- 'platform.filter_service.short_sunday': string;
63
- 'platform.filter_service.short_monday': string;
64
- 'platform.filter_service.short_tuesday': string;
65
- 'platform.filter_service.short_wednesday': string;
66
- 'platform.filter_service.short_thursday': string;
67
- 'platform.filter_service.short_friday': string;
68
- 'platform.filter_service.short_saturday': string;
69
24
  'platform.filter_service.yes': string;
70
25
  'platform.filter_service.no': string;
71
26
  'platform.filter_service.search_empty_message': string;
@@ -11,6 +11,9 @@ export interface TickedFilterResponse {
11
11
  export interface ContextsFiltersResponse {
12
12
  filters: Filter[];
13
13
  }
14
+ export interface FiltersByTicketResponse {
15
+ filters: TickedFilter[];
16
+ }
14
17
  export interface IGetFiltersResponse {
15
18
  error?: boolean;
16
19
  message?: HttpErrorResponse;
@@ -43,12 +46,29 @@ export declare class AdvancedFilterService {
43
46
  tryAgain(serviceContexts: Context[]): void;
44
47
  private getAndApplyFilters;
45
48
  private getFilters;
49
+ private applyTicketValues;
50
+ private fetchFiltersByTicket;
51
+ private mergeTicketValues;
52
+ /**
53
+ * Reconstrói o valor do filtro a partir dos itens do ticket (que contém apenas as chaves),
54
+ * reaproveitando o objeto completo já presente no filtro base quando a chave corresponde —
55
+ * preservando assim o texto de exibição. Chaves ausentes no base são mantidas como estão
56
+ * e resolvidas posteriormente pela busca de sugestões.
57
+ */
58
+ private buildMergedValue;
59
+ private indexBaseItemsByKey;
60
+ private getSearchOutput;
61
+ private parseJsonArray;
62
+ private buildTicketValueMap;
63
+ private normalizeTicketValue;
64
+ private getTicketKey;
46
65
  private mapFilters;
47
66
  private applySearchMapping;
48
67
  private assignFilterValue;
49
68
  private isMultiple;
50
69
  private mapValues;
51
70
  private mapValue;
71
+ private isPrimitiveValue;
52
72
  static ɵfac: i0.ɵɵFactoryDeclaration<AdvancedFilterService, never>;
53
73
  static ɵprov: i0.ɵɵInjectableDeclaration<AdvancedFilterService>;
54
74
  }
@@ -1,18 +1,14 @@
1
1
  import * as i0 from "@angular/core";
2
2
  export declare class CalendarOptionsService {
3
3
  private readonly translate;
4
- getOptions(): {
5
- clear: any;
6
- dateFormat: any;
7
- dayNames: any[];
8
- dayNamesMin: any[];
9
- dayNamesShort: any[];
10
- firstDayOfWeek: number;
11
- hourFormat: any;
12
- monthNames: any[];
13
- monthNamesShort: any[];
14
- today: any;
15
- };
4
+ /**
5
+ * Formato de data do locale ativo no padrão do `s-datepicker` (ex.: `dd/MM/yyyy`).
6
+ *
7
+ * As traduções `platform.filter_service.date_format` seguem o padrão legado do PrimeNG
8
+ * (`dd/mm/yy`), por isso são convertidas: `mm` → `MM` e `yy` → `yyyy`.
9
+ */
10
+ getDateFormat(): string;
11
+ getHourFormat(): '12' | '24';
16
12
  static ɵfac: i0.ɵɵFactoryDeclaration<CalendarOptionsService, never>;
17
13
  static ɵprov: i0.ɵɵInjectableDeclaration<CalendarOptionsService>;
18
14
  }
@@ -2,13 +2,12 @@ import * as i0 from "@angular/core";
2
2
  import * as i1 from "./component/spotlight.component";
3
3
  import * as i2 from "./pipes/translate.pipe";
4
4
  import * as i3 from "@angular/cdk/a11y";
5
- import * as i4 from "primeng/button";
6
- import * as i5 from "primeng/tooltip";
7
- import * as i6 from "@angular/common";
8
- import * as i7 from "../http-interceptor/http-interceptor.module";
9
- import * as i8 from "../translations/translations.module";
5
+ import * as i4 from "@seniorsistemas/angular-components/button";
6
+ import * as i5 from "@angular/common";
7
+ import * as i6 from "../http-interceptor/http-interceptor.module";
8
+ import * as i7 from "../translations/translations.module";
10
9
  export declare class SpotlightModule {
11
10
  static ɵfac: i0.ɵɵFactoryDeclaration<SpotlightModule, never>;
12
- static ɵmod: i0.ɵɵNgModuleDeclaration<SpotlightModule, [typeof i1.SpotlightComponent, typeof i2.TranslatePipe], [typeof i3.A11yModule, typeof i4.ButtonModule, typeof i5.TooltipModule, typeof i6.CommonModule, typeof i7.HttpInterceptorModule, typeof i8.TranslationsModule], [typeof i1.SpotlightComponent]>;
11
+ static ɵmod: i0.ɵɵNgModuleDeclaration<SpotlightModule, [typeof i1.SpotlightComponent, typeof i2.TranslatePipe], [typeof i3.A11yModule, typeof i4.ButtonComponent, typeof i5.CommonModule, typeof i6.HttpInterceptorModule, typeof i7.TranslationsModule], [typeof i1.SpotlightComponent]>;
13
12
  static ɵinj: i0.ɵɵInjectorDeclaration<SpotlightModule>;
14
13
  }
@@ -1,7 +1,7 @@
1
1
  import { HttpClient } from '@angular/common/http';
2
2
  import { InjectionToken, Injector, ModuleWithProviders } from '@angular/core';
3
3
  import { TranslateService } from '@ngx-translate/core';
4
- import { CookieService } from 'ngx-cookie-service';
4
+ import { CookieService } from '@seniorsistemas/angular-components/cookie';
5
5
  import * as i0 from "@angular/core";
6
6
  import * as i1 from "@ngx-translate/core";
7
7
  export declare const TranslationsConfig: InjectionToken<ITranslationsConfig[]>;
package/package.json CHANGED
@@ -1,5 +1,7 @@
1
1
  {
2
2
  "dependencies": {
3
+ "json-cycle": "^1.5.0",
4
+ "ramda": "^0.26.0",
3
5
  "tslib": "^2.3.0"
4
6
  },
5
7
  "exports": {
@@ -15,15 +17,23 @@
15
17
  },
16
18
  "module": "fesm2022/seniorsistemas-platform-components.mjs",
17
19
  "name": "@seniorsistemas/platform-components",
20
+ "ng-update": {
21
+ "migrations": "./schematics/migrations.json",
22
+ "packageGroup": {
23
+ "@seniorsistemas/angular-components": "^20.0.0"
24
+ }
25
+ },
18
26
  "peerDependencies": {
19
27
  "@angular/common": "^18.0.0",
20
- "@angular/core": "^18.0.0"
28
+ "@angular/core": "^18.0.0",
29
+ "@seniorsistemas/angular-components": "^20.0.1"
21
30
  },
22
31
  "repository": {
23
32
  "type": "git",
24
33
  "url": "http://git.senior.com.br/arquitetura/platform-components"
25
34
  },
35
+ "schematics": "./schematics/collection.json",
26
36
  "sideEffects": false,
27
37
  "typings": "index.d.ts",
28
- "version": "7.2.0"
38
+ "version": "7.2.1-develop-c3823f83"
29
39
  }
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "../../node_modules/@angular-devkit/schematics/collection-schema.json",
3
+ "schematics": {
4
+ "migrate-v8": {
5
+ "description": "Prepara o projeto para a v8 do platform-components (angular-components v20): adiciona provideLookupField() aos providers raiz do app quando ele usa o filtro avançado, pois os campos de pesquisa (SEARCH) passaram a usar o s-autocomplete. Também disponível via \"ng generate @seniorsistemas/platform-components:migrate-v8\".",
6
+ "factory": "./migrations/migrate-v8/index#migrate",
7
+ "schema": "./migrations/migrate-v8/schema.json"
8
+ }
9
+ }
10
+ }
@@ -0,0 +1,57 @@
1
+ import { Rule } from '@angular-devkit/schematics';
2
+ import * as ts from 'typescript';
3
+ export declare const PLATFORM_PACKAGE = "@seniorsistemas/platform-components";
4
+ export declare const LOOKUP_ENTRY = "@seniorsistemas/angular-components/lookup";
5
+ export declare const LOOKUP_PROVIDER = "provideLookupField";
6
+ /** Símbolos do platform-components que renderizam o filtro avançado (e, com ele, o campo `autocomplete`). */
7
+ export declare const ADVANCED_FILTER_SYMBOLS: string[];
8
+ interface ProvidersTarget {
9
+ priority: number;
10
+ path: string;
11
+ object: ts.ObjectLiteralExpression;
12
+ }
13
+ /** O arquivo importa algum símbolo do filtro avançado de `@seniorsistemas/platform-components`? */
14
+ export declare function usesAdvancedFilter(sf: ts.SourceFile): boolean;
15
+ /** O arquivo já chama `provideLookupField(...)`? */
16
+ export declare function hasLookupProvider(content: string): boolean;
17
+ /**
18
+ * Objeto com `providers` do app: `ApplicationConfig` (prioridade 0), `bootstrapApplication` (1) ou `NgModule` raiz,
19
+ * o que tem `bootstrap` (2). Menor prioridade ganha.
20
+ */
21
+ export declare function findProvidersTarget(path: string, sf: ts.SourceFile): ProvidersTarget | undefined;
22
+ export interface MigrationChange {
23
+ /** Caminho do arquivo alterado. */
24
+ path: string;
25
+ content: string;
26
+ message: string;
27
+ }
28
+ export interface MigrationResult {
29
+ /** Caminho do (primeiro) arquivo alterado, quando houve alteração. */
30
+ changed?: string;
31
+ /** Mensagem para o usuário, quando algo ficou pendente ou foi feito. */
32
+ message?: string;
33
+ /** Todas as alterações (uma por projeto que usa o filtro avançado). */
34
+ changes?: MigrationChange[];
35
+ /** Avisos de projetos em que não foi possível alterar nada. */
36
+ warnings?: string[];
37
+ }
38
+ export interface PlanOptions {
39
+ /** Raízes dos projetos do `angular.json` (sem barras nas pontas; `''` para a raiz do workspace). */
40
+ projectRoots?: string[];
41
+ }
42
+ /**
43
+ * Parte pura da migração: recebe os arquivos do projeto (caminho → conteúdo) e devolve o que mudar. Cada projeto do
44
+ * workspace que usa o filtro avançado é tratado separadamente: o alvo é escolhido entre os arquivos do próprio projeto.
45
+ */
46
+ export declare function planLookupProvider(files: Map<string, string>, options?: PlanOptions): MigrationResult & {
47
+ content?: string;
48
+ };
49
+ export interface MigrateOptions {
50
+ /** Pasta (relativa à raiz do workspace) que limita a migração. Tem precedência sobre `project`. */
51
+ path?: string;
52
+ /** Nome do projeto do angular.json que limita a migração. */
53
+ project?: string;
54
+ }
55
+ /** Migração do platform-components para a v8 (angular-components v20). Roda no `ng update` e via `ng generate`. */
56
+ export declare function migrate(options?: MigrateOptions): Rule;
57
+ export {};
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.migrate = exports.planLookupProvider = exports.findProvidersTarget = exports.hasLookupProvider = exports.usesAdvancedFilter = exports.ADVANCED_FILTER_SYMBOLS = exports.LOOKUP_PROVIDER = exports.LOOKUP_ENTRY = exports.PLATFORM_PACKAGE = void 0;
4
+ const ts = require("typescript");
5
+ exports.PLATFORM_PACKAGE = '@seniorsistemas/platform-components';
6
+ exports.LOOKUP_ENTRY = '@seniorsistemas/angular-components/lookup';
7
+ exports.LOOKUP_PROVIDER = 'provideLookupField';
8
+ /** Símbolos do platform-components que renderizam o filtro avançado (e, com ele, o campo `autocomplete`). */
9
+ exports.ADVANCED_FILTER_SYMBOLS = ['AdvancedFilterModule', 'AdvancedFilterComponent', 'FormFilterComponent'];
10
+ const SKIPPED_DIRS = ['/node_modules/', '/dist/', '/.angular/', '/.git/', '/coverage/'];
11
+ function parse(path, content) {
12
+ return ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true);
13
+ }
14
+ function isProjectSource(path) {
15
+ return (path.endsWith('.ts') &&
16
+ !path.endsWith('.d.ts') &&
17
+ !path.endsWith('.spec.ts') &&
18
+ !path.endsWith('.test.ts') &&
19
+ !SKIPPED_DIRS.some((dir) => path.includes(dir)));
20
+ }
21
+ function applyEdits(content, edits) {
22
+ return [...edits]
23
+ .sort((a, b) => b.start - a.start)
24
+ .reduce((text, edit) => text.slice(0, edit.start) + edit.text + text.slice(edit.end), content);
25
+ }
26
+ /** O arquivo importa algum símbolo do filtro avançado de `@seniorsistemas/platform-components`? */
27
+ function usesAdvancedFilter(sf) {
28
+ return sf.statements.some((statement) => ts.isImportDeclaration(statement) &&
29
+ ts.isStringLiteral(statement.moduleSpecifier) &&
30
+ statement.moduleSpecifier.text === exports.PLATFORM_PACKAGE &&
31
+ statement.importClause?.namedBindings !== undefined &&
32
+ ts.isNamedImports(statement.importClause.namedBindings) &&
33
+ statement.importClause.namedBindings.elements.some((el) => exports.ADVANCED_FILTER_SYMBOLS.includes((el.propertyName ?? el.name).text)));
34
+ }
35
+ exports.usesAdvancedFilter = usesAdvancedFilter;
36
+ /** O arquivo já chama `provideLookupField(...)`? */
37
+ function hasLookupProvider(content) {
38
+ return new RegExp(`\\b${exports.LOOKUP_PROVIDER}\\s*\\(`).test(content);
39
+ }
40
+ exports.hasLookupProvider = hasLookupProvider;
41
+ /**
42
+ * O objeto de providers do app (ou a variável/array que ele referencia, no caso de `providers` shorthand ou
43
+ * identificador) já chama `provideLookupField(...)`? Chamadas em outros arquivos (ex.: rotas lazy) não contam,
44
+ * pois não valem para o injector raiz.
45
+ */
46
+ function targetHasLookupProvider(sf, object) {
47
+ const texts = [object.getText(sf)];
48
+ const providers = object.properties.find((p) => p.name?.getText(sf) === 'providers');
49
+ const reference = providers
50
+ ? ts.isShorthandPropertyAssignment(providers)
51
+ ? providers.name.text
52
+ : ts.isPropertyAssignment(providers) && ts.isIdentifier(providers.initializer)
53
+ ? providers.initializer.text
54
+ : undefined
55
+ : undefined;
56
+ if (reference) {
57
+ const visit = (node) => {
58
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === reference && node.initializer) {
59
+ texts.push(node.initializer.getText(sf));
60
+ }
61
+ ts.forEachChild(node, visit);
62
+ };
63
+ visit(sf);
64
+ }
65
+ return texts.some(hasLookupProvider);
66
+ }
67
+ /**
68
+ * Objeto com `providers` do app: `ApplicationConfig` (prioridade 0), `bootstrapApplication` (1) ou `NgModule` raiz,
69
+ * o que tem `bootstrap` (2). Menor prioridade ganha.
70
+ */
71
+ function findProvidersTarget(path, sf) {
72
+ let found;
73
+ const consider = (priority, object) => {
74
+ if (!found || priority < found.priority)
75
+ found = { priority, path, object };
76
+ };
77
+ const visit = (node) => {
78
+ if (ts.isVariableDeclaration(node) &&
79
+ node.type &&
80
+ ts.isTypeReferenceNode(node.type) &&
81
+ node.type.typeName.getText(sf) === 'ApplicationConfig' &&
82
+ node.initializer &&
83
+ ts.isObjectLiteralExpression(node.initializer)) {
84
+ consider(0, node.initializer);
85
+ }
86
+ else if (ts.isCallExpression(node) &&
87
+ ts.isIdentifier(node.expression) &&
88
+ node.expression.text === 'bootstrapApplication' &&
89
+ node.arguments[1] &&
90
+ ts.isObjectLiteralExpression(node.arguments[1])) {
91
+ consider(1, node.arguments[1]);
92
+ }
93
+ else if (ts.isClassDeclaration(node)) {
94
+ for (const decorator of ts.canHaveDecorators(node) ? (ts.getDecorators(node) ?? []) : []) {
95
+ const call = decorator.expression;
96
+ if (ts.isCallExpression(call) &&
97
+ ts.isIdentifier(call.expression) &&
98
+ call.expression.text === 'NgModule' &&
99
+ call.arguments[0] &&
100
+ ts.isObjectLiteralExpression(call.arguments[0]) &&
101
+ call.arguments[0].properties.some((p) => p.name?.getText(sf) === 'bootstrap')) {
102
+ consider(2, call.arguments[0]);
103
+ }
104
+ }
105
+ }
106
+ ts.forEachChild(node, visit);
107
+ };
108
+ visit(sf);
109
+ return found;
110
+ }
111
+ exports.findProvidersTarget = findProvidersTarget;
112
+ function lineIndent(content, index) {
113
+ const lineStart = content.lastIndexOf('\n', index - 1) + 1;
114
+ return /^[ \t]*/.exec(content.slice(lineStart))?.[0] ?? '';
115
+ }
116
+ /** Edição que acrescenta `provideLookupField()` ao `providers` do objeto (criando-o se não existir). */
117
+ function addProviderEdit(content, sf, object) {
118
+ const call = `${exports.LOOKUP_PROVIDER}()`;
119
+ const eol = content.includes('\r\n') ? '\r\n' : '\n';
120
+ // providers → providers: [...providers, provideLookupField()]
121
+ const shorthand = object.properties.find((p) => ts.isShorthandPropertyAssignment(p) && p.name.text === 'providers');
122
+ if (shorthand) {
123
+ return { start: shorthand.getStart(sf), end: shorthand.getEnd(), text: `providers: [...providers, ${call}]` };
124
+ }
125
+ const providers = object.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText(sf) === 'providers');
126
+ if (providers && ts.isArrayLiteralExpression(providers.initializer)) {
127
+ const array = providers.initializer;
128
+ if (array.elements.length === 0) {
129
+ return { start: array.getStart(sf) + 1, end: array.getEnd() - 1, text: call };
130
+ }
131
+ const last = array.elements[array.elements.length - 1];
132
+ const multiline = array.getText(sf).includes('\n');
133
+ const text = multiline ? `,${eol}${lineIndent(content, last.getStart(sf))}${call}` : `, ${call}`;
134
+ return { start: last.getEnd(), end: last.getEnd(), text };
135
+ }
136
+ if (providers) {
137
+ // providers: algumaCoisa → providers: [...algumaCoisa, provideLookupField()]
138
+ const init = providers.initializer;
139
+ return { start: init.getStart(sf), end: init.getEnd(), text: `[...${init.getText(sf)}, ${call}]` };
140
+ }
141
+ const last = object.properties[object.properties.length - 1];
142
+ if (!last)
143
+ return { start: object.getStart(sf) + 1, end: object.getEnd() - 1, text: ` providers: [${call}] ` };
144
+ const multiline = object.getText(sf).includes('\n');
145
+ const text = multiline
146
+ ? `,${eol}${lineIndent(content, last.getStart(sf))}providers: [${call}]`
147
+ : `, providers: [${call}]`;
148
+ return { start: last.getEnd(), end: last.getEnd(), text };
149
+ }
150
+ /** Edição que garante `import { provideLookupField } from '.../lookup'`. */
151
+ function addImportEdit(sf) {
152
+ const existing = sf.statements.find((s) => ts.isImportDeclaration(s) && ts.isStringLiteral(s.moduleSpecifier) && s.moduleSpecifier.text === exports.LOOKUP_ENTRY);
153
+ const bindings = existing?.importClause?.namedBindings;
154
+ if (bindings && ts.isNamedImports(bindings)) {
155
+ if (bindings.elements.some((el) => (el.propertyName ?? el.name).text === exports.LOOKUP_PROVIDER))
156
+ return undefined;
157
+ const last = bindings.elements[bindings.elements.length - 1];
158
+ return last
159
+ ? { start: last.getEnd(), end: last.getEnd(), text: `, ${exports.LOOKUP_PROVIDER}` }
160
+ : { start: bindings.getStart(sf) + 1, end: bindings.getEnd() - 1, text: ` ${exports.LOOKUP_PROVIDER} ` };
161
+ }
162
+ const imports = sf.statements.filter(ts.isImportDeclaration);
163
+ const at = imports.length ? imports[imports.length - 1].getEnd() : 0;
164
+ const eol = sf.text.includes('\r\n') ? '\r\n' : '\n';
165
+ const text = `import { ${exports.LOOKUP_PROVIDER} } from '${exports.LOOKUP_ENTRY}';`;
166
+ return { start: at, end: at, text: imports.length ? `${eol}${text}` : `${text}${eol}` };
167
+ }
168
+ /** Projeto (raiz mais específica) a que o arquivo pertence. */
169
+ function projectOf(path, roots) {
170
+ return roots
171
+ .filter((root) => root === '' || path.startsWith(`/${root}/`))
172
+ .reduce((best, root) => (root.length > best.length ? root : best), '');
173
+ }
174
+ /**
175
+ * Parte pura da migração: recebe os arquivos do projeto (caminho → conteúdo) e devolve o que mudar. Cada projeto do
176
+ * workspace que usa o filtro avançado é tratado separadamente: o alvo é escolhido entre os arquivos do próprio projeto.
177
+ */
178
+ function planLookupProvider(files, options = {}) {
179
+ const roots = options.projectRoots ?? [];
180
+ const sources = [...files].filter(([path]) => isProjectSource(path));
181
+ const parsed = sources.map(([path, content]) => [path, content, parse(path, content)]);
182
+ const projects = [...new Set(parsed.filter(([, , sf]) => usesAdvancedFilter(sf)).map(([path]) => projectOf(path, roots)))];
183
+ const changes = [];
184
+ const warnings = [];
185
+ for (const project of projects) {
186
+ const inProject = parsed.filter(([path]) => projectOf(path, roots) === project);
187
+ let target;
188
+ let targetSource;
189
+ let targetContent = '';
190
+ for (const [path, content, sf] of inProject) {
191
+ const found = findProvidersTarget(path, sf);
192
+ if (found && (!target || found.priority < target.priority)) {
193
+ target = found;
194
+ targetSource = sf;
195
+ targetContent = content;
196
+ }
197
+ }
198
+ if (!target || !targetSource) {
199
+ warnings.push(`${project ? `Projeto em "${project}": o` : 'O'} app usa o filtro avançado do platform-components, mas não foi encontrado o ApplicationConfig, o bootstrapApplication ` +
200
+ `nem o NgModule raiz. Adicione ${exports.LOOKUP_PROVIDER}() (de '${exports.LOOKUP_ENTRY}') aos providers raiz do app.`);
201
+ continue;
202
+ }
203
+ if (targetHasLookupProvider(targetSource, target.object))
204
+ continue;
205
+ const edits = [addProviderEdit(targetContent, targetSource, target.object), addImportEdit(targetSource)].filter((e) => e !== undefined);
206
+ changes.push({
207
+ path: target.path,
208
+ content: applyEdits(targetContent, edits),
209
+ message: `${target.path}: adicionado ${exports.LOOKUP_PROVIDER}() aos providers raiz (necessário para os filtros de pesquisa do filtro avançado).`,
210
+ });
211
+ }
212
+ const result = {};
213
+ if (changes.length) {
214
+ result.changed = changes[0].path;
215
+ result.content = changes[0].content;
216
+ result.message = changes[0].message;
217
+ result.changes = changes;
218
+ }
219
+ if (warnings.length) {
220
+ result.warnings = warnings;
221
+ result.message ?? (result.message = warnings[0]);
222
+ }
223
+ return result;
224
+ }
225
+ exports.planLookupProvider = planLookupProvider;
226
+ function normalizeDir(dir) {
227
+ const cleaned = dir.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '').replace(/\/+$/, '');
228
+ return cleaned === '.' ? '' : cleaned;
229
+ }
230
+ function readProjectRoots(tree) {
231
+ const buffer = tree.read('angular.json');
232
+ if (!buffer)
233
+ return {};
234
+ try {
235
+ const projects = JSON.parse(buffer.toString('utf-8')).projects ?? {};
236
+ return Object.fromEntries(Object.entries(projects).map(([name, entry]) => [name, normalizeDir(entry?.root ?? '')]));
237
+ }
238
+ catch {
239
+ return {};
240
+ }
241
+ }
242
+ /** Pasta que delimita a migração (`''` = workspace inteiro). `--path` vence `--project`. */
243
+ function resolveScopeDir(options, roots, context) {
244
+ if (options.path)
245
+ return normalizeDir(options.path);
246
+ if (options.project) {
247
+ if (options.project in roots)
248
+ return roots[options.project];
249
+ context.logger.warn(`Projeto "${options.project}" não existe no angular.json: a opção --project foi ignorada.`);
250
+ }
251
+ return '';
252
+ }
253
+ function collectFiles(tree, scopeDir) {
254
+ const prefix = scopeDir ? `/${scopeDir}/` : '/';
255
+ const files = new Map();
256
+ tree.visit((path) => {
257
+ if (path.startsWith(prefix) && isProjectSource(path))
258
+ files.set(path, tree.read(path).toString('utf-8'));
259
+ });
260
+ return files;
261
+ }
262
+ /** Migração do platform-components para a v8 (angular-components v20). Roda no `ng update` e via `ng generate`. */
263
+ function migrate(options = {}) {
264
+ return (tree, context) => {
265
+ const roots = readProjectRoots(tree);
266
+ const scopeDir = resolveScopeDir(options, roots, context);
267
+ const result = planLookupProvider(collectFiles(tree, scopeDir), { projectRoots: Object.values(roots) });
268
+ for (const change of result.changes ?? []) {
269
+ tree.overwrite(change.path, change.content);
270
+ context.logger.info(change.message);
271
+ }
272
+ for (const warning of result.warnings ?? [])
273
+ context.logger.warn(warning);
274
+ if (!result.changes?.length && !result.warnings?.length) {
275
+ context.logger.info('platform-components v8: nenhuma alteração necessária.');
276
+ }
277
+ return tree;
278
+ };
279
+ }
280
+ exports.migrate = migrate;
281
+ //# sourceMappingURL=index.js.map