@barcidev/ngx-autogen 0.1.3 → 0.1.5

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.
package/package.json CHANGED
@@ -1,61 +1,62 @@
1
- {
2
- "name": "@barcidev/ngx-autogen",
3
- "version": "0.1.3",
4
- "description": "A collection of Angular schematics for essential functionalities.",
5
- "main": "dist/index.js",
6
- "scripts": {
7
- "build": "tsc -p tsconfig.json",
8
- "test": "npm run build && jasmine src/**/*_spec.js",
9
- "prepublishOnly": "npm run build"
10
- },
11
- "files": [
12
- "src/**/*.js",
13
- "src/**/*.template",
14
- "src/**/*.d.ts",
15
- "src/**/schema.json",
16
- "src/collection.json",
17
- "README.md",
18
- "LICENSE"
19
- ],
20
- "keywords": [
21
- "angular",
22
- "schematics",
23
- "state-management",
24
- "ngrx",
25
- "signals",
26
- "scaffolding"
27
- ],
28
- "author": "Jorge Palacio Barcinilla",
29
- "license": "MIT",
30
- "schematics": "./src/collection.json",
31
- "repository": {
32
- "type": "git",
33
- "url": "https://github.com/jpalacio09/ngx-autogen.git"
34
- },
35
- "publishConfig": {
36
- "access": "public"
37
- },
38
- "homepage": "https://github.com/jpalacio09/ngx-autogen#readme",
39
- "bugs": {
40
- "url": "https://github.com/jpalacio09/ngx-autogen/issues"
41
- },
42
- "funding": {
43
- "type": "github",
44
- "url": "https://github.com/sponsors/jpalacio09"
45
- },
46
- "engines": {
47
- "node": ">=16.0.0"
48
- },
49
- "dependencies": {
50
- "@angular-devkit/core": "^20.3.13",
51
- "@angular-devkit/schematics": "^20.3.13",
52
- "@schematics/angular": "^21.0.4",
53
- "typescript": "~5.9.2"
54
- },
55
- "devDependencies": {
56
- "@types/jasmine": "~5.1.0",
57
- "@types/node": "^20.17.19",
58
- "copyfiles": "^2.4.1",
59
- "jasmine": "^5.0.0"
60
- }
61
- }
1
+ {
2
+ "name": "@barcidev/ngx-autogen",
3
+ "version": "0.1.5",
4
+ "description": "A collection of Angular schematics for essential functionalities.",
5
+ "main": "dist/index.js",
6
+ "scripts": {
7
+ "build": "tsc -p tsconfig.json",
8
+ "test": "npm run build && jasmine src/**/*_spec.js",
9
+ "prepublishOnly": "npm run build"
10
+ },
11
+ "files": [
12
+ "src/**/*.js",
13
+ "src/**/*.template",
14
+ "src/**/*.d.ts",
15
+ "src/**/schema.json",
16
+ "src/collection.json",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "keywords": [
21
+ "angular",
22
+ "schematics",
23
+ "state-management",
24
+ "ngrx",
25
+ "signals",
26
+ "scaffolding"
27
+ ],
28
+ "author": "Jorge Palacio Barcinilla",
29
+ "license": "MIT",
30
+ "schematics": "./src/collection.json",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/jpalacio09/ngx-autogen.git"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "homepage": "https://github.com/jpalacio09/ngx-autogen#readme",
39
+ "bugs": {
40
+ "url": "https://github.com/jpalacio09/ngx-autogen/issues"
41
+ },
42
+ "funding": {
43
+ "type": "github",
44
+ "url": "https://github.com/sponsors/jpalacio09"
45
+ },
46
+ "engines": {
47
+ "node": ">=16.0.0"
48
+ },
49
+ "dependencies": {
50
+ "@angular-devkit/core": "^20.3.13",
51
+ "@angular-devkit/schematics": "^20.3.13",
52
+ "@schematics/angular": "^21.0.4",
53
+ "typescript": "~5.9.2"
54
+ },
55
+ "devDependencies": {
56
+ "@angular-devkit/schematics-cli": "^21.1.2",
57
+ "@types/jasmine": "~5.1.0",
58
+ "@types/node": "^20.17.19",
59
+ "copyfiles": "^2.4.1",
60
+ "jasmine": "^5.0.0"
61
+ }
62
+ }
@@ -1,15 +1,15 @@
1
- {
2
- "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
3
- "schematics": {
4
- "ng-add": {
5
- "description": "Ng add schematic for ngx-autogen.",
6
- "factory": "./ng-add/index#ngAdd",
7
- "schema": "./ng-add/schema.json"
8
- },
9
- "app-store": {
10
- "description": "Adds NgRx Store to the Angular application with signal support.",
11
- "factory": "./ngrx/store/index#signalStore",
12
- "schema": "./ngrx/store/schema.json"
13
- }
14
- }
1
+ {
2
+ "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
3
+ "schematics": {
4
+ "ng-add": {
5
+ "description": "Ng add schematic for ngx-autogen.",
6
+ "factory": "./ng-add/index#ngAdd",
7
+ "schema": "./ng-add/schema.json"
8
+ },
9
+ "app-store": {
10
+ "description": "Adds NgRx Store to the Angular application with signal support.",
11
+ "factory": "./ngrx/store/index#signalStore",
12
+ "schema": "./ngrx/store/schema.json"
13
+ }
14
+ }
15
15
  }
@@ -11,26 +11,20 @@ function ngAdd(options) {
11
11
  throw new schematics_1.SchematicsException("Could not find package.json. Make sure you are in the root of an Angular project.");
12
12
  }
13
13
  const packageJson = JSON.parse(buffer.toString());
14
- // 1. Obtener la versión de Angular Core
15
14
  const angularCoreVer = packageJson.dependencies["@angular/core"] ||
16
15
  packageJson.devDependencies["@angular/core"];
17
16
  if (!angularCoreVer) {
18
17
  throw new schematics_1.SchematicsException("The version of @angular/core could not be determined. Please ensure that Angular is installed in your project.");
19
18
  }
20
19
  const mainVersion = parseInt(angularCoreVer.replace(/[^\d.]/g, "").split(".")[0], 10);
21
- // 2. Validación: NgRx Signals requiere Angular 16+ (v17+ recomendado)
22
- if (mainVersion < 16) {
23
- _context.logger.error(`❌ Error: ngx-essentials requires Angular v16 or higher. Detected: v${mainVersion}`);
20
+ if (mainVersion < 20) {
21
+ _context.logger.error(`❌ Error: ngx-essentials requires Angular v20 or higher. Detected: v${mainVersion}`);
24
22
  return tree; // Stop execution
25
23
  }
26
- // 3. Mapear versión de NgRx (NgRx suele ir a la par con Angular)
27
24
  const ngrxVersion = `^${mainVersion}.0.0`;
28
25
  _context.logger.info(`📦 Configuring dependencies for Angular v${mainVersion}...`);
29
- // 4. Modificar package.json
30
- const packageName = "@barcidev/ngx-autogen";
31
- // Inyectar dependencias compatibles
26
+ const packageName = "ngx-autogen";
32
27
  packageJson.dependencies = Object.assign(Object.assign({}, packageJson.dependencies), { "@ngrx/signals": ngrxVersion });
33
- // Mover a devDependencies si es necesario
34
28
  if (packageJson.dependencies[packageName]) {
35
29
  const currentVer = packageJson.dependencies[packageName];
36
30
  delete packageJson.dependencies[packageName];
@@ -39,9 +33,8 @@ function ngAdd(options) {
39
33
  packageJson.dependencies = sortObjectKeys(packageJson.dependencies);
40
34
  packageJson.devDependencies = sortObjectKeys(packageJson.devDependencies);
41
35
  tree.overwrite(packagePath, JSON.stringify(packageJson, null, 2));
42
- // 5. Configurar angular.json (Collections y Primary Key)
43
36
  updateAngularJson(tree, options);
44
- // 6. Tarea de instalación
37
+ updateTsConfig(tree);
45
38
  _context.addTask(new tasks_1.NodePackageInstallTask());
46
39
  return tree;
47
40
  };
@@ -63,16 +56,51 @@ function updateAngularJson(tree, options) {
63
56
  if (!workspace.cli)
64
57
  workspace.cli = {};
65
58
  const collections = workspace.cli.schematicCollections || [];
66
- if (!collections.includes("@barcidev/ngx-autogen")) {
67
- collections.push("@barcidev/ngx-autogen");
59
+ if (!collections.includes("ngx-autogen")) {
60
+ collections.push("ngx-autogen");
68
61
  workspace.cli.schematicCollections = collections;
69
62
  }
70
63
  if (!workspace.schematics)
71
64
  workspace.schematics = {};
72
- workspace.schematics["@barcidev/ngx-autogen:all"] = {
65
+ workspace.schematics["ngx-autogen:all"] = {
73
66
  pk: options.pk,
74
- path: options.path,
67
+ lang: options.lang,
75
68
  };
76
69
  tree.overwrite(path, JSON.stringify(workspace, null, 2));
77
70
  }
71
+ /**
72
+ * Configura los Paths en el tsconfig.json para permitir el uso de @shared/*
73
+ */
74
+ function updateTsConfig(tree) {
75
+ const tsConfigPath = "/tsconfig.json";
76
+ const path = tree.exists(tsConfigPath) ? tsConfigPath : "/tsconfig.app.json";
77
+ const buffer = tree.read(path);
78
+ if (!buffer)
79
+ return;
80
+ let contentText = buffer.toString();
81
+ // Limpieza manual de comentarios para evitar que JSON.parse falle
82
+ const cleanJson = contentText.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, "$1");
83
+ let tsconfig;
84
+ try {
85
+ tsconfig = JSON.parse(cleanJson);
86
+ }
87
+ catch (e) {
88
+ // Si falla, intentamos parsearlo tal cual por si no tiene comentarios
89
+ try {
90
+ tsconfig = JSON.parse(contentText);
91
+ }
92
+ catch (innerError) {
93
+ throw new schematics_1.SchematicsException(`No se pudo parsear ${path}. Asegúrate de que es un JSON válido.`);
94
+ }
95
+ }
96
+ // Configurar los paths
97
+ tsconfig.compilerOptions = tsconfig.compilerOptions || {};
98
+ tsconfig.compilerOptions.paths = tsconfig.compilerOptions.paths || {};
99
+ const sharedAlias = "@shared-state/*";
100
+ const sharedPath = ["src/app/shared/state/*"];
101
+ if (!tsconfig.compilerOptions.paths[sharedAlias]) {
102
+ tsconfig.compilerOptions.paths[sharedAlias] = sharedPath;
103
+ tree.overwrite(path, JSON.stringify(tsconfig, null, 2));
104
+ }
105
+ }
78
106
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- export interface NgAddSchemaOptions {
2
- pk: string;
3
- path: string;
4
- }
1
+ export interface NgAddSchemaOptions {
2
+ pk: string;
3
+ lang: string;
4
+ }
@@ -1,20 +1,20 @@
1
- {
2
- "$schema": "http://json-schema.org/schema",
3
- "$id": "ng-add-schema",
4
- "type": "object",
5
- "properties": {
6
- "pk": {
7
- "type": "string",
8
- "description": "The name of the default Primary Key (e.g., id, cod, uuid); default is 'id'.",
9
- "x-prompt": "What is the name of the default Primary Key (e.g., id, cod, uuid)?",
10
- "default": "id"
11
- },
12
- "path": {
13
- "type": "string",
14
- "description": "The path where the state management files will be created.",
15
- "x-prompt": "Where do you want to create the state management files?",
16
- "default": "src/app/core"
17
- }
18
- },
19
- "required": ["pk", "path"]
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "$id": "ng-add-schema",
4
+ "type": "object",
5
+ "properties": {
6
+ "pk": {
7
+ "type": "string",
8
+ "description": "The name of the default Primary Key (e.g., id, cod, uuid); default is 'id'.",
9
+ "x-prompt": "What is the name of the default Primary Key (e.g., id, cod, uuid)?",
10
+ "default": "id"
11
+ },
12
+ "lang":{
13
+ "type": "string",
14
+ "description": "The default language for the application (en, es); default is 'en'.",
15
+ "x-prompt": "What is the default language for the application (en, es)?",
16
+ "default": "en"
17
+ }
18
+ },
19
+ "required": ["pk"]
20
20
  }
@@ -1,22 +1,12 @@
1
- import { FormControl } from '@angular/forms';
2
-
3
- export interface EntityStatus {
4
- addError?: Error | null;
5
- addLoading?: boolean;
6
- error: Error | null;
7
- idSelected?: null | number | string;
8
- idsRemoving?: (number | string)[];
9
- idsUpdating?: (number | string)[];
10
- loaded: boolean;
11
- loading: boolean;
12
- removeError?: Error | null;
13
- removeLoading?: boolean;
14
- selectedError?: Error | null;
15
- selectedLoading?: boolean;
16
- updateError?: Error | null;
17
- updateLoading?: boolean;
18
- }
19
-
20
- export type FormGroupType<T> = {
21
- [K in keyof T]: FormControl<T[K]>;
22
- };
1
+ import { HttpErrorResponse } from '@angular/common/http';
2
+ import { FormControl } from '@angular/forms';
3
+
4
+ export type FormGroupType<T> = {
5
+ [K in keyof T]: FormControl<T[K]>;
6
+ };
7
+
8
+ export interface RequestConfig<T, U = unknown> {
9
+ onError?: (error?: HttpErrorResponse) => void;
10
+ onSuccess?: (response?: U) => void;
11
+ payload: T;
12
+ }
@@ -0,0 +1,89 @@
1
+ import { computed, Signal } from '@angular/core';
2
+ import {
3
+ EmptyFeatureResult,
4
+ patchState,
5
+ SignalStoreFeature,
6
+ signalStoreFeature,
7
+ withComputed,
8
+ withMethods,
9
+ withState
10
+ } from '@ngrx/signals';
11
+
12
+ export interface PaginationState {
13
+ page: number;
14
+ pageSize: number;
15
+ totalCount: number;
16
+ }
17
+
18
+ interface PaginationComputedProps {
19
+ hasNext: boolean;
20
+ hasPrevious: boolean;
21
+ totalPages: number;
22
+ }
23
+
24
+ const initialPaginationState: PaginationState = {
25
+ page: 1,
26
+ pageSize: 10,
27
+ totalCount: 0
28
+ };
29
+
30
+ /**
31
+ * Resetea el estado de paginación al estado inicial.
32
+ * @returns {PaginationState} - El estado inicial de paginación.
33
+ */
34
+ export function resetPaginationState(): PaginationState {
35
+ return initialPaginationState;
36
+ }
37
+
38
+ /**
39
+ * Agrega funcionalidades de paginación a un Store.
40
+ * @param {[number]} initialPageSize - Tamaño inicial de página (opcional).
41
+ * @returns {SignalStoreFeature} - Características de la tienda con estado, computados y métodos de paginación.
42
+ */
43
+ export function withPagination(initialPageSize?: number): SignalStoreFeature<
44
+ EmptyFeatureResult,
45
+ {
46
+ methods: {
47
+ nextPage: () => void;
48
+ previousPage: () => void;
49
+ setPage: (page: number) => void;
50
+ setPageSize: (pageSize: number) => void;
51
+ setTotalCount: (totalCount: number) => void;
52
+ };
53
+ props: Record<'paginationComputed', Signal<PaginationComputedProps>>;
54
+ state: Record<'pagination', PaginationState>;
55
+ }
56
+ > {
57
+ return signalStoreFeature(
58
+ withState({
59
+ pagination: initialPageSize ? { ...initialPaginationState, pageSize: initialPageSize } : initialPaginationState
60
+ }),
61
+
62
+ withComputed(({ pagination: { page, pageSize, totalCount } }) => ({
63
+ paginationComputed: computed(() => ({
64
+ hasNext: page() < Math.ceil(totalCount() / pageSize()),
65
+ hasPrevious: page() > 1,
66
+ totalPages: Math.ceil(totalCount() / pageSize())
67
+ }))
68
+ })),
69
+ withMethods((store) => ({
70
+ nextPage: () => {
71
+ if (store.pagination.page() < Math.ceil(store.pagination.totalCount() / store.pagination.pageSize())) {
72
+ patchState(store, (state) => ({ pagination: { ...state.pagination, page: store.pagination.page() + 1 } }));
73
+ }
74
+ },
75
+ previousPage: () => {
76
+ if (store.pagination.page() > 1) {
77
+ patchState(store, (state) => ({ pagination: { ...state.pagination, page: store.pagination.page() - 1 } }));
78
+ }
79
+ },
80
+ setPage: (page: number) => {
81
+ patchState(store, (state) => ({ pagination: { ...state.pagination, page } }));
82
+ },
83
+ setPageSize: (pageSize: number) =>
84
+ patchState(store, (state) => ({ pagination: { ...state.pagination, page: 1, pageSize } })), // Reset a pág 1 si cambia el tamaño
85
+ setTotalCount: (totalCount: number) =>
86
+ patchState(store, (state) => ({ pagination: { ...state.pagination, totalCount } }))
87
+ }))
88
+ );
89
+ }
@@ -0,0 +1,92 @@
1
+ import { computed, Signal } from '@angular/core';
2
+ import { EmptyFeatureResult, SignalStoreFeature, signalStoreFeature, withComputed, withState } from '@ngrx/signals';
3
+
4
+ export interface EntityStatus {
5
+ _removeLoading: boolean;
6
+ _updateLoading: boolean;
7
+ addError: Error | null;
8
+ addLoading: boolean;
9
+ error: Error | null;
10
+ idSelected: null | number | string;
11
+ idsRemoving: (number | string)[];
12
+ idsUpdating: (number | string)[];
13
+ loaded: boolean;
14
+ loading: boolean;
15
+ removeError: Error | null;
16
+ selectedError: Error | null;
17
+ selectedLoading: boolean;
18
+ updateError: Error | null;
19
+ }
20
+
21
+ interface EntityStatusComputedProps {
22
+ anyError: Error | null;
23
+ isAnyActionLoading: boolean;
24
+ removeLoading: boolean;
25
+ updateLoading: boolean;
26
+ }
27
+
28
+ type EntityStatusMethodProps = Record<string, (...args: unknown[]) => unknown>;
29
+
30
+ const initialState: EntityStatus = {
31
+ _removeLoading: false,
32
+ _updateLoading: false,
33
+ addError: null,
34
+ addLoading: false,
35
+ error: null,
36
+ idSelected: null,
37
+ idsRemoving: [],
38
+ idsUpdating: [],
39
+ loaded: false,
40
+ loading: false,
41
+ removeError: null,
42
+ selectedError: null,
43
+ selectedLoading: false,
44
+ updateError: null
45
+ };
46
+
47
+ /**
48
+ * Resetea el estado de la entidad al estado inicial.
49
+ * @returns {EntityStatus} - El estado inicial de la entidad.
50
+ */
51
+ export function resetEntityStatus(): EntityStatus {
52
+ return initialState;
53
+ }
54
+
55
+ /**
56
+ * Agrega funcionalidades comunes de estado y computados para manejar el estado de entidades.
57
+ * @returns {SignalStoreFeature} -Características de la tienda con estado y computados para el manejo de entidades.
58
+ */
59
+ export function withEntityStatus(): SignalStoreFeature<
60
+ EmptyFeatureResult,
61
+ {
62
+ methods: EntityStatusMethodProps;
63
+ props: Record<'statusComputed', Signal<EntityStatusComputedProps>>;
64
+ state: Record<'status', EntityStatus>;
65
+ }
66
+ > {
67
+ return signalStoreFeature(
68
+ withState({ status: initialState }),
69
+ withComputed(
70
+ ({
71
+ status: {
72
+ _removeLoading,
73
+ _updateLoading,
74
+ addError,
75
+ error,
76
+ idsRemoving,
77
+ idsUpdating,
78
+ removeError,
79
+ selectedError,
80
+ updateError
81
+ }
82
+ }) => ({
83
+ statusComputed: computed(() => ({
84
+ anyError: error() || addError() || removeError() || updateError() || selectedError(),
85
+ isAnyActionLoading: idsUpdating().length > 0 || idsRemoving().length > 0,
86
+ removeLoading: _removeLoading() || idsRemoving().length > 0,
87
+ updateLoading: _updateLoading() || idsUpdating().length > 0
88
+ }))
89
+ })
90
+ )
91
+ );
92
+ }
@@ -1,14 +1,14 @@
1
- import { FormGroupType } from '../common/entity/entity.model';
2
-
3
- export interface Add<%= classify(name) %> {
4
- }
5
-
6
- export type Add<%= classify(name) %>Form = FormGroupType<Add<%= classify(name) %>>;
7
-
8
- export interface <%= classify(name) %>Dto {
9
- <%= pk %>: number;
10
- }
11
-
12
- export type Update<%= classify(name) %> = Partial<<%= classify(name) %>Dto> & Pick<<%= classify(name) %>Dto, '<%= pk %>'>;
13
-
1
+ import { FormGroupType } from '@shared-state/entity.model';
2
+
3
+ export interface Add<%= classify(name) %> {
4
+ }
5
+
6
+ export type Add<%= classify(name) %>Form = FormGroupType<Add<%= classify(name) %>>;
7
+
8
+ export interface <%= classify(name) %>Dto {
9
+ <%= pk %>: number;
10
+ }
11
+
12
+ export type Update<%= classify(name) %> = Partial<<%= classify(name) %>Dto> & Pick<<%= classify(name) %>Dto, '<%= pk %>'>;
13
+
14
14
  export interface <%= classify(name) %>Request{}
@@ -1,29 +1,29 @@
1
- import { Injectable } from '@angular/core';
2
- import { Observable, of } from 'rxjs';
3
- import {
4
- Add<%= classify(name) %>,
5
- <%= classify(name) %>Dto,
6
- Update<%= classify(name) %>
7
- } from './<%= dasherize(name) %>.model';
8
-
9
- @Injectable({
10
- providedIn: 'root'
11
- })
12
- export class <%= classify(name) %>Service {
13
-
14
- add<%= classify(name) %>$(entity: Add<%= classify(name) %>): Observable<number> {
15
- return of(0);
16
- }
17
-
18
- remove<%= classify(name) %>$(<%= pk %>: number): Observable<boolean> {
19
- return of(true);
20
- }
21
-
22
- get<%= classify(pluralize(name)) %>$(): Observable<<%= classify(name) %>Dto[]> {
23
- return of([]);
24
- }
25
-
26
- update<%= classify(name) %>$(entity: Update<%= classify(name) %>): Observable<boolean> {
27
- return of(true);
28
- }
1
+ import { Injectable } from '@angular/core';
2
+ import { Observable, of } from 'rxjs';
3
+ import {
4
+ Add<%= classify(name) %>,
5
+ <%= classify(name) %>Dto,
6
+ Update<%= classify(name) %>
7
+ } from '<%= grouped ? "../models/" + dasherize(name) + ".model" : "./" + dasherize(name) + ".model" %>';
8
+
9
+ @Injectable({
10
+ providedIn: 'root'
11
+ })
12
+ export class <%= classify(name) %>Service {
13
+
14
+ add<%= classify(name) %>$(entity: Add<%= classify(name) %>): Observable<number> {
15
+ return of(0);
16
+ }
17
+
18
+ remove<%= classify(name) %>$(<%= pk %>: number): Observable<boolean> {
19
+ return of(true);
20
+ }
21
+
22
+ get<%= classify(pluralize(name)) %>$(): Observable<<%= classify(name) %>Dto[]> {
23
+ return of([]);
24
+ }
25
+
26
+ update<%= classify(name) %>$(entity: Update<%= classify(name) %>): Observable<boolean> {
27
+ return of(true);
28
+ }
29
29
  }