@barcidev/ngx-autogen 0.1.26 → 0.1.28

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,6 +1,6 @@
1
1
  {
2
2
  "name": "@barcidev/ngx-autogen",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
4
4
  "description": "A collection of Angular schematics for essential functionalities.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -50,7 +50,7 @@
50
50
  "dependencies": {
51
51
  "@angular-devkit/core": "^21.2.0",
52
52
  "@angular-devkit/schematics": "^21.2.0",
53
- "@barcidev/typed-transloco": "^0.0.9",
53
+ "@barcidev/typed-transloco": "^0.0.10",
54
54
  "@schematics/angular": "^21.2.0",
55
55
  "typescript": "~5.9.2"
56
56
  },
@@ -1,6 +1,6 @@
1
1
  import { Rule } from "@angular-devkit/schematics";
2
2
  import { TranslocoSchemaOptions } from "./scheme";
3
3
  /**
4
- * Lógica principal del Schematic
4
+ * Schematic principal para configurar Transloco en un componente específico
5
5
  */
6
6
  export declare function transloco(options: TranslocoSchemaOptions): Rule;
@@ -11,143 +11,139 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.transloco = transloco;
13
13
  const schematics_1 = require("@angular-devkit/schematics");
14
- const tasks_1 = require("@angular-devkit/schematics/tasks");
15
- const dependencies_1 = require("@schematics/angular/utility/dependencies");
16
14
  const workspace_1 = require("@schematics/angular/utility/workspace");
17
15
  const path_1 = require("path");
18
- const jsonc_parser_1 = require("jsonc-parser");
19
16
  const file_actions_1 = require("../common/file-actions");
20
17
  const pluralize_1 = require("../common/pluralize");
21
18
  /**
22
- * Lógica principal del Schematic
19
+ * Schematic principal para configurar Transloco en un componente específico
23
20
  */
24
21
  function transloco(options) {
25
- return (tree) => __awaiter(this, void 0, void 0, function* () {
22
+ return (tree, _context) => __awaiter(this, void 0, void 0, function* () {
23
+ // --- 1. CONFIGURACIÓN INICIAL Y WORKSPACE ---
26
24
  const workspace = yield (0, workspace_1.getWorkspace)(tree);
27
- // 1. Obtención correcta del ROOT del proyecto
28
- const projectName = options.project ||
29
- workspace.extensions.defaultProject ||
30
- Array.from(workspace.projects.keys())[0];
31
- const project = workspace.projects.get(projectName);
32
- if (!project)
33
- throw new schematics_1.SchematicsException(`El proyecto "${projectName}" no existe.`);
34
- // Usamos project.sourceRoot para ir a 'src' (o lo que esté configurado)
35
- const projectSourceRoot = project.sourceRoot || "src";
36
- // 2. Contexto del componente
37
- const { path, componentFile, componentName } = resolveComponentContext(tree, options);
38
- const finalOptions = Object.assign(Object.assign({}, options), { project: projectName, path, name: componentName, projectRoot: projectSourceRoot });
39
- // 3. RETORNO DE CADENA LIMPIA
40
- // El secreto es que todas las reglas sean secuenciales y no disparen procesos paralelos
25
+ if (!options.project) {
26
+ options.project =
27
+ workspace.extensions.defaultProject ||
28
+ Array.from(workspace.projects.keys())[0];
29
+ }
30
+ const project = workspace.projects.get(options.project);
31
+ if (!project) {
32
+ throw new schematics_1.SchematicsException(`El proyecto "${options.project}" no existe.`);
33
+ }
34
+ // --- 2. DETERMINACIÓN DE RUTAS Y DETECCIÓN DE COMPONENTE ---
35
+ // Resolvemos el path relativo (src/app/...) basado en el directorio de ejecución
36
+ const fullPath = process.cwd();
37
+ const srcIndex = fullPath.lastIndexOf("src");
38
+ const relativePath = srcIndex !== -1
39
+ ? fullPath.substring(srcIndex)
40
+ : (0, path_1.join)((0, path_1.normalize)("src"), "app");
41
+ options.path = (0, path_1.normalize)(relativePath);
42
+ const directory = tree.getDir(options.path);
43
+ // Buscamos el archivo .ts principal del directorio
44
+ const componentFile = directory.subfiles.find((f) => f.endsWith(".component.ts")) ||
45
+ directory.subfiles.find((f) => f.endsWith(".ts"));
46
+ if (!componentFile && !options.name) {
47
+ throw new schematics_1.SchematicsException("❌ No se encontró un archivo .ts en este directorio y no se proveyó un --name.");
48
+ }
49
+ // Normalizamos el nombre (ej. mi-componente.component -> mi-componente)
50
+ options.name = componentFile
51
+ ? componentFile.replace(".component.ts", "").replace(".ts", "")
52
+ : options.name;
53
+ const rules = [];
54
+ // --- 3. CONFIGURACIÓN GLOBAL (IDEMPOTENTE) ---
55
+ /*const appConfigPath = "src/app/app.config.ts";
56
+ const appConfigContent = tree.read(appConfigPath)?.toString() || "";
57
+
58
+ if (!appConfigContent.includes("provideTransloco")) {
59
+ _context.logger.info(
60
+ "📦 Transloco no detectado. Configurando globalmente...",
61
+ );
62
+ // Dependencias y tarea de instalación
63
+ rules.push((host: Tree) => {
64
+ addPackageJsonDependency(host, {
65
+ type: NodeDependencyType.Default,
66
+ name: "@jsverse/transloco",
67
+ version: "^7.0.0",
68
+ });
69
+ _context.addTask(new NodePackageInstallTask());
70
+ return host;
71
+ });
72
+ }*/
73
+ // --- 4. GENERACIÓN DE ARCHIVOS I18N DEL COMPONENTE ---
74
+ rules.push((0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)("./files/component"), [
75
+ (0, schematics_1.applyTemplates)(Object.assign(Object.assign(Object.assign({}, schematics_1.strings), options), { pluralize: (word) => options.lang === "es" ? (0, pluralize_1.pluralizeEs)(word) : (0, pluralize_1.pluralizeEn)(word) })),
76
+ (0, schematics_1.move)(options.path),
77
+ ])));
78
+ // --- 5. REGISTRO DEL SCOPE EN EL COMPONENTE ---
79
+ if (componentFile) {
80
+ const componentPath = (0, path_1.join)(options.path, componentFile);
81
+ const i18nConstantName = `${schematics_1.strings.camelize(options.name)}I18n`;
82
+ rules.push((0, file_actions_1.addProviderToStandaloneComponent)(componentPath, `provideTranslocoScopeWrapper(${i18nConstantName})`, [
83
+ {
84
+ symbol: `provideTranslocoScopeWrapper`,
85
+ path: `@barcidev/typed-transloco`,
86
+ },
87
+ {
88
+ symbol: i18nConstantName,
89
+ path: `./${schematics_1.strings.dasherize(options.name)}.i18n`,
90
+ },
91
+ ]));
92
+ }
41
93
  return (0, schematics_1.chain)([
42
- setupGlobalConfig(projectName),
43
- generateI18nFiles(finalOptions),
44
- updateAppI18nTypeRule(finalOptions), // Pasamos las opciones con el root
45
- registerProviderInComponent(finalOptions, componentFile),
94
+ ...rules,
95
+ (0, schematics_1.externalSchematic)("@barcidev/typed-transloco", "ng-add", {}),
46
96
  ]);
47
97
  });
48
98
  }
49
- function resolveComponentContext(tree, options) {
50
- const fullPath = process.cwd();
51
- const srcIndex = fullPath.lastIndexOf("src");
52
- const path = (0, path_1.normalize)(srcIndex !== -1
53
- ? fullPath.substring(srcIndex)
54
- : (0, path_1.join)((0, path_1.normalize)("src"), "app"));
55
- const directory = tree.getDir(path);
56
- const componentFile = directory.subfiles.find((f) => f.endsWith(".component.ts")) ||
57
- directory.subfiles.find((f) => f.endsWith(".ts"));
58
- if (!componentFile && !options.name) {
59
- throw new schematics_1.SchematicsException("❌ No se encontró un componente y no se proveyó un --name.");
99
+ /*function updateAppI18nType(
100
+ root: string,
101
+ name: string,
102
+ importPath: string,
103
+ ): Rule {
104
+ return (tree: Tree, context: SchematicContext) => {
105
+ const path = `${root}/app/i18n/app.i18n.ts`;
106
+ const buffer = tree.read(path);
107
+
108
+ if (!buffer) {
109
+ context.logger.warn(`⚠️ No se encontró el archivo ${path}`);
110
+ return tree;
60
111
  }
61
- const componentName = componentFile
62
- ? componentFile.replace(".component.ts", "").replace(".ts", "")
63
- : options.name;
64
- return { path, componentFile, componentName };
65
- }
66
- /**
67
- * Ajuste en setupGlobalConfig para recibir el proyecto
68
- */
69
- function setupGlobalConfig(projectName) {
70
- return (tree, context) => {
71
- var _a;
72
- const appConfigPath = "src/app/app.config.ts"; // Opcional: podrías usar el root aquí también
73
- const content = ((_a = tree.read(appConfigPath)) === null || _a === void 0 ? void 0 : _a.toString()) || "";
74
- if (content.includes("provideTransloco"))
75
- return tree;
76
- // Solo añadimos dependencias si no existen
77
- (0, dependencies_1.addPackageJsonDependency)(tree, {
78
- type: dependencies_1.NodeDependencyType.Default,
79
- name: "@jsverse/transloco",
80
- version: "^8.0.0",
81
- });
82
- context.addTask(new tasks_1.NodePackageInstallTask());
83
- // Devolvemos el schematic externo como parte de la cadena
84
- return (0, schematics_1.externalSchematic)("@barcidev/typed-transloco", "ng-add", {
85
- project: projectName,
86
- });
87
- };
88
- }
89
- function generateI18nFiles(options) {
90
- return (0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)("./files/component"), [
91
- (0, schematics_1.applyTemplates)(Object.assign(Object.assign(Object.assign({}, schematics_1.strings), options), { pluralize: (word) => options.lang === "es" ? (0, pluralize_1.pluralizeEs)(word) : (0, pluralize_1.pluralizeEn)(word) })),
92
- (0, schematics_1.move)(options.path),
93
- ]));
94
- }
95
- /** * Ajuste en updateAppI18nType para usar el root detectado
96
- */
97
- function updateAppI18nTypeRule(options) {
98
- return (tree, context) => {
99
- // IMPORTANTE: Construimos la ruta usando el root detectado dinámicamente
100
- const path = `${options.projectRoot}/app/i18n/app.i18n.ts`;
101
- const buffer = tree.read(path);
102
- if (!buffer) {
103
- context.logger.warn(`⚠️ No se encontró el archivo ${path}. Asegúrate de que ng-add se ejecutó primero.`);
104
- return tree;
105
- }
106
- let content = buffer.toString();
107
- const name = `${schematics_1.strings.camelize(options.name)}I18n`;
108
- const importPath = `${options.path}/${schematics_1.strings.dasherize(options.name)}.i18n`;
109
- // Lógica de importación
110
- const importStatement = `import { ${name} } from '${importPath}';\n`;
111
- if (!content.includes(importPath)) {
112
- content = importStatement + content;
113
- }
114
- // Lógica de JSONC-Parser para evitar Overlapping
115
- const modificationOptions = {
116
- formattingOptions: { insertSpaces: true, tabSize: 2 },
117
- };
118
- const regex = /const\s+appI18n\s*=\s*(\{[\s\S]*?\});/;
119
- const match = content.match(regex);
120
- if (match) {
121
- const oldObjectStr = match[1];
122
- // El valor que quieres inyectar: name.translations['en-US']
123
- const valueToInject = `${name}.translations['en-US']`;
124
- // TRUCO: Usamos un placeholder para que jsonc-parser no ponga comillas de string
125
- const placeholder = `__REF__${name}`;
126
- const edits = (0, jsonc_parser_1.modify)(oldObjectStr, [schematics_1.strings.camelize(options.name)], placeholder, modificationOptions);
127
- let newObjectStr = (0, jsonc_parser_1.applyEdits)(oldObjectStr, edits);
128
- // Reemplazamos el placeholder por la referencia real de TS
129
- newObjectStr = newObjectStr.replace(`"${placeholder}"`, valueToInject);
130
- const newContent = content.replace(oldObjectStr, newObjectStr);
131
- tree.overwrite(path, newContent);
132
- context.logger.info(`✅ Registro de tipos actualizado en app.i18n.ts`);
133
- }
134
- return tree;
112
+
113
+ let content = buffer.toString();
114
+ const importStatement = `import { ${name} } from '${importPath}';\n`;
115
+
116
+ // 1. AGREGAR EL IMPORT (si no existe ya)
117
+ if (!content.includes(importPath)) {
118
+ content = importStatement + content;
119
+ }
120
+
121
+ // 2. ACTUALIZAR EL OBJETO appI18n
122
+ const options: ModificationOptions = {
123
+ formattingOptions: { insertSpaces: true, tabSize: 2 },
135
124
  };
136
- }
137
- function registerProviderInComponent(options, componentFile) {
138
- if (!componentFile)
139
- return (tree) => tree;
140
- const componentPath = (0, path_1.join)(options.path, componentFile);
141
- const i18nConstantName = `${schematics_1.strings.camelize(options.name)}I18n`;
142
- return (0, file_actions_1.addProviderToStandaloneComponent)(componentPath, `provideTranslocoScopeWrapper(${i18nConstantName})`, [
143
- {
144
- symbol: `provideTranslocoScopeWrapper`,
145
- path: `@barcidev/typed-transloco`,
146
- },
147
- {
148
- symbol: i18nConstantName,
149
- path: `./${schematics_1.strings.dasherize(options.name)}.i18n`,
150
- },
151
- ]);
152
- }
125
+
126
+ // Buscamos el bloque del objeto appI18n
127
+ const regex = /const\s+appI18n\s*=\s*(\{[\s\S]*?\});/;
128
+ const match = content.match(regex);
129
+
130
+ if (match) {
131
+ const oldObjectStr = match[1];
132
+
133
+
134
+ const edits = modify(
135
+ oldObjectStr,
136
+ [name],
137
+ [name + ".translations[en-US]"],
138
+ options,
139
+ );
140
+ let newObjectStr = applyEdits(oldObjectStr, edits);
141
+
142
+ const newContent = content.replace(oldObjectStr, newObjectStr);
143
+ tree.overwrite(path, newContent);
144
+
145
+ context.logger.info(`✅ Importado ${name}"`);
146
+ }
147
+ };
148
+ }*/
153
149
  //# sourceMappingURL=index.js.map