@barcidev/ngx-autogen 0.1.25 → 0.1.27

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.25",
3
+ "version": "0.1.27",
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;
@@ -15,136 +15,134 @@ const tasks_1 = require("@angular-devkit/schematics/tasks");
15
15
  const dependencies_1 = require("@schematics/angular/utility/dependencies");
16
16
  const workspace_1 = require("@schematics/angular/utility/workspace");
17
17
  const path_1 = require("path");
18
- const jsonc_parser_1 = require("jsonc-parser");
19
18
  const file_actions_1 = require("../common/file-actions");
20
19
  const pluralize_1 = require("../common/pluralize");
21
20
  /**
22
- * Lógica principal del Schematic
21
+ * Schematic principal para configurar Transloco en un componente específico
23
22
  */
24
23
  function transloco(options) {
25
- return (tree) => __awaiter(this, void 0, void 0, function* () {
26
- const workspace = yield (0, workspace_1.getWorkspace)(tree);
27
- const { project, projectName } = getProjectConfiguration(workspace, options);
28
- const { path, componentFile, componentName } = resolveComponentContext(tree, options);
29
- // Actualizamos las opciones con los valores calculados para las siguientes reglas
30
- const finalOptions = Object.assign(Object.assign({}, options), { project: projectName, path, name: componentName });
31
- return (0, schematics_1.chain)([
32
- setupGlobalConfig(),
33
- generateI18nFiles(finalOptions),
34
- updateAppI18nType(project.root || "src", `${schematics_1.strings.camelize(componentName)}I18n`, `${path}/${schematics_1.strings.dasherize(componentName)}.i18n`),
35
- registerProviderInComponent(finalOptions, componentFile),
36
- ]);
37
- });
38
- }
39
- /**
40
- * --- FUNCIONES HELPER (PURAS O DE CONFIGURACIÓN) ---
41
- */
42
- function getProjectConfiguration(workspace, options) {
43
- const projectName = options.project ||
44
- workspace.extensions.defaultProject ||
45
- Array.from(workspace.projects.keys())[0];
46
- const project = workspace.projects.get(projectName);
47
- if (!project)
48
- throw new schematics_1.SchematicsException(`El proyecto "${projectName}" no existe.`);
49
- return { project, projectName };
50
- }
51
- function resolveComponentContext(tree, options) {
52
- const fullPath = process.cwd();
53
- const srcIndex = fullPath.lastIndexOf("src");
54
- const path = (0, path_1.normalize)(srcIndex !== -1
55
- ? fullPath.substring(srcIndex)
56
- : (0, path_1.join)((0, path_1.normalize)("src"), "app"));
57
- const directory = tree.getDir(path);
58
- const componentFile = directory.subfiles.find((f) => f.endsWith(".component.ts")) ||
59
- directory.subfiles.find((f) => f.endsWith(".ts"));
60
- if (!componentFile && !options.name) {
61
- throw new schematics_1.SchematicsException("❌ No se encontró un componente y no se proveyó un --name.");
62
- }
63
- const componentName = componentFile
64
- ? componentFile.replace(".component.ts", "").replace(".ts", "")
65
- : options.name;
66
- return { path, componentFile, componentName };
67
- }
68
- /**
69
- * --- REGLAS (RULES) ---
70
- */
71
- function setupGlobalConfig() {
72
- return (tree, context) => {
24
+ return (tree, _context) => __awaiter(this, void 0, void 0, function* () {
73
25
  var _a;
74
- const appConfigPath = "src/app/app.config.ts";
75
- const content = ((_a = tree.read(appConfigPath)) === null || _a === void 0 ? void 0 : _a.toString()) || "";
76
- if (content.includes("provideTransloco"))
77
- return tree;
78
- context.logger.info("📦 Configurando dependencias globales de Transloco...");
79
- (0, dependencies_1.addPackageJsonDependency)(tree, {
80
- type: dependencies_1.NodeDependencyType.Default,
81
- name: "@jsverse/transloco",
82
- version: "^8.0.0",
83
- });
84
- context.addTask(new tasks_1.NodePackageInstallTask());
85
- return (0, schematics_1.chain)([
86
- (0, schematics_1.externalSchematic)("@barcidev/typed-transloco", "ng-add", {}),
87
- ]);
88
- };
89
- }
90
- function generateI18nFiles(options) {
91
- return (0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)("./files/component"), [
92
- (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) })),
93
- (0, schematics_1.move)(options.path),
94
- ]));
95
- }
96
- function updateAppI18nType(root, name, importPath) {
97
- return (tree, context) => {
98
- const path = `${root}/app/i18n/app.i18n.ts`;
99
- const buffer = tree.read(path);
100
- if (!buffer) {
101
- context.logger.warn(`⚠️ No se encontró el archivo ${path}`);
102
- return tree;
26
+ // --- 1. CONFIGURACIÓN INICIAL Y WORKSPACE ---
27
+ const workspace = yield (0, workspace_1.getWorkspace)(tree);
28
+ if (!options.project) {
29
+ options.project =
30
+ workspace.extensions.defaultProject ||
31
+ Array.from(workspace.projects.keys())[0];
103
32
  }
104
- let content = buffer.toString();
105
- const importStatement = `import { ${name} } from '${importPath}';\n`;
106
- // 1. AGREGAR EL IMPORT (si no existe ya)
107
- if (!content.includes(importPath)) {
108
- content = importStatement + content;
33
+ const project = workspace.projects.get(options.project);
34
+ if (!project) {
35
+ throw new schematics_1.SchematicsException(`El proyecto "${options.project}" no existe.`);
109
36
  }
110
- // 2. ACTUALIZAR EL OBJETO appI18n
111
- const options = {
112
- formattingOptions: { insertSpaces: true, tabSize: 2 },
113
- };
114
- // Buscamos el bloque del objeto appI18n
115
- const regex = /const\s+appI18n\s*=\s*(\{[\s\S]*?\});/;
116
- const match = content.match(regex);
117
- if (match) {
118
- const oldObjectStr = match[1];
119
- /**
120
- * Usamos jsonc-parser sobre el fragmento del objeto.
121
- * Nota: Pasamos la variableName como referencia (string sin comillas en el valor final)
122
- * Para que TS lo reconozca como la variable importada y no como un string,
123
- * hacemos un pequeño truco de reemplazo después de modificar.
124
- */
125
- const edits = (0, jsonc_parser_1.modify)(oldObjectStr, [name], [name + ".translations[en-US]"], options);
126
- let newObjectStr = (0, jsonc_parser_1.applyEdits)(oldObjectStr, edits);
127
- const newContent = content.replace(oldObjectStr, newObjectStr);
128
- tree.overwrite(path, newContent);
129
- context.logger.info(`✅ Importado ${name}"`);
37
+ // --- 2. DETERMINACIÓN DE RUTAS Y DETECCIÓN DE COMPONENTE ---
38
+ // Resolvemos el path relativo (src/app/...) basado en el directorio de ejecución
39
+ const fullPath = process.cwd();
40
+ const srcIndex = fullPath.lastIndexOf("src");
41
+ const relativePath = srcIndex !== -1
42
+ ? fullPath.substring(srcIndex)
43
+ : (0, path_1.join)((0, path_1.normalize)("src"), "app");
44
+ options.path = (0, path_1.normalize)(relativePath);
45
+ const directory = tree.getDir(options.path);
46
+ // Buscamos el archivo .ts principal del directorio
47
+ const componentFile = directory.subfiles.find((f) => f.endsWith(".component.ts")) ||
48
+ directory.subfiles.find((f) => f.endsWith(".ts"));
49
+ if (!componentFile && !options.name) {
50
+ throw new schematics_1.SchematicsException("❌ No se encontró un archivo .ts en este directorio y no se proveyó un --name.");
130
51
  }
131
- return tree;
132
- };
133
- }
134
- function registerProviderInComponent(options, componentFile) {
135
- if (!componentFile)
136
- return (tree) => tree;
137
- const componentPath = (0, path_1.join)(options.path, componentFile);
138
- const i18nConstantName = `${schematics_1.strings.camelize(options.name)}I18n`;
139
- return (0, file_actions_1.addProviderToStandaloneComponent)(componentPath, `provideTranslocoScopeWrapper(${i18nConstantName})`, [
140
- {
141
- symbol: `provideTranslocoScopeWrapper`,
142
- path: `@barcidev/typed-transloco`,
143
- },
144
- {
145
- symbol: i18nConstantName,
146
- path: `./${schematics_1.strings.dasherize(options.name)}.i18n`,
147
- },
148
- ]);
52
+ // Normalizamos el nombre (ej. mi-componente.component -> mi-componente)
53
+ options.name = componentFile
54
+ ? componentFile.replace(".component.ts", "").replace(".ts", "")
55
+ : options.name;
56
+ const rules = [
57
+ (0, schematics_1.externalSchematic)("@barcidev/typed-transloco", "ng-add", {}),
58
+ ];
59
+ // --- 3. CONFIGURACIÓN GLOBAL (IDEMPOTENTE) ---
60
+ const appConfigPath = "src/app/app.config.ts";
61
+ const appConfigContent = ((_a = tree.read(appConfigPath)) === null || _a === void 0 ? void 0 : _a.toString()) || "";
62
+ if (!appConfigContent.includes("provideTransloco")) {
63
+ _context.logger.info("📦 Transloco no detectado. Configurando globalmente...");
64
+ // Dependencias y tarea de instalación
65
+ rules.push((host) => {
66
+ (0, dependencies_1.addPackageJsonDependency)(host, {
67
+ type: dependencies_1.NodeDependencyType.Default,
68
+ name: "@jsverse/transloco",
69
+ version: "^7.0.0",
70
+ });
71
+ _context.addTask(new tasks_1.NodePackageInstallTask());
72
+ return host;
73
+ });
74
+ }
75
+ // --- 4. GENERACIÓN DE ARCHIVOS I18N DEL COMPONENTE ---
76
+ rules.push((0, schematics_1.mergeWith)((0, schematics_1.apply)((0, schematics_1.url)("./files/component"), [
77
+ (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) })),
78
+ (0, schematics_1.move)(options.path),
79
+ ])));
80
+ // --- 5. REGISTRO DEL SCOPE EN EL COMPONENTE ---
81
+ if (componentFile) {
82
+ const componentPath = (0, path_1.join)(options.path, componentFile);
83
+ const i18nConstantName = `${schematics_1.strings.camelize(options.name)}I18n`;
84
+ rules.push((0, file_actions_1.addProviderToStandaloneComponent)(componentPath, `provideTranslocoScopeWrapper(${i18nConstantName})`, [
85
+ {
86
+ symbol: `provideTranslocoScopeWrapper`,
87
+ path: `@barcidev/typed-transloco`,
88
+ },
89
+ {
90
+ symbol: i18nConstantName,
91
+ path: `./${schematics_1.strings.dasherize(options.name)}.i18n`,
92
+ },
93
+ ]));
94
+ }
95
+ return (0, schematics_1.chain)(rules);
96
+ });
149
97
  }
