forjajs 1.1.6 → 1.2.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/CHANGELOG.md +37 -0
- package/README.en.md +28 -5
- package/README.md +30 -4
- package/bin/forja.mjs +3 -3
- package/boilerplates/06-clean-arch/README.md +48 -0
- package/boilerplates/06-clean-arch/WHEN-CLEAN-WHEN-LEAN.md +42 -0
- package/boilerplates/06-clean-arch/backend/package.json +43 -0
- package/boilerplates/06-clean-arch/backend/src/app.module.ts +20 -0
- package/boilerplates/06-clean-arch/backend/src/main.ts +10 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/application/place-order.usecase.ts +47 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/application/ship-order.usecase.ts +28 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/money.vo.ts +30 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order-status.vo.ts +36 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.entity.ts +85 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/domain/order.repository.ts +17 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/infrastructure/order.orm-entity.ts +24 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/infrastructure/typeorm-order.repository.ts +57 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/orders.module.ts +28 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.controller.ts +31 -0
- package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.http.dto.ts +30 -0
- package/boilerplates/06-clean-arch/backend/src/modules/products/product.entity.ts +20 -0
- package/boilerplates/06-clean-arch/backend/src/modules/products/products.controller.ts +43 -0
- package/boilerplates/06-clean-arch/backend/src/modules/products/products.module.ts +11 -0
- package/boilerplates/06-clean-arch/backend/src/shared/result.ts +32 -0
- package/boilerplates/06-clean-arch/backend/test/orders/place-order.spec.ts +46 -0
- package/boilerplates/06-clean-arch/backend/tsconfig.json +16 -0
- package/boilerplates/06-clean-arch/boilerplate.manifest.json +43 -0
- package/boilerplates/06-clean-arch/memory/30-domains/orders/context.md +39 -0
- package/boilerplates/06-clean-arch/memory/30-domains/products/context.md +23 -0
- package/boilerplates/README.md +20 -0
- package/docs/personas/architect/README.md +4 -4
- package/docs/personas/developer/README.md +3 -3
- package/docs/personas/qa/README.md +3 -3
- package/docs/quick-reference.md +9 -9
- package/docs/structure.md +3 -3
- package/lib/core/checks.mjs +20 -3
- package/lib/core/doc-graph.mjs +231 -0
- package/lib/core/health.mjs +131 -29
- package/lib/core/registry.mjs +23 -0
- package/lib/core/release.mjs +48 -8
- package/lib/templates/harness/code-intel.mjs +2 -2
- package/memory/90-decisions/0025-coerencia-da-documentacao.md +95 -0
- package/memory/90-decisions/0027-clean-arch-calibrada.md +96 -0
- package/package.json +7 -1
- package/scripts/agent-harness.mjs +7 -5
- package/scripts/context-ops.mjs +7 -4
- package/scripts/dev.mjs +2 -2
- package/scripts/hook-guard-paths.mjs +1 -0
- package/scripts/hook-user-prompt.mjs +1 -1
- package/scripts/spec-cli.mjs +4 -3
- package/scripts/tools-doctor.mjs +1 -1
- package/specs/clean-arch-boilerplate/plan.md +137 -0
- package/specs/clean-arch-boilerplate/spec.md +121 -0
- package/specs/clean-arch-boilerplate/tasks.md +70 -0
- package/specs/coerencia-do-sistema/plan.md +155 -0
- package/specs/coerencia-do-sistema/spec.md +15 -14
- package/specs/coerencia-do-sistema/tasks.md +115 -0
- package/specs/ts-migration/plan.md +188 -0
- package/specs/ts-migration/spec.md +119 -0
- package/specs/ts-migration/tasks.md +110 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Injectable } from '@nestjs/common';
|
|
2
|
+
import { InjectRepository } from '@nestjs/typeorm';
|
|
3
|
+
import { Repository } from 'typeorm';
|
|
4
|
+
import { Order, OrderLine } from '../domain/order.entity';
|
|
5
|
+
import { Money } from '../domain/money.vo';
|
|
6
|
+
import { OrderStatus, OrderStatusValue } from '../domain/order-status.vo';
|
|
7
|
+
import { OrderRepository } from '../domain/order.repository';
|
|
8
|
+
import { OrderOrmEntity } from './order.orm-entity';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* O ADAPTER: implementa a porta `OrderRepository` do domínio usando TypeORM. É o único lugar que
|
|
12
|
+
* conhece o ORM. O **mapper** (toDomain/toOrm) traduz entre o agregado puro e a orm-entity — a
|
|
13
|
+
* fronteira que impede o TypeORM de vazar para dentro.
|
|
14
|
+
*/
|
|
15
|
+
@Injectable()
|
|
16
|
+
export class TypeOrmOrderRepository implements OrderRepository {
|
|
17
|
+
constructor(
|
|
18
|
+
@InjectRepository(OrderOrmEntity)
|
|
19
|
+
private readonly repo: Repository<OrderOrmEntity>,
|
|
20
|
+
) {}
|
|
21
|
+
|
|
22
|
+
async save(order: Order): Promise<void> {
|
|
23
|
+
await this.repo.save(this.toOrm(order));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async byId(id: string): Promise<Order | null> {
|
|
27
|
+
const row = await this.repo.findOne({ where: { id } });
|
|
28
|
+
return row ? this.toDomain(row) : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
private toOrm(order: Order): OrderOrmEntity {
|
|
32
|
+
const row = new OrderOrmEntity();
|
|
33
|
+
row.id = order.id;
|
|
34
|
+
row.customerId = order.customerId;
|
|
35
|
+
row.status = order.status.value;
|
|
36
|
+
row.lines = order.lines.map((l) => ({
|
|
37
|
+
productId: l.productId,
|
|
38
|
+
unitPriceCents: l.unitPrice.cents,
|
|
39
|
+
quantity: l.quantity,
|
|
40
|
+
}));
|
|
41
|
+
return row;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
private toDomain(row: OrderOrmEntity): Order {
|
|
45
|
+
const lines: OrderLine[] = row.lines.map((l) => ({
|
|
46
|
+
productId: l.productId,
|
|
47
|
+
unitPrice: Money.of(l.unitPriceCents),
|
|
48
|
+
quantity: l.quantity,
|
|
49
|
+
}));
|
|
50
|
+
return Order.rehydrate(
|
|
51
|
+
row.id,
|
|
52
|
+
row.customerId,
|
|
53
|
+
lines,
|
|
54
|
+
OrderStatus.from(row.status as OrderStatusValue),
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
3
|
+
import { ORDER_REPOSITORY } from './domain/order.repository';
|
|
4
|
+
import { OrderOrmEntity } from './infrastructure/order.orm-entity';
|
|
5
|
+
import { TypeOrmOrderRepository } from './infrastructure/typeorm-order.repository';
|
|
6
|
+
import { PlaceOrderUseCase } from './application/place-order.usecase';
|
|
7
|
+
import { ShipOrderUseCase } from './application/ship-order.usecase';
|
|
8
|
+
import { OrdersController } from './presentation/orders.controller';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* O módulo é onde a **inversão de dependência** acontece, numa linha:
|
|
12
|
+
*
|
|
13
|
+
* { provide: ORDER_REPOSITORY, useClass: TypeOrmOrderRepository }
|
|
14
|
+
*
|
|
15
|
+
* O use-case pede o token `ORDER_REPOSITORY` (a porta do domínio); o Nest entrega o adapter TypeORM.
|
|
16
|
+
* Trocar de persistência = trocar o `useClass` aqui, e nada mais. O domínio e a aplicação não sabem
|
|
17
|
+
* que TypeORM existe.
|
|
18
|
+
*/
|
|
19
|
+
@Module({
|
|
20
|
+
imports: [TypeOrmModule.forFeature([OrderOrmEntity])],
|
|
21
|
+
controllers: [OrdersController],
|
|
22
|
+
providers: [
|
|
23
|
+
PlaceOrderUseCase,
|
|
24
|
+
ShipOrderUseCase,
|
|
25
|
+
{ provide: ORDER_REPOSITORY, useClass: TypeOrmOrderRepository },
|
|
26
|
+
],
|
|
27
|
+
})
|
|
28
|
+
export class OrdersModule {}
|
package/boilerplates/06-clean-arch/backend/src/modules/orders/presentation/orders.controller.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { BadRequestException, Body, Controller, Param, Post } from '@nestjs/common';
|
|
2
|
+
import { PlaceOrderUseCase } from '../application/place-order.usecase';
|
|
3
|
+
import { ShipOrderUseCase } from '../application/ship-order.usecase';
|
|
4
|
+
import { PlaceOrderHttpDto } from './orders.http.dto';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* O controller é FINO. Ele traduz HTTP↔use-case e converte falha de domínio em erro HTTP — nada
|
|
8
|
+
* mais. Zero regra de negócio aqui. Se você sentir vontade de colocar um `if` de regra no
|
|
9
|
+
* controller, ele pertence ao domínio.
|
|
10
|
+
*/
|
|
11
|
+
@Controller('orders')
|
|
12
|
+
export class OrdersController {
|
|
13
|
+
constructor(
|
|
14
|
+
private readonly placeOrder: PlaceOrderUseCase,
|
|
15
|
+
private readonly shipOrder: ShipOrderUseCase,
|
|
16
|
+
) {}
|
|
17
|
+
|
|
18
|
+
@Post()
|
|
19
|
+
async place(@Body() dto: PlaceOrderHttpDto) {
|
|
20
|
+
const result = await this.placeOrder.execute(dto);
|
|
21
|
+
if (result.isFailure) throw new BadRequestException(result.error);
|
|
22
|
+
return result.value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
@Post(':id/ship')
|
|
26
|
+
async ship(@Param('id') id: string) {
|
|
27
|
+
const result = await this.shipOrder.execute({ orderId: id });
|
|
28
|
+
if (result.isFailure) throw new BadRequestException(result.error);
|
|
29
|
+
return { ok: true };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { IsArray, IsInt, IsPositive, IsString, ValidateNested } from 'class-validator';
|
|
2
|
+
import { Type } from 'class-transformer';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* DTOs de HTTP — a forma do que chega pela borda. Validados com class-validator. São de
|
|
6
|
+
* PRESENTAÇÃO: o controller os traduz para o input do use-case. O domínio nunca vê estes tipos.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
class OrderItemDto {
|
|
10
|
+
@IsString()
|
|
11
|
+
productId!: string;
|
|
12
|
+
|
|
13
|
+
@IsInt()
|
|
14
|
+
@IsPositive()
|
|
15
|
+
unitPriceCents!: number;
|
|
16
|
+
|
|
17
|
+
@IsInt()
|
|
18
|
+
@IsPositive()
|
|
19
|
+
quantity!: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class PlaceOrderHttpDto {
|
|
23
|
+
@IsString()
|
|
24
|
+
customerId!: string;
|
|
25
|
+
|
|
26
|
+
@IsArray()
|
|
27
|
+
@ValidateNested({ each: true })
|
|
28
|
+
@Type(() => OrderItemDto)
|
|
29
|
+
items!: OrderItemDto[];
|
|
30
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Product — CRUD puro, SEM regra de negócio. Aqui a orm-entity É o modelo: não há invariante para
|
|
5
|
+
* proteger, então separar domínio/persistência seria custo sem retorno. Uma classe, decorada.
|
|
6
|
+
*
|
|
7
|
+
* Este é o **caminho enxuto** (AC-4). Compare com `modules/orders/`: lá, quatro camadas porque há
|
|
8
|
+
* regra que se paga; aqui, uma, porque não há. Ver `WHEN-CLEAN-WHEN-LEAN.md`.
|
|
9
|
+
*/
|
|
10
|
+
@Entity('products')
|
|
11
|
+
export class Product {
|
|
12
|
+
@PrimaryGeneratedColumn('uuid')
|
|
13
|
+
id!: string;
|
|
14
|
+
|
|
15
|
+
@Column()
|
|
16
|
+
name!: string;
|
|
17
|
+
|
|
18
|
+
@Column('int')
|
|
19
|
+
priceCents!: number;
|
|
20
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
|
|
2
|
+
import { InjectRepository } from '@nestjs/typeorm';
|
|
3
|
+
import { Repository } from 'typeorm';
|
|
4
|
+
import { IsInt, IsPositive, IsString } from 'class-validator';
|
|
5
|
+
import { Product } from './product.entity';
|
|
6
|
+
|
|
7
|
+
class CreateProductDto {
|
|
8
|
+
@IsString()
|
|
9
|
+
name!: string;
|
|
10
|
+
|
|
11
|
+
@IsInt()
|
|
12
|
+
@IsPositive()
|
|
13
|
+
priceCents!: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* CRUD enxuto: o controller fala DIRETO com o repositório do TypeORM. Sem use-case, sem porta, sem
|
|
18
|
+
* mapper. Para dados sem invariante, essas camadas seriam só arquivos a mais para o dev e para o
|
|
19
|
+
* agente lerem — o oposto de economia de token.
|
|
20
|
+
*
|
|
21
|
+
* A regra de quando promover isto para o padrão de `orders/` está em `WHEN-CLEAN-WHEN-LEAN.md`.
|
|
22
|
+
*/
|
|
23
|
+
@Controller('products')
|
|
24
|
+
export class ProductsController {
|
|
25
|
+
constructor(
|
|
26
|
+
@InjectRepository(Product) private readonly repo: Repository<Product>,
|
|
27
|
+
) {}
|
|
28
|
+
|
|
29
|
+
@Post()
|
|
30
|
+
create(@Body() dto: CreateProductDto) {
|
|
31
|
+
return this.repo.save(this.repo.create(dto));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
@Get()
|
|
35
|
+
list() {
|
|
36
|
+
return this.repo.find();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
@Get(':id')
|
|
40
|
+
byId(@Param('id') id: string) {
|
|
41
|
+
return this.repo.findOne({ where: { id } });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Module } from '@nestjs/common';
|
|
2
|
+
import { TypeOrmModule } from '@nestjs/typeorm';
|
|
3
|
+
import { Product } from './product.entity';
|
|
4
|
+
import { ProductsController } from './products.controller';
|
|
5
|
+
|
|
6
|
+
/** CRUD enxuto: só o controller e a entity. Sem providers de porta/adapter — não há o que inverter. */
|
|
7
|
+
@Module({
|
|
8
|
+
imports: [TypeOrmModule.forFeature([Product])],
|
|
9
|
+
controllers: [ProductsController],
|
|
10
|
+
})
|
|
11
|
+
export class ProductsModule {}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Result<T> — sucesso ou falha de domínio, sem lançar exceção.
|
|
3
|
+
*
|
|
4
|
+
* O domínio devolve `Result` em vez de `throw` para que a regra de negócio seja um valor testável
|
|
5
|
+
* (o teste lê `.isFailure`, não captura exceção) e para que a camada de aplicação decida o que
|
|
6
|
+
* fazer com a falha. `throw` é reservado para o inesperado (bug), não para regra de negócio.
|
|
7
|
+
*/
|
|
8
|
+
export class Result<T> {
|
|
9
|
+
private constructor(
|
|
10
|
+
public readonly isSuccess: boolean,
|
|
11
|
+
private readonly _value?: T,
|
|
12
|
+
public readonly error?: string,
|
|
13
|
+
) {}
|
|
14
|
+
|
|
15
|
+
get isFailure(): boolean {
|
|
16
|
+
return !this.isSuccess;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Só chame após checar `isSuccess`. Falha aqui é bug, não regra. */
|
|
20
|
+
get value(): T {
|
|
21
|
+
if (!this.isSuccess) throw new Error(`Result sem valor: ${this.error}`);
|
|
22
|
+
return this._value as T;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
static ok<T>(value: T): Result<T> {
|
|
26
|
+
return new Result(true, value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
static fail<T>(error: string): Result<T> {
|
|
30
|
+
return new Result<T>(false, undefined, error);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { Order } from '../../src/modules/orders/domain/order.entity';
|
|
2
|
+
import { Money } from '../../src/modules/orders/domain/money.vo';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A prova concreta do isolamento (AC-8): estes testes exercem a **regra de negócio** instanciando
|
|
6
|
+
* SÓ o agregado de domínio — sem `Test.createTestingModule`, sem ORM, sem subir o Nest. Se um dia a
|
|
7
|
+
* invariante precisar do framework para ser testada, o domínio vazou e a arquitetura falhou.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const line = (cents: number, qty: number) => ({
|
|
11
|
+
productId: 'p1',
|
|
12
|
+
unitPrice: Money.of(cents),
|
|
13
|
+
quantity: qty,
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
describe('Order (domínio, sem Nest)', () => {
|
|
17
|
+
it('não cria pedido sem itens', () => {
|
|
18
|
+
const r = Order.place('o1', 'c1', []);
|
|
19
|
+
expect(r.isFailure).toBe(true);
|
|
20
|
+
expect(r.error).toMatch(/ao menos um item/);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('deriva o total das linhas', () => {
|
|
24
|
+
const order = Order.place('o1', 'c1', [line(1000, 2), line(500, 1)]).value;
|
|
25
|
+
expect(order.total.cents).toBe(2500);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('NÃO envia sem pagamento — a invariante-chave', () => {
|
|
29
|
+
const order = Order.place('o1', 'c1', [line(1000, 1)]).value;
|
|
30
|
+
order.confirm();
|
|
31
|
+
// pula o pay() de propósito
|
|
32
|
+
const shipped = order.ship();
|
|
33
|
+
expect(shipped.isFailure).toBe(true);
|
|
34
|
+
expect(shipped.error).toMatch(/transição inválida/);
|
|
35
|
+
expect(order.status.value).toBe('CONFIRMED');
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it('envia quando pago — o caminho feliz da máquina de estados', () => {
|
|
39
|
+
const order = Order.place('o1', 'c1', [line(1000, 1)]).value;
|
|
40
|
+
order.confirm();
|
|
41
|
+
order.pay();
|
|
42
|
+
const shipped = order.ship();
|
|
43
|
+
expect(shipped.isSuccess).toBe(true);
|
|
44
|
+
expect(order.status.value).toBe('SHIPPED');
|
|
45
|
+
});
|
|
46
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"module": "commonjs",
|
|
4
|
+
"target": "es2022",
|
|
5
|
+
"moduleResolution": "node",
|
|
6
|
+
"experimentalDecorators": true,
|
|
7
|
+
"emitDecoratorMetadata": true,
|
|
8
|
+
"declaration": false,
|
|
9
|
+
"strict": true,
|
|
10
|
+
"skipLibCheck": true,
|
|
11
|
+
"esModuleInterop": true,
|
|
12
|
+
"outDir": "./dist",
|
|
13
|
+
"baseUrl": "./"
|
|
14
|
+
},
|
|
15
|
+
"include": ["src/**/*", "test/**/*"]
|
|
16
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": "1.0",
|
|
3
|
+
"type": "boilerplate",
|
|
4
|
+
"name": "06-clean-arch",
|
|
5
|
+
"title": "Clean Architecture Calibrada - DDD por camadas, sem cerimônia",
|
|
6
|
+
"path": "boilerplates/06-clean-arch",
|
|
7
|
+
"readme": "boilerplates/06-clean-arch/README.md",
|
|
8
|
+
"stack": [
|
|
9
|
+
"NestJS",
|
|
10
|
+
"TypeScript",
|
|
11
|
+
"TypeORM",
|
|
12
|
+
"Postgres"
|
|
13
|
+
],
|
|
14
|
+
"useCases": [
|
|
15
|
+
"Domínio com regra de negócio",
|
|
16
|
+
"DDD",
|
|
17
|
+
"Clean Architecture",
|
|
18
|
+
"Hexagonal"
|
|
19
|
+
],
|
|
20
|
+
"commands": [
|
|
21
|
+
"npm install",
|
|
22
|
+
"npm run start:dev",
|
|
23
|
+
"npm test",
|
|
24
|
+
"npm run test:e2e"
|
|
25
|
+
],
|
|
26
|
+
"gates": [
|
|
27
|
+
"npm test",
|
|
28
|
+
"npm run test:cov"
|
|
29
|
+
],
|
|
30
|
+
"tokenPolicy": {
|
|
31
|
+
"firstRead": [
|
|
32
|
+
"boilerplate.manifest.json",
|
|
33
|
+
"README.md",
|
|
34
|
+
"WHEN-CLEAN-WHEN-LEAN.md",
|
|
35
|
+
"memory/30-domains/orders/context.md"
|
|
36
|
+
],
|
|
37
|
+
"avoidLoadingByDefault": [
|
|
38
|
+
"node_modules",
|
|
39
|
+
"dist",
|
|
40
|
+
"coverage"
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Contexto: Orders (fatia rica)
|
|
2
|
+
|
|
3
|
+
> Leia **este arquivo antes do código**. Ele descreve o domínio na linguagem ubíqua. Você só precisa
|
|
4
|
+
> descer à implementação quando for *editar* — e aí sabe exatamente onde. Isso é a economia de token
|
|
5
|
+
> do boilerplate (ADR-0009): o resumo tipado do domínio, não a leitura da árvore inteira.
|
|
6
|
+
|
|
7
|
+
## Linguagem ubíqua
|
|
8
|
+
|
|
9
|
+
- **Order** (agregado) — um pedido de um cliente, com uma ou mais linhas.
|
|
10
|
+
- **OrderLine** — produto + preço unitário + quantidade.
|
|
11
|
+
- **OrderStatus** — máquina de estados: `DRAFT → CONFIRMED → PAID → SHIPPED`, e `CANCELLED` de
|
|
12
|
+
qualquer estado não-enviado.
|
|
13
|
+
- **Money** — value object em centavos; imutável, comparado por valor.
|
|
14
|
+
|
|
15
|
+
## Invariantes (moram em `domain/order.entity.ts`)
|
|
16
|
+
|
|
17
|
+
1. Um pedido **precisa de ao menos uma linha** para ser criado.
|
|
18
|
+
2. Toda quantidade é **positiva**.
|
|
19
|
+
3. O **total é derivado** das linhas — nunca setado de fora.
|
|
20
|
+
4. As transições de estado seguem a máquina; em especial: **não se envia sem pagamento** (`SHIPPED`
|
|
21
|
+
só a partir de `PAID`).
|
|
22
|
+
|
|
23
|
+
Se você vai mexer numa regra, ela está no agregado. Não procure no controller nem no service.
|
|
24
|
+
|
|
25
|
+
## Casos de uso (contratos em `application/`)
|
|
26
|
+
|
|
27
|
+
| Use-case | Input → Output | O que faz |
|
|
28
|
+
|---|---|---|
|
|
29
|
+
| `PlaceOrderUseCase` | `{ customerId, items[] }` → `{ orderId, totalCents }` | cria + confirma o pedido |
|
|
30
|
+
| `ShipOrderUseCase` | `{ orderId }` → `void` | envia — falha se não estiver pago |
|
|
31
|
+
|
|
32
|
+
A assinatura basta para saber o que a feature faz. O corpo só interessa ao editar.
|
|
33
|
+
|
|
34
|
+
## Onde as coisas ficam
|
|
35
|
+
|
|
36
|
+
- Regra nova → `domain/order.entity.ts` (e teste em `test/orders/place-order.spec.ts`, sem Nest).
|
|
37
|
+
- Caso de uso novo → `application/*.usecase.ts`.
|
|
38
|
+
- Persistência → `infrastructure/typeorm-order.repository.ts` (implementa a porta do domínio).
|
|
39
|
+
- Endpoint → `presentation/orders.controller.ts` (fino: traduz HTTP ↔ use-case).
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Contexto: Products (caminho enxuto)
|
|
2
|
+
|
|
3
|
+
> CRUD sem regra de negócio. **Uma camada.** Se você esperava as quatro camadas de `orders/`, leia o
|
|
4
|
+
> `WHEN-CLEAN-WHEN-LEAN.md` — a ausência delas aqui é decisão, não esquecimento.
|
|
5
|
+
|
|
6
|
+
## Linguagem ubíqua
|
|
7
|
+
|
|
8
|
+
- **Product** — nome + preço (centavos). Não há comportamento a proteger; o modelo é a tabela.
|
|
9
|
+
|
|
10
|
+
## Regras
|
|
11
|
+
|
|
12
|
+
Nenhuma além de validação de formato (nome string, preço inteiro positivo). Não há invariante, não
|
|
13
|
+
há transição de estado. Por isso o `controller` fala direto com o repositório do TypeORM.
|
|
14
|
+
|
|
15
|
+
## Quando isto vira `orders/`
|
|
16
|
+
|
|
17
|
+
No dia em que aparecer uma regra de verdade — por exemplo, *"não pode desativar um produto com pedido
|
|
18
|
+
em aberto"* — este contexto ganha um agregado de domínio e migra para o padrão de quatro camadas. Até
|
|
19
|
+
lá, promover seria pagar tokens adiantado por camadas vazias.
|
|
20
|
+
|
|
21
|
+
## Onde as coisas ficam
|
|
22
|
+
|
|
23
|
+
- Tudo em `modules/products/`: `product.entity.ts` (o modelo) e `products.controller.ts` (o CRUD).
|
package/boilerplates/README.md
CHANGED
|
@@ -119,6 +119,26 @@ node ../bin/init-project.js meu-projeto --template monorepo
|
|
|
119
119
|
|
|
120
120
|
---
|
|
121
121
|
|
|
122
|
+
### 🧱 6. Clean Architecture (Calibrada)
|
|
123
|
+
**Para**: Produtos com regra de negócio de verdade — DDD por camadas, sem cerimônia
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
node ../bin/init-project.js meu-projeto --template clean-arch
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
**Inclui**:
|
|
130
|
+
- Fatia rica (Orders): domain / application / infrastructure / presentation, com inversão de dependência
|
|
131
|
+
- Caminho enxuto (Products): CRUD em 1 camada, lado a lado — a calibração visível
|
|
132
|
+
- Invariante de domínio testável **sem subir o Nest**
|
|
133
|
+
- Memória por bounded context (linguagem ubíqua) para leitura barata por agente
|
|
134
|
+
- `WHEN-CLEAN-WHEN-LEAN.md`: o critério de quando usar cada padrão
|
|
135
|
+
|
|
136
|
+
**Use quando**: há invariante de negócio ou máquina de estados. Para CRUD puro, prefira um dos flat acima.
|
|
137
|
+
|
|
138
|
+
[Abrir 📂](./06-clean-arch)
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
122
142
|
### 📊 6. Dashboard Admin
|
|
123
143
|
**Para**: Painel administrativo, gestão interna
|
|
124
144
|
|
|
@@ -309,10 +309,10 @@ Seguir [Guia de Developer](../developer/README.md)
|
|
|
309
309
|
|
|
310
310
|
| Documento | Quando ler |
|
|
311
311
|
|-----------|-----------|
|
|
312
|
-
| [
|
|
313
|
-
| [
|
|
314
|
-
| [
|
|
315
|
-
| [
|
|
312
|
+
| [AGENTS.md](../../../AGENTS.md) | Os 6 papéis e a topologia |
|
|
313
|
+
| [memory/90-decisions/](../../../memory/90-decisions/) | ADRs com rationale |
|
|
314
|
+
| [structure.md](../../structure.md) | Estrutura de diretórios |
|
|
315
|
+
| [agent-harnesses.md](../../agent-harnesses.md) | Harness e ferramentas de processo |
|
|
316
316
|
|
|
317
317
|
---
|
|
318
318
|
|
|
@@ -294,9 +294,9 @@ open coverage/index.html
|
|
|
294
294
|
|
|
295
295
|
| Recurso | Quando usar |
|
|
296
296
|
|---------|------------|
|
|
297
|
-
| [
|
|
298
|
-
| [
|
|
299
|
-
| [
|
|
297
|
+
| [boilerplates/](../../../boilerplates/README.md) | Padrões prontos por stack |
|
|
298
|
+
| [quick-reference.md](../../quick-reference.md) | Atalhos de comandos |
|
|
299
|
+
| [fluxo.md](../../fluxo.md) | Roteiro do ciclo CLI-first |
|
|
300
300
|
| [NestJS Docs](https://docs.nestjs.com) | Dúvidas NestJS |
|
|
301
301
|
|
|
302
302
|
---
|
|
@@ -339,9 +339,9 @@ POST /api/seu-endpoint com payload { "campo": "valor especial" }
|
|
|
339
339
|
|
|
340
340
|
| Recurso | Quando usar |
|
|
341
341
|
|---------|------------|
|
|
342
|
-
| [
|
|
343
|
-
| [
|
|
344
|
-
| [
|
|
342
|
+
| [agent-harnesses.md](../../agent-harnesses.md) | Gates e ferramentas de processo |
|
|
343
|
+
| [DOC-MAP.md](../../../DOC-MAP.md) | Mapa da documentação |
|
|
344
|
+
| [memory/90-decisions/](../../../memory/90-decisions/) | Decisões e rationale |
|
|
345
345
|
|
|
346
346
|
---
|
|
347
347
|
|
package/docs/quick-reference.md
CHANGED
|
@@ -345,11 +345,11 @@ logger.error('Auth failed', error); // Erro
|
|
|
345
345
|
|
|
346
346
|
| Recurso | Link |
|
|
347
347
|
|---------|------|
|
|
348
|
-
| Documentation Map | [DOC-MAP.md](DOC-MAP.md) |
|
|
349
|
-
|
|
|
350
|
-
|
|
|
351
|
-
| Architecture | [
|
|
352
|
-
| Personas | [
|
|
348
|
+
| Documentation Map | [DOC-MAP.md](../DOC-MAP.md) |
|
|
349
|
+
| Getting Started | [README.md](../README.md) |
|
|
350
|
+
| Boilerplates | [boilerplates/](../boilerplates/README.md) |
|
|
351
|
+
| Architecture | [AGENTS.md](../AGENTS.md) |
|
|
352
|
+
| Personas | [personas/](personas/) |
|
|
353
353
|
|
|
354
354
|
---
|
|
355
355
|
|
|
@@ -399,10 +399,10 @@ open http://localhost:3000/api/health
|
|
|
399
399
|
|
|
400
400
|
| Dúvida | Arquivo |
|
|
401
401
|
|--------|---------|
|
|
402
|
-
| "Como começar?" | [
|
|
403
|
-
| "Como codificar?" | [
|
|
404
|
-
| "Como arquitetar?" | [
|
|
405
|
-
| "Qual minha persona?" | [DOC-MAP.md](DOC-MAP.md) |
|
|
402
|
+
| "Como começar?" | [README.md](../README.md) |
|
|
403
|
+
| "Como codificar?" | [boilerplates/](../boilerplates/README.md) |
|
|
404
|
+
| "Como arquitetar?" | [AGENTS.md](../AGENTS.md) |
|
|
405
|
+
| "Qual minha persona?" | [DOC-MAP.md](../DOC-MAP.md) |
|
|
406
406
|
|
|
407
407
|
---
|
|
408
408
|
|
package/docs/structure.md
CHANGED
|
@@ -355,6 +355,6 @@ node backend/scripts/memory-db-query.mjs --table improvement_items
|
|
|
355
355
|
---
|
|
356
356
|
|
|
357
357
|
**Para mais detalhes**, veja:
|
|
358
|
-
- [
|
|
359
|
-
- [
|
|
360
|
-
- [
|
|
358
|
+
- [README.md](../README.md)
|
|
359
|
+
- [AGENTS.md](../AGENTS.md)
|
|
360
|
+
- [DOC-MAP.md](../DOC-MAP.md)
|
package/lib/core/checks.mjs
CHANGED
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
* @property {Severity} severity `critical` trava o gate; `warn` informa.
|
|
31
31
|
* @property {Scope=} scope Filtro opcional do runner.
|
|
32
32
|
* @property {string=} dependsOn Id de outro check. Se ele não passar, este vira `skipped`.
|
|
33
|
-
* @property {(env:
|
|
33
|
+
* @property {(env: any) => Promise<Probe>|Probe} probe `env` é injetado e polimórfico entre os
|
|
34
|
+
* catálogos (health/release/doc); tipagem por-catálogo com generics fica para a Fase 2 (.ts).
|
|
34
35
|
*/
|
|
35
36
|
|
|
36
37
|
/**
|
|
@@ -40,10 +41,23 @@
|
|
|
40
41
|
* @property {string|null=} fix Comando exato que corrige. `null` quando não há o que corrigir.
|
|
41
42
|
*/
|
|
42
43
|
|
|
43
|
-
/** @typedef {{ id, title, severity: Severity, scope
|
|
44
|
+
/** @typedef {{ id: string, title: string, severity: Severity, scope?: Scope, status: Status, detail: string, fix: string|null }} Result */
|
|
44
45
|
|
|
46
|
+
/** @type {Severity} */
|
|
45
47
|
const SEVERITY_FALLBACK = 'critical';
|
|
46
48
|
|
|
49
|
+
/**
|
|
50
|
+
* Estreita um valor capturado num `catch` (que o TS tipa como `unknown`) para a forma de erro do
|
|
51
|
+
* Node — `code`/`message` opcionais. Não muda comportamento: só dá ao compilador o que o runtime
|
|
52
|
+
* já assume ao ler `err.code`.
|
|
53
|
+
*
|
|
54
|
+
* @param {unknown} e
|
|
55
|
+
* @returns {NodeJS.ErrnoException}
|
|
56
|
+
*/
|
|
57
|
+
export function asErrno(e) {
|
|
58
|
+
return /** @type {NodeJS.ErrnoException} */ (e);
|
|
59
|
+
}
|
|
60
|
+
|
|
47
61
|
/**
|
|
48
62
|
* Um probe que estoura é pior que probe nenhum: derrubaria o diagnóstico justamente no ambiente
|
|
49
63
|
* quebrado que ele existe para diagnosticar. O runner blinda cada um e segue para o próximo.
|
|
@@ -57,9 +71,10 @@ async function runProbe(check, env) {
|
|
|
57
71
|
fix: probe.fix ?? null,
|
|
58
72
|
};
|
|
59
73
|
} catch (err) {
|
|
74
|
+
const e = asErrno(err);
|
|
60
75
|
return {
|
|
61
76
|
status: 'fail',
|
|
62
|
-
detail: `probe falhou: ${
|
|
77
|
+
detail: `probe falhou: ${e.message || e}`,
|
|
63
78
|
fix: null,
|
|
64
79
|
};
|
|
65
80
|
}
|
|
@@ -73,7 +88,9 @@ async function runProbe(check, env) {
|
|
|
73
88
|
*/
|
|
74
89
|
export async function runChecks({ checks, scope = 'all', env = {} }) {
|
|
75
90
|
const selected = checks.filter((c) => scope === 'all' || c.scope === scope);
|
|
91
|
+
/** @type {Map<string, Status>} */
|
|
76
92
|
const statusById = new Map();
|
|
93
|
+
/** @type {Result[]} */
|
|
77
94
|
const results = [];
|
|
78
95
|
|
|
79
96
|
for (const check of selected) {
|