@solercia/ui 0.3.1 → 0.4.0
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/fesm2022/solercia-ui.mjs +126 -7
- package/fesm2022/solercia-ui.mjs.map +1 -1
- package/package.json +1 -1
- package/schematics/collection.json +34 -0
- package/schematics/entity/files/api/__name__-api.service.ts.template +51 -0
- package/schematics/entity/files/index.ts.template +2 -0
- package/schematics/entity/files/model/__name__.model.ts.template +16 -0
- package/schematics/entity/index.js +40 -0
- package/schematics/entity/schema.json +19 -0
- package/schematics/feature/files/index.ts.template +1 -0
- package/schematics/feature/files/ui/__name__.component.ts.template +41 -0
- package/schematics/feature/index.js +40 -0
- package/schematics/feature/schema.json +19 -0
- package/schematics/migrations/1-noop/index.js +19 -0
- package/schematics/migrations.json +10 -0
- package/schematics/ng-add/index.js +340 -0
- package/schematics/ng-add/schema.json +18 -0
- package/schematics/package.json +3 -0
- package/schematics/page/files/__name__.routes.ts.template +6 -0
- package/schematics/page/files/index.ts.template +2 -0
- package/schematics/page/files/ui/__name__-page.component.ts.template +31 -0
- package/schematics/page/index.js +38 -0
- package/schematics/page/schema.json +19 -0
- package/schematics/utils.js +127 -0
- package/schematics/widget/files/index.ts.template +1 -0
- package/schematics/widget/files/ui/__name__.component.ts.template +54 -0
- package/schematics/widget/index.js +40 -0
- package/schematics/widget/schema.json +19 -0
- package/types/solercia-ui.d.ts +38 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@solercia/ui",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Design system Solercia (componentes sol-*, theming agnóstico por puertos, contrato i18n y schematics ng add/ng generate) para proyectos Angular del ecosistema Solercia.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Solercia Solutions SAS",
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "../../../../node_modules/@angular-devkit/schematics/collection-schema.json",
|
|
3
|
+
"schematics": {
|
|
4
|
+
"ng-add": {
|
|
5
|
+
"description": "Scaffoldea el andamiaje FSD (carpetas + index.ts, path aliases, tokens + estilos, providers de los puertos de theming/i18n, @solercia/eslint-config y Husky) en un proyecto Angular consumidor.",
|
|
6
|
+
"factory": "./ng-add/index#ngAdd",
|
|
7
|
+
"schema": "./ng-add/schema.json"
|
|
8
|
+
},
|
|
9
|
+
"page": {
|
|
10
|
+
"aliases": ["p"],
|
|
11
|
+
"description": "Genera una page FSD (standalone, OnPush, claves i18n) en <sourceRoot>/pages/.",
|
|
12
|
+
"factory": "./page/index#page",
|
|
13
|
+
"schema": "./page/schema.json"
|
|
14
|
+
},
|
|
15
|
+
"feature": {
|
|
16
|
+
"aliases": ["f"],
|
|
17
|
+
"description": "Genera una feature FSD (standalone, OnPush, signals input()/output(), claves i18n) en <sourceRoot>/features/.",
|
|
18
|
+
"factory": "./feature/index#feature",
|
|
19
|
+
"schema": "./feature/schema.json"
|
|
20
|
+
},
|
|
21
|
+
"entity": {
|
|
22
|
+
"aliases": ["e"],
|
|
23
|
+
"description": "Genera una entity FSD (model + api) en <sourceRoot>/entities/.",
|
|
24
|
+
"factory": "./entity/index#entity",
|
|
25
|
+
"schema": "./entity/schema.json"
|
|
26
|
+
},
|
|
27
|
+
"widget": {
|
|
28
|
+
"aliases": ["w"],
|
|
29
|
+
"description": "Genera un widget FSD (standalone, OnPush, signals, claves i18n) en <sourceRoot>/widgets/.",
|
|
30
|
+
"factory": "./widget/index#widget",
|
|
31
|
+
"schema": "./widget/schema.json"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { Injectable, inject } from '@angular/core';
|
|
2
|
+
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
|
3
|
+
import { Observable, throwError } from 'rxjs';
|
|
4
|
+
import { catchError } from 'rxjs/operators';
|
|
5
|
+
import { APP_CONSTANTS } from '@shared/config';
|
|
6
|
+
import { ApiSuccessResponse, CustomError } from '@shared/api';
|
|
7
|
+
import { <%= className %>, Create<%= className %>Request } from '../model/<%= name %>.model';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Cliente REST de <%= className %>, generado por
|
|
11
|
+
* `ng g @solercia/ui:entity <%= name %>`. CRUD mínimo contra
|
|
12
|
+
* `${APP_CONSTANTS.apiBaseUrl}/<%= pluralName %>` — calcado del molde real
|
|
13
|
+
* (`src/entities/tag/api/tag-api.service.ts`).
|
|
14
|
+
*/
|
|
15
|
+
@Injectable({ providedIn: 'root' })
|
|
16
|
+
export class <%= className %>ApiService {
|
|
17
|
+
private http = inject(HttpClient);
|
|
18
|
+
private baseUrl = `${APP_CONSTANTS.apiBaseUrl}/<%= pluralName %>`;
|
|
19
|
+
|
|
20
|
+
getAll(): Observable<ApiSuccessResponse<<%= className %>[]>> {
|
|
21
|
+
return this.http
|
|
22
|
+
.get<ApiSuccessResponse<<%= className %>[]>>(this.baseUrl)
|
|
23
|
+
.pipe(catchError(this.handleError));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
create(data: Create<%= className %>Request): Observable<ApiSuccessResponse<<%= className %>>> {
|
|
27
|
+
return this.http
|
|
28
|
+
.post<ApiSuccessResponse<<%= className %>>>(this.baseUrl, data)
|
|
29
|
+
.pipe(catchError(this.handleError));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
update(id: number, data: Partial<Create<%= className %>Request>): Observable<ApiSuccessResponse<<%= className %>>> {
|
|
33
|
+
return this.http
|
|
34
|
+
.put<ApiSuccessResponse<<%= className %>>>(`${this.baseUrl}/${id}`, data)
|
|
35
|
+
.pipe(catchError(this.handleError));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
delete(id: number): Observable<ApiSuccessResponse<void>> {
|
|
39
|
+
return this.http
|
|
40
|
+
.delete<ApiSuccessResponse<void>>(`${this.baseUrl}/${id}`)
|
|
41
|
+
.pipe(catchError(this.handleError));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private handleError(error: HttpErrorResponse): Observable<never> {
|
|
45
|
+
const customError: CustomError = new Error(error.error?.message ?? 'Error desconocido') as CustomError;
|
|
46
|
+
customError.code = error.error?.errors?.[0]?.code ?? 'UNKNOWN';
|
|
47
|
+
customError.status = error.status;
|
|
48
|
+
customError.originalError = error;
|
|
49
|
+
return throwError(() => customError);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Modelo de dominio de <%= className %>, generado por
|
|
3
|
+
* `ng g @solercia/ui:entity <%= name %>`.
|
|
4
|
+
*
|
|
5
|
+
* Los nombres de campo siguen el contrato PascalCase que expone el backend
|
|
6
|
+
* (.NET) — ajusta a la forma real del DTO (ver `src/entities/tag/model/` en
|
|
7
|
+
* boki-front para un ejemplo completo con validators).
|
|
8
|
+
*/
|
|
9
|
+
export interface <%= className %> {
|
|
10
|
+
Id: number;
|
|
11
|
+
VcName: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface Create<%= className %>Request {
|
|
15
|
+
VcName: string;
|
|
16
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.entity = entity;
|
|
4
|
+
const schematics_1 = require("@angular-devkit/schematics");
|
|
5
|
+
const utils_1 = require("../utils");
|
|
6
|
+
/**
|
|
7
|
+
* `ng g @solercia/ui:entity <name>` — crea `<sourceRoot>/entities/<name>/`
|
|
8
|
+
* con `model/<name>.model.ts` (interfaz de dominio) y `api/<name>-api.service.ts`
|
|
9
|
+
* (CRUD REST sobre `APP_CONSTANTS.apiBaseUrl`), calcado del molde real
|
|
10
|
+
* (`src/entities/tag/`). Las entities NO tienen componentes: la capa `entities`
|
|
11
|
+
* solo modela dominio + acceso a datos (CONVENCIONES-FRONT-SOLERCIA §4).
|
|
12
|
+
*
|
|
13
|
+
* Actualiza (idempotente) el barrel agregador `<sourceRoot>/entities/index.ts`
|
|
14
|
+
* además del `index.ts` propio de la carpeta nueva.
|
|
15
|
+
*/
|
|
16
|
+
function entity(options) {
|
|
17
|
+
return async (tree, context) => {
|
|
18
|
+
if (!options.name?.trim()) {
|
|
19
|
+
throw new Error('El schematic "entity" requiere un nombre, ej. `ng g @solercia/ui:entity tag`.');
|
|
20
|
+
}
|
|
21
|
+
const sourceRoot = await (0, utils_1.resolveSourceRoot)(tree, options.project);
|
|
22
|
+
const name = (0, utils_1.toDasherized)(options.name);
|
|
23
|
+
const className = (0, utils_1.toClassName)(options.name);
|
|
24
|
+
const pluralName = (0, utils_1.toPluralKebab)(options.name);
|
|
25
|
+
const targetDir = `${sourceRoot}/entities/${name}`;
|
|
26
|
+
const templateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files'), [
|
|
27
|
+
(0, schematics_1.applyTemplates)({ name, className, pluralName }),
|
|
28
|
+
(0, schematics_1.move)(targetDir),
|
|
29
|
+
]);
|
|
30
|
+
context.logger.info(`[@solercia/ui] Entity "${name}" creada en ${targetDir}/ (recurso REST /${pluralName}). ` +
|
|
31
|
+
`Ajusta los campos del modelo al contrato real del backend.`);
|
|
32
|
+
return (0, schematics_1.chain)([
|
|
33
|
+
(0, schematics_1.mergeWith)(templateSource),
|
|
34
|
+
(host) => {
|
|
35
|
+
(0, utils_1.appendToLayerBarrel)(host, `${sourceRoot}/entities/index.ts`, `export type { ${className}, Create${className}Request } from './${name}';\nexport { ${className}ApiService } from './${name}';`);
|
|
36
|
+
return host;
|
|
37
|
+
},
|
|
38
|
+
]);
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema",
|
|
3
|
+
"$id": "SolerciaUiEntity",
|
|
4
|
+
"title": "Solercia UI entity schematic",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"properties": {
|
|
7
|
+
"name": {
|
|
8
|
+
"type": "string",
|
|
9
|
+
"description": "Nombre de la entity (kebab-case recomendado, ej. \"tag\").",
|
|
10
|
+
"$default": { "$source": "argv", "index": 0 }
|
|
11
|
+
},
|
|
12
|
+
"project": {
|
|
13
|
+
"type": "string",
|
|
14
|
+
"description": "Proyecto Angular objetivo. Por defecto, el proyecto de tipo application del workspace.",
|
|
15
|
+
"$default": { "$source": "projectName" }
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"required": ["name"]
|
|
19
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { <%= className %>Component } from './ui/<%= name %>.component';
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Component, ChangeDetectionStrategy, input, output, inject } from '@angular/core';
|
|
2
|
+
import { I18nService } from '@shared/i18n';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Feature generada por `ng g @solercia/ui:feature <%= name %>`.
|
|
6
|
+
*
|
|
7
|
+
* Standalone + `OnPush` + signals (`input()`/`output()`) + textos por clave
|
|
8
|
+
* i18n (`features.<%= camelName %>.*`), calcado del molde de `@solercia/ui`
|
|
9
|
+
* (ver `src/features/auth/ui/login-form.component.ts` en boki-front).
|
|
10
|
+
*/
|
|
11
|
+
@Component({
|
|
12
|
+
standalone: true,
|
|
13
|
+
selector: '<%= selector %>',
|
|
14
|
+
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
15
|
+
template: `
|
|
16
|
+
<div class="<%= name %>">
|
|
17
|
+
<span>{{ titleLabel() }}</span>
|
|
18
|
+
@if (value()) {
|
|
19
|
+
<span class="<%= name %>__value">{{ value() }}</span>
|
|
20
|
+
}
|
|
21
|
+
</div>
|
|
22
|
+
`,
|
|
23
|
+
styles: [`
|
|
24
|
+
.<%= name %> {
|
|
25
|
+
display: flex;
|
|
26
|
+
align-items: center;
|
|
27
|
+
gap: var(--sol-space-sm, 8px);
|
|
28
|
+
font-family: var(--sol-font-family);
|
|
29
|
+
color: var(--sol-color-text-primary);
|
|
30
|
+
}
|
|
31
|
+
`],
|
|
32
|
+
})
|
|
33
|
+
export class <%= className %>Component {
|
|
34
|
+
private readonly i18n = inject(I18nService);
|
|
35
|
+
|
|
36
|
+
/** Ajusta el tipo/valor por defecto al contrato real de la feature. */
|
|
37
|
+
readonly value = input<string>('');
|
|
38
|
+
readonly changed = output<string>();
|
|
39
|
+
|
|
40
|
+
readonly titleLabel = this.i18n.t('features.<%= camelName %>.title');
|
|
41
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.feature = feature;
|
|
4
|
+
const schematics_1 = require("@angular-devkit/schematics");
|
|
5
|
+
const utils_1 = require("../utils");
|
|
6
|
+
/**
|
|
7
|
+
* `ng g @solercia/ui:feature <name>` — crea `<sourceRoot>/features/<name>/`
|
|
8
|
+
* con un componente standalone `OnPush` con signals (`input()`/`output()`),
|
|
9
|
+
* calcado del molde real (`src/features/auth/ui/login-form.component.ts`):
|
|
10
|
+
* selector `sol-<name>`, clase `<Name>Component`, textos por
|
|
11
|
+
* `I18nService.t('features.<camelName>.*')`.
|
|
12
|
+
*
|
|
13
|
+
* Actualiza (idempotente) el barrel agregador `<sourceRoot>/features/index.ts`
|
|
14
|
+
* además del `index.ts` propio de la carpeta nueva.
|
|
15
|
+
*/
|
|
16
|
+
function feature(options) {
|
|
17
|
+
return async (tree, context) => {
|
|
18
|
+
if (!options.name?.trim()) {
|
|
19
|
+
throw new Error('El schematic "feature" requiere un nombre, ej. `ng g @solercia/ui:feature manage-tags`.');
|
|
20
|
+
}
|
|
21
|
+
const sourceRoot = await (0, utils_1.resolveSourceRoot)(tree, options.project);
|
|
22
|
+
const name = (0, utils_1.toDasherized)(options.name);
|
|
23
|
+
const className = (0, utils_1.toClassName)(options.name);
|
|
24
|
+
const camelName = (0, utils_1.toCamelCase)(options.name);
|
|
25
|
+
const selector = `sol-${name}`;
|
|
26
|
+
const targetDir = `${sourceRoot}/features/${name}`;
|
|
27
|
+
(0, utils_1.upsertI18nKey)(tree, context, 'features', camelName, 'title', className, `${sourceRoot}/assets/i18n/es-CO.json`);
|
|
28
|
+
const templateSource = (0, schematics_1.apply)((0, schematics_1.url)('./files'), [
|
|
29
|
+
(0, schematics_1.applyTemplates)({ name, className, camelName, selector }),
|
|
30
|
+
(0, schematics_1.move)(targetDir),
|
|
31
|
+
]);
|
|
32
|
+
return (0, schematics_1.chain)([
|
|
33
|
+
(0, schematics_1.mergeWith)(templateSource),
|
|
34
|
+
(host) => {
|
|
35
|
+
(0, utils_1.appendToLayerBarrel)(host, `${sourceRoot}/features/index.ts`, `export { ${className}Component } from './${name}';`);
|
|
36
|
+
return host;
|
|
37
|
+
},
|
|
38
|
+
]);
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema",
|
|
3
|
+
"$id": "SolerciaUiFeature",
|
|
4
|
+
"title": "Solercia UI feature schematic",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"properties": {
|
|
7
|
+
"name": {
|
|
8
|
+
"type": "string",
|
|
9
|
+
"description": "Nombre de la feature (kebab-case recomendado, ej. \"manage-tags\").",
|
|
10
|
+
"$default": { "$source": "argv", "index": 0 }
|
|
11
|
+
},
|
|
12
|
+
"project": {
|
|
13
|
+
"type": "string",
|
|
14
|
+
"description": "Proyecto Angular objetivo. Por defecto, el proyecto de tipo application del workspace.",
|
|
15
|
+
"$default": { "$source": "projectName" }
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"required": ["name"]
|
|
19
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.migrate = migrate;
|
|
4
|
+
/**
|
|
5
|
+
* Migración no-op de ejemplo (`ng update @solercia/ui` a 0.1.0). Sienta el
|
|
6
|
+
* andamiaje/convención para futuras migraciones reales — p. ej. cuando un
|
|
7
|
+
* `ng update` mayor renombre un token `--sol-*` o un `input()` de un
|
|
8
|
+
* componente `sol-*`, esta carpeta es el molde: cada versión con migración
|
|
9
|
+
* agrega su propia entrada a `migrations.json` con un factory dedicado.
|
|
10
|
+
*
|
|
11
|
+
* Ver diseño (Decisión B): lo que evoluciona en la librería se propaga por
|
|
12
|
+
* `ng update`, no por re-clonado (anti-patrón `modbase`).
|
|
13
|
+
*/
|
|
14
|
+
function migrate() {
|
|
15
|
+
return (tree) => {
|
|
16
|
+
// Intencionalmente no-op: no hay cambios que migrar en 0.1.0.
|
|
17
|
+
return tree;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "../../../../node_modules/@angular-devkit/schematics/collection-schema.json",
|
|
3
|
+
"schematics": {
|
|
4
|
+
"migration-0-1-0-noop": {
|
|
5
|
+
"version": "0.1.0",
|
|
6
|
+
"description": "Andamiaje de migraciones para `ng update @solercia/ui`. No-op: sienta la convención para futuros renombres de tokens/inputs propagables (ver design.md, Decisión B — herencia por dependencia).",
|
|
7
|
+
"factory": "./migrations/1-noop/index#migrate"
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ngAdd = ngAdd;
|
|
4
|
+
const schematics_1 = require("@angular-devkit/schematics");
|
|
5
|
+
const utility_1 = require("@schematics/angular/utility");
|
|
6
|
+
const json_file_1 = require("@schematics/angular/utility/json-file");
|
|
7
|
+
const utils_1 = require("../utils");
|
|
8
|
+
/** Alias FSD fijos del ecosistema Solercia (CONVENCIONES-FRONT-SOLERCIA.md).
|
|
9
|
+
* Prefijo `./` explícito (fix TS5090): un `tsconfig.json` de `ng new` NO
|
|
10
|
+
* define `baseUrl`, así que una entrada de `paths` sin `./` (p. ej.
|
|
11
|
+
* `"src/pages/*"`) queda ambigua para el compilador y falla con
|
|
12
|
+
* `TS5090 (non-relative paths are not allowed when 'baseUrl' is not set)`. */
|
|
13
|
+
function fsdPathAliases(sourceRoot) {
|
|
14
|
+
return {
|
|
15
|
+
'@app/*': [`./${sourceRoot}/app/*`],
|
|
16
|
+
'@pages/*': [`./${sourceRoot}/pages/*`],
|
|
17
|
+
'@widgets/*': [`./${sourceRoot}/widgets/*`],
|
|
18
|
+
'@features/*': [`./${sourceRoot}/features/*`],
|
|
19
|
+
'@entities/*': [`./${sourceRoot}/entities/*`],
|
|
20
|
+
'@shared/*': [`./${sourceRoot}/shared/*`],
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* `ng add @solercia/ui` — scaffoldea el andamiaje FSD en un proyecto Angular
|
|
25
|
+
* standalone recién creado (`ng new`): carpetas `pages/widgets/features/entities`
|
|
26
|
+
* (con sus `index.ts` agregadores) + `shared/tokens` (adaptadores de los
|
|
27
|
+
* puertos de theming/tenant de `@solercia/ui`) + `shared/i18n` (adaptador del
|
|
28
|
+
* puerto `SOL_I18N`, consumido también por los schematics `page/feature/widget`),
|
|
29
|
+
* path aliases en `tsconfig.json`, `provideTheme()` cableado real en
|
|
30
|
+
* `app.config.ts`, `@solercia/eslint-config` instalada como `devDependency` y
|
|
31
|
+
* Husky + lint-staged + commitlint.
|
|
32
|
+
*
|
|
33
|
+
* Alcance deliberado (ver `openspec/07-e9-extraccion-solercia-ui/design.md`,
|
|
34
|
+
* Decisión A): `@solercia/ui` expone puertos (`THEME_SOURCE`, `SOL_TENANT_RESOLVER`,
|
|
35
|
+
* `SOL_I18N`) con defaults null-object `providedIn: 'root'` — un proyecto recién
|
|
36
|
+
* scaffoldeado YA renderiza con el tema por defecto de la librería sin wiring
|
|
37
|
+
* adicional. `ng-add` deja los ADAPTADORES listos en `shared/tokens/` y
|
|
38
|
+
* `shared/i18n/` (con TODO) para cuando el consumidor tenga backend/tenant/motor
|
|
39
|
+
* i18n real, en vez de inventar una llamada HTTP falsa que rompería un `ng new`
|
|
40
|
+
* limpio.
|
|
41
|
+
*/
|
|
42
|
+
function ngAdd(options) {
|
|
43
|
+
return async (tree, context) => {
|
|
44
|
+
const projectName = await (0, utils_1.resolveProjectName)(tree, options.project);
|
|
45
|
+
const sourceRoot = await (0, utils_1.resolveSourceRoot)(tree, options.project);
|
|
46
|
+
const rules = [
|
|
47
|
+
scaffoldFsdLayers(sourceRoot),
|
|
48
|
+
scaffoldThemeAdapters(sourceRoot),
|
|
49
|
+
scaffoldI18nAdapter(sourceRoot),
|
|
50
|
+
wireTsconfigPaths(sourceRoot),
|
|
51
|
+
appendGlobalStyles(sourceRoot, context),
|
|
52
|
+
scaffoldEslintConfig(context),
|
|
53
|
+
scaffoldHusky(context),
|
|
54
|
+
];
|
|
55
|
+
// provideTheme() es la ÚNICA pieza que se puede cablear con seguridad vía
|
|
56
|
+
// AST en CUALQUIER `ng new` estándar (import de paquete, sin rutas
|
|
57
|
+
// relativas frágiles): activa el runtime de theming de @solercia/ui
|
|
58
|
+
// (aplica SOL_DEFAULT_THEME de inmediato).
|
|
59
|
+
if (projectName) {
|
|
60
|
+
rules.push((0, utility_1.addRootProvider)(projectName, ({ code, external }) => {
|
|
61
|
+
return code `${external('provideTheme', '@solercia/ui')}()`;
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
context.logger.warn('[@solercia/ui] No se encontró angular.json — se omite el cableado automático de ' +
|
|
66
|
+
'provideTheme() en app.config.ts. Agrégalo a mano: providers: [provideTheme(), ...].');
|
|
67
|
+
}
|
|
68
|
+
// devDependencies que SÍ existen en un registry público — `addDependency`
|
|
69
|
+
// ya agenda su propia NodePackageInstallTask (una sola, deduplicada) salvo
|
|
70
|
+
// `skipInstall`. `@solercia/eslint-config` está publicado desde 0.1.1 (npm
|
|
71
|
+
// público) y es el preset que referencia el `eslint.config.{js,mjs}`
|
|
72
|
+
// scaffoldeado por `scaffoldEslintConfig`.
|
|
73
|
+
const installBehavior = options.skipInstall ? utility_1.InstallBehavior.None : utility_1.InstallBehavior.Auto;
|
|
74
|
+
return (0, schematics_1.chain)([
|
|
75
|
+
...rules,
|
|
76
|
+
(0, utility_1.addDependency)('@solercia/eslint-config', '^0.1.1', {
|
|
77
|
+
type: utility_1.DependencyType.Dev,
|
|
78
|
+
install: installBehavior,
|
|
79
|
+
}),
|
|
80
|
+
(0, utility_1.addDependency)('husky', '^9.1.7', { type: utility_1.DependencyType.Dev, install: installBehavior }),
|
|
81
|
+
(0, utility_1.addDependency)('lint-staged', '^17.0.8', { type: utility_1.DependencyType.Dev, install: installBehavior }),
|
|
82
|
+
(0, utility_1.addDependency)('@commitlint/cli', '^21.2.1', { type: utility_1.DependencyType.Dev, install: installBehavior }),
|
|
83
|
+
(0, utility_1.addDependency)('@commitlint/config-conventional', '^21.2.0', {
|
|
84
|
+
type: utility_1.DependencyType.Dev,
|
|
85
|
+
install: installBehavior,
|
|
86
|
+
}),
|
|
87
|
+
]);
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** Carpetas FSD con su `index.ts` agregador (vacío salvo el comentario de capa,
|
|
91
|
+
* calcado de `src/{pages,widgets,features,entities}/index.ts` reales). `pages/`
|
|
92
|
+
* NUNCA reexporta slices (lazy-loading por ruta) — las otras 3 capas sí. */
|
|
93
|
+
function scaffoldFsdLayers(sourceRoot) {
|
|
94
|
+
const layers = [
|
|
95
|
+
{ name: 'pages', comment: 'Pages layer — lazy-loaded route views' },
|
|
96
|
+
{ name: 'widgets', comment: 'Widgets layer — autonomous composed UI blocks' },
|
|
97
|
+
{ name: 'features', comment: 'Features layer — user actions with business value' },
|
|
98
|
+
{ name: 'entities', comment: 'Entities layer — domain models' },
|
|
99
|
+
];
|
|
100
|
+
return (tree) => {
|
|
101
|
+
for (const layer of layers) {
|
|
102
|
+
const indexPath = `/${sourceRoot}/${layer.name}/index.ts`;
|
|
103
|
+
if (!tree.exists(indexPath)) {
|
|
104
|
+
tree.create(indexPath, `// ${layer.comment}\n`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return tree;
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** Adaptadores mínimos de los puertos de `@solercia/ui` en `shared/tokens/`,
|
|
111
|
+
* listos para activarse cuando exista backend/tenant real. */
|
|
112
|
+
function scaffoldThemeAdapters(sourceRoot) {
|
|
113
|
+
return (tree) => {
|
|
114
|
+
const dir = `/${sourceRoot}/shared/tokens`;
|
|
115
|
+
const themeSourcePath = `${dir}/app-theme-source.ts`;
|
|
116
|
+
if (!tree.exists(themeSourcePath)) {
|
|
117
|
+
tree.create(themeSourcePath, `import { Injectable } from '@angular/core';\n` +
|
|
118
|
+
`import type { ThemeFile, ThemeSource } from '@solercia/ui';\n\n` +
|
|
119
|
+
`/**\n` +
|
|
120
|
+
` * Adaptador de THEME_SOURCE (puerto de @solercia/ui). Por defecto no resuelve\n` +
|
|
121
|
+
` * tema por tenant (retorna null → se aplica SOL_DEFAULT_THEME). Reemplaza el\n` +
|
|
122
|
+
` * cuerpo de loadTheme() por tu llamada real (HTTP, storage, etc.) cuando exista\n` +
|
|
123
|
+
` * backend multi-tenant. Cablea en app.config.ts:\n` +
|
|
124
|
+
` * { provide: THEME_SOURCE, useExisting: AppThemeSource }\n` +
|
|
125
|
+
` */\n` +
|
|
126
|
+
`@Injectable({ providedIn: 'root' })\n` +
|
|
127
|
+
`export class AppThemeSource implements ThemeSource {\n` +
|
|
128
|
+
` async loadTheme(_tenantId: number | string): Promise<ThemeFile | null> {\n` +
|
|
129
|
+
` return null;\n` +
|
|
130
|
+
` }\n` +
|
|
131
|
+
`}\n`);
|
|
132
|
+
}
|
|
133
|
+
const tenantResolverPath = `${dir}/app-tenant-resolver.ts`;
|
|
134
|
+
if (!tree.exists(tenantResolverPath)) {
|
|
135
|
+
tree.create(tenantResolverPath, `import { Injectable } from '@angular/core';\n` +
|
|
136
|
+
`import type { SolTenantResolver } from '@solercia/ui';\n\n` +
|
|
137
|
+
`/**\n` +
|
|
138
|
+
` * Adaptador de SOL_TENANT_RESOLVER (puerto de @solercia/ui). Por defecto no hay\n` +
|
|
139
|
+
` * tenant activo (tema único). Implementa tu resolución real (sesión, dominio,\n` +
|
|
140
|
+
` * slug) cuando exista multi-tenant. Cablea en app.config.ts:\n` +
|
|
141
|
+
` * { provide: SOL_TENANT_RESOLVER, useExisting: AppTenantResolver }\n` +
|
|
142
|
+
` */\n` +
|
|
143
|
+
`@Injectable({ providedIn: 'root' })\n` +
|
|
144
|
+
`export class AppTenantResolver implements SolTenantResolver {\n` +
|
|
145
|
+
` activeTenantId(): number | null {\n` +
|
|
146
|
+
` return null;\n` +
|
|
147
|
+
` }\n` +
|
|
148
|
+
`}\n`);
|
|
149
|
+
}
|
|
150
|
+
const indexPath = `${dir}/index.ts`;
|
|
151
|
+
if (!tree.exists(indexPath)) {
|
|
152
|
+
tree.create(indexPath, `export { AppThemeSource } from './app-theme-source';\n` +
|
|
153
|
+
`export { AppTenantResolver } from './app-tenant-resolver';\n`);
|
|
154
|
+
}
|
|
155
|
+
return tree;
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
/** Adaptador mínimo de `SOL_I18N` (puerto de `@solercia/ui`) en `shared/i18n/`.
|
|
159
|
+
* Fix TS2571: los schematics `page`/`feature`/`widget` de esta misma colección
|
|
160
|
+
* generan código que importa `I18nService` desde `@shared/i18n` — sin esta capa
|
|
161
|
+
* el proyecto horneado por el starter no compila. Por defecto es una identidad
|
|
162
|
+
* (retorna la clave sin traducir), igual que `createIdentitySolI18n()` de la
|
|
163
|
+
* librería; el consumidor reemplaza el cuerpo por su motor real (Transloco,
|
|
164
|
+
* ngx-translate, `@angular/localize`) cuando lo tenga — ver
|
|
165
|
+
* projects/solercia/ui/docs/I18N.md. */
|
|
166
|
+
function scaffoldI18nAdapter(sourceRoot) {
|
|
167
|
+
return (tree) => {
|
|
168
|
+
const dir = `/${sourceRoot}/shared/i18n`;
|
|
169
|
+
const servicePath = `${dir}/i18n.service.ts`;
|
|
170
|
+
if (!tree.exists(servicePath)) {
|
|
171
|
+
tree.create(servicePath, `import { Injectable, Signal, signal } from '@angular/core';\n` +
|
|
172
|
+
`import type { SolI18n } from '@solercia/ui';\n\n` +
|
|
173
|
+
`/**\n` +
|
|
174
|
+
` * Adaptador de SOL_I18N (puerto de @solercia/ui), consumido también por los\n` +
|
|
175
|
+
` * componentes que generan los schematics \`page\`/\`feature\`/\`widget\` de esta\n` +
|
|
176
|
+
` * misma colección (\`inject(I18nService)\`). Por defecto es una identidad\n` +
|
|
177
|
+
` * (retorna la clave sin traducir) — reemplaza el cuerpo por tu motor real\n` +
|
|
178
|
+
` * (Transloco, ngx-translate, @angular/localize) cuando el proyecto lo tenga.\n` +
|
|
179
|
+
` * Para que los propios componentes de @solercia/ui usen el mismo motor,\n` +
|
|
180
|
+
` * cablea en app.config.ts:\n` +
|
|
181
|
+
` * { provide: SOL_I18N, useExisting: I18nService }\n` +
|
|
182
|
+
` * (ver projects/solercia/ui/docs/I18N.md del monorepo).\n` +
|
|
183
|
+
` */\n` +
|
|
184
|
+
`@Injectable({ providedIn: 'root' })\n` +
|
|
185
|
+
`export class I18nService implements SolI18n {\n` +
|
|
186
|
+
` readonly activeLang: Signal<string> = signal('es-CO');\n\n` +
|
|
187
|
+
` translate(key: string, _params?: Record<string, unknown>): string {\n` +
|
|
188
|
+
` return key;\n` +
|
|
189
|
+
` }\n\n` +
|
|
190
|
+
` t(key: string, _params?: Record<string, unknown>): Signal<string> {\n` +
|
|
191
|
+
` return signal(key);\n` +
|
|
192
|
+
` }\n\n` +
|
|
193
|
+
` tMany(keys: string[]): Signal<string[]> {\n` +
|
|
194
|
+
` return signal(keys);\n` +
|
|
195
|
+
` }\n` +
|
|
196
|
+
`}\n`);
|
|
197
|
+
}
|
|
198
|
+
const indexPath = `${dir}/index.ts`;
|
|
199
|
+
if (!tree.exists(indexPath)) {
|
|
200
|
+
tree.create(indexPath, `export { I18nService } from './i18n.service';\n`);
|
|
201
|
+
}
|
|
202
|
+
return tree;
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
/** Path aliases FSD en `tsconfig.json` (edición segura vía JSONC AST — tolera
|
|
206
|
+
* comentarios/trailing commas, igual que el resto del tooling oficial Angular). */
|
|
207
|
+
function wireTsconfigPaths(sourceRoot) {
|
|
208
|
+
return (tree) => {
|
|
209
|
+
const tsconfigPath = '/tsconfig.json';
|
|
210
|
+
if (!tree.exists(tsconfigPath)) {
|
|
211
|
+
return tree;
|
|
212
|
+
}
|
|
213
|
+
const json = new json_file_1.JSONFile(tree, tsconfigPath);
|
|
214
|
+
for (const [alias, paths] of Object.entries(fsdPathAliases(sourceRoot))) {
|
|
215
|
+
json.modify(['compilerOptions', 'paths', alias], paths);
|
|
216
|
+
}
|
|
217
|
+
return tree;
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/** Snippet de estilos globales que demuestra el consumo de los tokens `--sol-*`
|
|
221
|
+
* (el resto de las 95 variables las emite ThemeService en runtime — ver
|
|
222
|
+
* projects/solercia/ui/docs/THEMING.md). Detecta tanto `styles.css` como
|
|
223
|
+
* `styles.scss` (fix: `ng new --style=scss` dejaba los tokens sin inyectar
|
|
224
|
+
* porque solo se comprobaba `styles.css`); el snippet usa comentarios estilo
|
|
225
|
+
* CSS de bloque, válidos también en SCSS. Si el proyecto no tiene ninguno de
|
|
226
|
+
* los dos archivos, solo avisa. */
|
|
227
|
+
function appendGlobalStyles(sourceRoot, context) {
|
|
228
|
+
return (tree) => {
|
|
229
|
+
const candidates = [`/${sourceRoot}/styles.css`, `/${sourceRoot}/styles.scss`];
|
|
230
|
+
const stylesPath = candidates.find((candidate) => tree.exists(candidate));
|
|
231
|
+
if (!stylesPath) {
|
|
232
|
+
context.logger.warn(`[@solercia/ui] No se encontró "${candidates[0]}" ni "${candidates[1]}" — agrega ` +
|
|
233
|
+
'manualmente el snippet de tokens --sol-* a tu hoja de estilos global (ver ' +
|
|
234
|
+
'projects/solercia/ui/docs/THEMING.md).');
|
|
235
|
+
return tree;
|
|
236
|
+
}
|
|
237
|
+
const marker = '/* @solercia/ui — tokens base */';
|
|
238
|
+
const current = tree.read(stylesPath)?.toString('utf-8') ?? '';
|
|
239
|
+
if (current.includes(marker)) {
|
|
240
|
+
return tree;
|
|
241
|
+
}
|
|
242
|
+
const snippet = `\n${marker}\n` +
|
|
243
|
+
`body {\n` +
|
|
244
|
+
` background: var(--sol-bg-page);\n` +
|
|
245
|
+
` color: var(--sol-color-text-primary);\n` +
|
|
246
|
+
` font-family: var(--sol-font-family);\n` +
|
|
247
|
+
`}\n`;
|
|
248
|
+
tree.overwrite(stylesPath, `${current}${snippet}`);
|
|
249
|
+
return tree;
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
/** `true` cuando el `package.json` del anfitrión declara `"type": "module"`. */
|
|
253
|
+
function packageDeclaresEsm(tree) {
|
|
254
|
+
if (!tree.exists('/package.json')) {
|
|
255
|
+
return false;
|
|
256
|
+
}
|
|
257
|
+
const pkg = new json_file_1.JSONFile(tree, '/package.json');
|
|
258
|
+
return pkg.get(['type']) === 'module';
|
|
259
|
+
}
|
|
260
|
+
/** `eslint.config.{js,mjs}` del consumidor, referenciando `@solercia/eslint-config`
|
|
261
|
+
* (preset compartido — fronteras FSD, smart/dumb, Chart.js, naming-convention).
|
|
262
|
+
* El `srcDir` por defecto del preset (`'src'`) ya coincide con el scaffold FSD
|
|
263
|
+
* de este schematic. No sobrescribe uno existente (proyecto que ya trae su
|
|
264
|
+
* propio lint, en cualquiera de las dos extensiones).
|
|
265
|
+
*
|
|
266
|
+
* Fix ESM: el preset se importa con `import ... from` (sintaxis ESM). Un
|
|
267
|
+
* `package.json` de `ng new` NO declara `"type": "module"` por defecto, así
|
|
268
|
+
* que Node interpreta `eslint.config.js` como CommonJS y falla con
|
|
269
|
+
* `ERR_REQUIRE_ESM` al resolver el `import`. En vez de forzar `type: module`
|
|
270
|
+
* en `package.json` (rompería los `module.exports` de `commitlint.config.js`/
|
|
271
|
+
* `lint-staged.config.js` que scaffoldea `scaffoldHusky`), se emite el archivo
|
|
272
|
+
* como `.mjs` cuando el proyecto no es ya ESM. */
|
|
273
|
+
function scaffoldEslintConfig(context) {
|
|
274
|
+
return (tree) => {
|
|
275
|
+
const jsPath = '/eslint.config.js';
|
|
276
|
+
const mjsPath = '/eslint.config.mjs';
|
|
277
|
+
if (tree.exists(jsPath) || tree.exists(mjsPath)) {
|
|
278
|
+
context.logger.info('[@solercia/ui] Ya existe un "eslint.config.{js,mjs}" — se deja intacto.');
|
|
279
|
+
return tree;
|
|
280
|
+
}
|
|
281
|
+
const targetPath = packageDeclaresEsm(tree) ? jsPath : mjsPath;
|
|
282
|
+
tree.create(targetPath, `// @ts-check\n` +
|
|
283
|
+
`// Generado por \`ng add @solercia/ui\`. @solercia/eslint-config trae las fronteras FSD\n` +
|
|
284
|
+
`// (app → pages → widgets → features → entities → shared), la regla smart/dumb de\n` +
|
|
285
|
+
`// shared/ui, la restricción de Chart.js y naming-convention/filename-case.\n` +
|
|
286
|
+
`import solerciaConfig from '@solercia/eslint-config';\n\n` +
|
|
287
|
+
`export default [\n` +
|
|
288
|
+
` { ignores: ['.angular/', 'dist/', 'coverage/', 'node_modules/'] },\n` +
|
|
289
|
+
` ...solerciaConfig,\n` +
|
|
290
|
+
`];\n`);
|
|
291
|
+
return tree;
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
/** Husky + lint-staged + commitlint, calcados 1:1 del cableado real de
|
|
295
|
+
* `boki-front` (07-e9 PR2, T21): `pre-commit` → lint-staged (eslint --fix +
|
|
296
|
+
* tsc --noEmit sobre staged); `commit-msg` → commitlint (conventional commits).
|
|
297
|
+
*
|
|
298
|
+
* Fix ESM (coherente con `scaffoldEslintConfig`): ambos configs usan sintaxis
|
|
299
|
+
* CommonJS (`module.exports`). Si el `package.json` anfitrión declara
|
|
300
|
+
* `"type": "module"`, Node interpreta cualquier `.js` como ESM y `module` deja
|
|
301
|
+
* de existir en ese scope (`ReferenceError: module is not defined in ES
|
|
302
|
+
* module scope`), reventando los hooks de Husky. commitlint y lint-staged
|
|
303
|
+
* soportan `.cjs` explícito para forzar CommonJS sin tocar el contenido — se
|
|
304
|
+
* usa esa extensión cuando el host ya es ESM; en caso contrario se mantiene
|
|
305
|
+
* `.js` (comportamiento previo, sin cambios para el caso por defecto). */
|
|
306
|
+
function scaffoldHusky(context) {
|
|
307
|
+
return (tree) => {
|
|
308
|
+
const commonJsExt = packageDeclaresEsm(tree) ? 'cjs' : 'js';
|
|
309
|
+
if (!tree.exists('/.husky/pre-commit')) {
|
|
310
|
+
tree.create('/.husky/pre-commit', 'npx lint-staged\n');
|
|
311
|
+
}
|
|
312
|
+
if (!tree.exists('/.husky/commit-msg')) {
|
|
313
|
+
tree.create('/.husky/commit-msg', 'npx --no -- commitlint --edit "$1"\n');
|
|
314
|
+
}
|
|
315
|
+
const commitlintPath = `/commitlint.config.${commonJsExt}`;
|
|
316
|
+
if (!tree.exists('/commitlint.config.js') && !tree.exists('/commitlint.config.cjs')) {
|
|
317
|
+
tree.create(commitlintPath, `module.exports = {\n extends: ['@commitlint/config-conventional'],\n};\n`);
|
|
318
|
+
}
|
|
319
|
+
const lintStagedPath = `/lint-staged.config.${commonJsExt}`;
|
|
320
|
+
if (!tree.exists('/lint-staged.config.js') && !tree.exists('/lint-staged.config.cjs')) {
|
|
321
|
+
tree.create(lintStagedPath, `// tsc --noEmit corre UNA vez contra todo el proyecto (no archivo por archivo):\n` +
|
|
322
|
+
`// TypeScript necesita el grafo completo para chequear tipos correctamente.\n` +
|
|
323
|
+
`module.exports = {\n` +
|
|
324
|
+
` '*.ts': [\n` +
|
|
325
|
+
` 'eslint --fix',\n` +
|
|
326
|
+
` () => 'tsc -p tsconfig.app.json --noEmit',\n` +
|
|
327
|
+
` ],\n` +
|
|
328
|
+
`};\n`);
|
|
329
|
+
}
|
|
330
|
+
if (tree.exists('/package.json')) {
|
|
331
|
+
const pkg = new json_file_1.JSONFile(tree, '/package.json');
|
|
332
|
+
if (pkg.get(['scripts', 'prepare']) === undefined) {
|
|
333
|
+
pkg.modify(['scripts', 'prepare'], 'husky');
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
context.logger.info('[@solercia/ui] Husky scaffoldeado. Ejecuta `npm run prepare` (o `npx husky`) una vez ' +
|
|
337
|
+
'instaladas las dependencias para activar los hooks de git.');
|
|
338
|
+
return tree;
|
|
339
|
+
};
|
|
340
|
+
}
|