98
+ /*function updateAppI18nType(
99
+ root: string,
100
+ name: string,
101
+ importPath: string,
102
+ ): Rule {
103
+ return (tree: Tree, context: SchematicContext) => {
104
+ const path = `${root}/app/i18n/app.i18n.ts`;
105
+ const buffer = tree.read(path);
106
+
107
+ if (!buffer) {
108
+ context.logger.warn(`⚠️ No se encontró el archivo ${path}`);
109
+ return tree;
110
+ }
111
+
112
+ let content = buffer.toString();
113
+ const importStatement = `import { ${name} } from '${importPath}';\n`;
114
+
115
+ // 1. AGREGAR EL IMPORT (si no existe ya)
116
+ if (!content.includes(importPath)) {
117
+ content = importStatement + content;
118
+ }
119
+
120
+ // 2. ACTUALIZAR EL OBJETO appI18n
121
+ const options: ModificationOptions = {
122
+ formattingOptions: { insertSpaces: true, tabSize: 2 },
123
+ };
124
+
125
+ // Buscamos el bloque del objeto appI18n
126
+ const regex = /const\s+appI18n\s*=\s*(\{[\s\S]*?\});/;
127
+ const match = content.match(regex);
128
+
129
+ if (match) {
130
+ const oldObjectStr = match[1];
131
+
132
+
133
+ const edits = modify(
134
+ oldObjectStr,
135
+ [name],
136
+ [name + ".translations[en-US]"],
137
+ options,
138
+ );
139
+ let newObjectStr = applyEdits(oldObjectStr, edits);
140
+
141
+ const newContent = content.replace(oldObjectStr, newObjectStr);
142
+ tree.overwrite(path, newContent);
143
+
144
+ context.logger.info(`✅ Importado ${name}"`);
145
+ }
146
+ };
147
+ }*/
150
148
  //# sourceMappingURL=index.js.map