vsrepo 2.5.0 → 2.7.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +611 -531
  2. package/LICENSE +20 -20
  3. package/README.md +221 -1243
  4. package/README.pt-BR.md +221 -1246
  5. package/dist/VSRepoAdapter.d.ts +12 -0
  6. package/dist/VSRepoAdapter.js.map +1 -1
  7. package/dist/VSRepository.d.ts +93 -5
  8. package/dist/VSRepository.js +116 -35
  9. package/dist/VSRepository.js.map +1 -1
  10. package/dist/decorators/dynamic-method.decorator.d.ts +1 -1
  11. package/dist/decorators/dynamic-method.decorator.js +2 -4
  12. package/dist/decorators/dynamic-method.decorator.js.map +1 -1
  13. package/dist/decorators/query-method.decorator.d.ts +3 -24
  14. package/dist/decorators/query-method.decorator.js +4 -27
  15. package/dist/decorators/query-method.decorator.js.map +1 -1
  16. package/dist/index.d.ts +5 -0
  17. package/dist/index.js +7 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/internal/enums/vsrepo-error-type.enum.d.ts +3 -1
  20. package/dist/internal/enums/vsrepo-error-type.enum.js +2 -0
  21. package/dist/internal/enums/vsrepo-error-type.enum.js.map +1 -1
  22. package/dist/internal/resolvers/dynamic-methods.resolver.d.ts +7 -1
  23. package/dist/internal/resolvers/dynamic-methods.resolver.js +191 -112
  24. package/dist/internal/resolvers/dynamic-methods.resolver.js.map +1 -1
  25. package/dist/internal/utils/vs-logger.util.js.map +1 -1
  26. package/dist/internal/utils/vs-placeholder-parser.util.d.ts +2 -0
  27. package/dist/internal/utils/vs-placeholder-parser.util.js +62 -0
  28. package/dist/internal/utils/vs-placeholder-parser.util.js.map +1 -0
  29. package/dist/internal/utils/vs-query-builder.util.d.ts +239 -0
  30. package/dist/internal/utils/vs-query-builder.util.js +401 -0
  31. package/dist/internal/utils/vs-query-builder.util.js.map +1 -0
  32. package/dist/internal/utils/vs-raw-query-builder.util.d.ts +238 -0
  33. package/dist/internal/utils/vs-raw-query-builder.util.js +433 -0
  34. package/dist/internal/utils/vs-raw-query-builder.util.js.map +1 -0
  35. package/dist/internal/utils/vs-sql.util.d.ts +100 -0
  36. package/dist/internal/utils/vs-sql.util.js +151 -0
  37. package/dist/internal/utils/vs-sql.util.js.map +1 -0
  38. package/dist/internal/utils/with-db.util.js.map +1 -1
  39. package/dist/internal/validators/decorators.validator.js +3 -7
  40. package/dist/internal/validators/decorators.validator.js.map +1 -1
  41. package/dist/internal/validators/schemas/pagination.schema.d.ts +2 -2
  42. package/dist/internal/validators/schemas/pagination.schema.js +2 -2
  43. package/dist/internal/validators/schemas/pagination.schema.js.map +1 -1
  44. package/dist/internal/validators/schemas/relations.schema.d.ts +4 -0
  45. package/dist/internal/validators/schemas/relations.schema.js +39 -0
  46. package/dist/internal/validators/schemas/relations.schema.js.map +1 -0
  47. package/dist/internal/validators/schemas/see-mode.schema.d.ts +3 -0
  48. package/dist/internal/validators/schemas/see-mode.schema.js +38 -0
  49. package/dist/internal/validators/schemas/see-mode.schema.js.map +1 -0
  50. package/dist/internal/validators/schemas/select.schema.d.ts +4 -0
  51. package/dist/internal/validators/schemas/select.schema.js +39 -0
  52. package/dist/internal/validators/schemas/select.schema.js.map +1 -0
  53. package/dist/internal/validators/vsrepo.validator.js +7 -5
  54. package/dist/internal/validators/vsrepo.validator.js.map +1 -1
  55. package/dist/types/dynamic-methods/dynamic-method-info.type.d.ts +1 -0
  56. package/dist/types/utils/query-args.type.d.ts +1 -4
  57. package/dist/types/vsrepo/vs-raw-query-builder-cte-query.type.d.ts +8 -0
  58. package/dist/types/vsrepo/vs-raw-query-builder-cte-query.type.js +3 -0
  59. package/dist/types/vsrepo/vs-raw-query-builder-cte-query.type.js.map +1 -0
  60. package/dist/types/vsrepo/vs-raw-query-builder-target.type.d.ts +7 -0
  61. package/dist/types/vsrepo/vs-raw-query-builder-target.type.js +3 -0
  62. package/dist/types/vsrepo/vs-raw-query-builder-target.type.js.map +1 -0
  63. package/dist/types/vsrepo/vsrepo-options.type.d.ts +27 -0
  64. package/package.json +88 -80
package/CHANGELOG.md CHANGED
@@ -1,531 +1,611 @@
1
- # Changelog
2
-
3
- All notable changes to this project will be documented in this file.
4
-
5
- (Português) Todas as mudanças notáveis neste projeto serão documentadas neste arquivo.
6
-
7
- ---
8
-
9
- ## [2.5.0] - 2026-09-20
10
-
11
- > Promotes `2.5.0-beta` to stable.
12
-
13
- ---
14
-
15
- ## [2.5.0] - 2026-09-20 (Português)
16
-
17
- > Promove `2.5.0-beta` para estável.
18
-
19
- ---
20
-
21
- ## [2.5.0-beta] - 2026-09-19
22
-
23
- ### Added
24
- - **`InferMethodReturn<T, Options>`** — new opt-in utility type for stricter return typing, exported from the package entry point. It narrows the type returned by a method (`Entity`, `Entity | null` or `Entity[]`) to the fields and relations actually requested through `select`/`relations`, instead of the whole entity: with no options only the scalar fields are returned; with `relations`, the scalar fields plus the requested relations (nested ones included); with `select`, only the selected fields (a relation set to `true` brings all of its scalar fields, and a nested `select` restricts it further). When both are passed, `select` takes precedence and `relations` is ignored. `null`/array-ness and optional (`?`) modifiers are preserved, and if the options are typed as a plain `MethodOptions<T>` (not narrowed) the whole entity is returned unchanged. The default typing of the methods is **not** changed
25
- - **`InferMethodType<Args, Return, OrmTypes?>`** — new utility type, exported from the package entry point, to declare dynamic methods whose return type is inferred on each call from the `select`/`relations` passed in `options`: `@DynamicMethod() declare findByName: InferMethodType<[name: string], User[]>`. Calls without `options` return only the scalar fields. Unknown keys in `select`/`relations` (at any depth) are rejected at compile time, and the editor autocompletes them, just like with a plain `MethodOptions<T>` parameter. The third generic (`OrmTypes`) is optional and types the `db` option
26
- - **`getPkName?(): string`** - new optional method that allows the adapter to declare the entity's primary key field to the repository. When instantiating a `VSRepository`, you can omit `pkName` from the constructor options, and it will be read from `adapter.getPkName()`. If you omit it and the adapter does not implement `getPkName()`, the constructor throws a `VSRepoError`
27
-
28
- ### Documentation
29
- - Both READMEs document the new types: new "Strict return typing with `InferMethodReturn`" and "Strict return typing with `InferMethodType`" sections, a pointer in the dynamic-methods intro, and two new rows in the utility types table
30
- - Documents the new optional `getPkName?(): string` method of `VSRepoAdapter`
31
-
32
- ### Fixed
33
- - Fixed the `OrderByField` typing so it doesn't claim to accept nested ordering
34
-
35
- ---
36
-
37
- ## [2.5.0-beta] - 2026-09-19 (Português)
38
-
39
- ### Adicionado
40
- - **`InferMethodReturn<T, Options>`** — novo tipo utilitário opt-in para uma tipagem de retorno mais restrita, exportado pelo entry point do pacote. Ele estreita o tipo retornado por um método (`Entity`, `Entity | null` ou `Entity[]`) para os campos e relações realmente pedidos via `select`/`relations`, em vez da entidade inteira: sem options, apenas os campos escalares; com `relations`, os campos escalares mais as relações pedidas (inclusive as aninhadas); com `select`, apenas os campos selecionados (uma relação com `true` traz todos os seus campos escalares, e um `select` aninhado a restringe ainda mais). Quando os dois são passados, `select` tem precedência e `relations` é ignorado. `null`/array e os modificadores opcionais (`?`) são preservados, e se as options estiverem tipadas como um `MethodOptions<T>` genérico (sem estreitamento) a entidade inteira é retornada sem alterações. A tipagem padrão dos métodos **não** foi alterada
41
- - **`InferMethodType<Args, Return, OrmTypes?>`** — novo tipo utilitário, exportado pelo entry point do pacote, para declarar métodos dinâmicos cujo tipo de retorno é inferido a cada chamada a partir do `select`/`relations` passados em `options`: `@DynamicMethod() declare findByName: InferMethodType<[name: string], User[]>`. Chamadas sem `options` retornam apenas os campos escalares. Chaves inexistentes em `select`/`relations` (em qualquer profundidade) são rejeitadas em tempo de compilação, e o editor as sugere via autocomplete, igual a um parâmetro `MethodOptions<T>` comum. A terceira generic (`OrmTypes`) é opcional e tipa a option `db`
42
- - **`getPkName?(): string`** - novo método opcional permite que o adapter declare ao repository qual campo é a primary key da entidade. Ao instanciar um `VSRepository`, você pode omitir o `pkName` das options do construtor e ele será lido do `adapter.getPkName()`. Se você omitir e o adapter não implementar o `getPkName()`, o construtor lança um `VSRepoError`
43
-
44
- ### Documentação
45
- - Ambos os READMEs documentam os novos tipos: novas seções "Tipagem de retorno restrita com `InferMethodReturn`" e "Tipagem de retorno restrita com `InferMethodType`", uma indicação na introdução de métodos dinâmicos, e duas novas linhas na tabela de tipos utilitários
46
- - Documenta o novo método opcional `getPkName?(): string` do `VSRepoAdapter`
47
-
48
- ### Corrigido
49
- - Corrigida a tipagem do `OrderByField` para não dizer que aceita nested ordering
50
-
51
- ---
52
-
53
- ## [2.4.0] - 2026-09-16
54
-
55
- ### Added
56
- - **`logSlowThresholdMs: false`** — passing `false` to `logSlowThresholdMs` (on `VSRepoOptions` or on the `VSLogger` constructor) now disables slow-operation warnings entirely, without having to set an arbitrarily large threshold. Passing `true` or omitting the option keeps the existing 300 ms default. The accepted type is now `number | boolean` instead of `number`
57
-
58
- ### Changed
59
- - `@vsrepo/drizzle-adapter` is now available as an **alpha** release on npm — install it with `npm i @vsrepo/drizzle-adapter@alpha`. The API may still change before the stable release; check the [`DrizzleAdapter`](https://github.com/jaobrabo123/VSRepoDrizzleAdapter) repository for the current status and known limitations
60
-
61
- ### Documentation
62
- - `proxyTo` decorator option now has a dedicated code example in both READMEs, showing the main use case: giving a method a custom name (e.g. a non-English name) while internally resolving it to a valid dynamic-method pattern
63
- - `groupBy` is documented as **not planned** for v2; `aggregate` as a dynamic-method prefix is also unlikely to be added since the most common aggregate operations are already available as dedicated base methods (`sum`, `average`, `min`, `max`, `increment`, `decrement`, `multiply`, `divide`) — `@QueryMethod` with raw SQL is the recommended escape hatch for anything more complex
64
- - Multiple README improvements: fixed and expanded the constructor-options table, corrected examples in the dynamic-methods section, improved descriptions across several utility-type entries, and removed the outdated TypeORM `relations` note from the `select`/`relations` section
65
-
66
- ---
67
-
68
- ## [2.4.0] - 2026-09-16 (Português)
69
-
70
- ### Adicionado
71
- - **`logSlowThresholdMs: false`** — passar `false` em `logSlowThresholdMs` (no `VSRepoOptions` ou no construtor do `VSLogger`) agora desabilita completamente os avisos de operação lenta, sem precisar definir um threshold arbitrariamente grande. Passar `true` ou omitir a option mantém o padrão existente de 300 ms. O tipo aceito agora é `number | boolean` em vez de `number`
72
-
73
- ### Alterado
74
- - `@vsrepo/drizzle-adapter` agora está disponível como versão **alpha** no npm — instale com `npm i @vsrepo/drizzle-adapter@alpha`. A API ainda pode mudar antes do release estável; veja o repositório do [`DrizzleAdapter`](https://github.com/jaobrabo123/VSRepoDrizzleAdapter) para o estado atual e limitações conhecidas
75
-
76
- ### Documentação
77
- - A option `proxyTo` do decorador agora tem um exemplo de código dedicado em ambos os READMEs, mostrando o principal caso de uso: dar um nome customizado a um método (ex.: um nome em outro idioma) enquanto ele resolve internamente para um padrão de método dinâmico válido
78
- - `groupBy` está documentado como **não planejado** para a v2; `aggregate` como prefixo de método dinâmico também dificilmente será adicionado, já que as operações de agregação mais comuns já estão disponíveis como métodos base dedicados (`sum`, `average`, `min`, `max`, `increment`, `decrement`, `multiply`, `divide`) — `@QueryMethod` com SQL raw é o escape hatch recomendado para qualquer coisa mais complexa
79
- - Diversas melhorias nos READMEs: tabela de constructor options corrigida e expandida, exemplos na seção de métodos dinâmicos corrigidos, descrições melhoradas em várias entradas de tipos utilitários, e remoção da nota desatualizada sobre TypeORM e `relations` na seção `select`/`relations`
80
-
81
- ---
82
-
83
- ## [2.3.0] - 2026-09-14
84
-
85
- ### Added
86
- - **`AdapterErrorCode.TRANSACTION_ROLLED_BACK`** — new adapter error code to signal that a database transaction was rolled back. Adapters can now throw `VSRepoAdapterError` with this code to give callers a clear, typed signal that the transaction did not commit
87
-
88
- ### Fixed
89
- - Documentation and JSDoc across READMEs and JavaDocs now correctly state that SQL placeholders are **database-specific** (e.g. `?` for MySQL, `$1`/`$2` for PostgreSQL) instead of implying a single universal syntax
90
-
91
- ### Documentation
92
- - Documented the current state of `VSRepoDrizzleAdapter` — available features, limitations, and planned work
93
- - Documented the new `AdapterErrorCode.TRANSACTION_ROLLED_BACK` in all relevant READMEs and JSDoc
94
-
95
- ---
96
-
97
- ## [2.3.0] - 2026-09-14 (Português)
98
-
99
- ### Adicionado
100
- - **`AdapterErrorCode.TRANSACTION_ROLLED_BACK`** — novo código de erro de adapter para sinalizar que uma transação no banco de dados foi revertida (*rolled back*). Adapters agora podem lançar `VSRepoAdapterError` com esse código para dar ao chamador um sinal claro e tipado de que a transação não foi commitada
101
-
102
- ### Corrigido
103
- - A documentação e o JSDoc nos READMEs e JavaDocs agora informam corretamente que os placeholders de SQL são **específicos do banco de dados** (ex.: `?` para MySQL, `$1`/`$2` para PostgreSQL) em vez de implicar uma sintaxe universal única
104
-
105
- ### Documentação
106
- - Documentado o estado atual do `VSRepoDrizzleAdapter` — funcionalidades disponíveis, limitações e trabalho planejado
107
- - Documentado o novo `AdapterErrorCode.TRANSACTION_ROLLED_BACK` em todos os READMEs e JSDoc relevantes
108
-
109
- ---
110
-
111
- ## [2.2.1] - 2026-09-09
112
-
113
- ### Changed
114
- - Build now generates **sourcemap files** (`sourceMap: true`) for easier debugging of the published package
115
- - Added `stripInternal: true` to the build config — declarations for members marked `@internal` are now stripped from the published `.d.ts` files, keeping the public API surface clean
116
- - Added `noImplicitOverride: true` to the TypeScript config, enforcing the `override` keyword on subclass members that override a parent
117
-
118
- ### Fixed
119
- - Documentation and JSDoc for `VSRepoErrorType.DYNAMIC` now correctly state that the error can be thrown by both **dynamic** and **query** methods (previously only mentioned dynamic methods)
120
-
121
- ---
122
-
123
- ## [2.2.1] - 2026-09-09 (Português)
124
-
125
- ### Alterado
126
- - A build agora gera **arquivos sourcemap** (`sourceMap: true`) para facilitar a depuração do pacote publicado
127
- - Adicionado `stripInternal: true` na config de build — declarações de membros marcados com `@internal` agora são removidas dos arquivos `.d.ts` publicados, mantendo a superfície da API pública limpa
128
- - Adicionado `noImplicitOverride: true` no config do TypeScript, forçando a palavra-chave `override` em membros de subclasses que sobrescrevem um pai
129
-
130
- ### Corrigido
131
- - A documentação e o JSDoc do `VSRepoErrorType.DYNAMIC` agora informam corretamente que o erro pode ser lançado tanto por métodos **dynamic** quanto por **query methods** (antes mencionava apenas métodos dinâmicos)
132
-
133
- ---
134
-
135
- ## [2.2.0] - 2026-09-06
136
-
137
- ### Added
138
- - **`singleResult` option** on `@QueryMethod` and `query()` — collapses an array result into its first element (`null` if the array is empty) instead of leaving it as an array. Has no effect on non-array results (e.g. a `modifying` query's affected-row count). Useful for queries known to return at most one row (a `SELECT ... LIMIT 1` or a lookup by a unique column)
139
- - **`spreadArgs` option** on `@QueryMethod` — receive SQL placeholder values as separate positional arguments (`method(a, b, c)`), JpaRepository style, instead of a single `QueryMethodArg` object (`method({ args: [a, b, c] })`). Calling a method declared without `spreadArgs` using more than one argument now throws a `VSRepoError` (`type: VALIDATOR`), since the single-object call style is expected instead
140
- - **`DbArg<T>` / `withDb()`** — wrap a database client or transaction (`withDb(tx)`) to pass it as the trailing argument of a `spreadArgs` call, running that query against `tx` instead of the repository's default client. Recognized via `instanceof`, so it never collides with a regular positional argument, even one that happens to be an object
141
- - New public type `QueryArgs<T, O>` — types the spread parameter list of a `@QueryMethod` declared with `{ spreadArgs: true }`: `T`'s values in order, followed by an optional trailing `DbArg<O>`
142
- - Implementation tests covering `singleResult` and `spreadArgs` (including the `DbArg`/`withDb` extraction and the call-arity guard), plus README docs and JSDoc for every new option, type and function
143
-
144
- ### Changed
145
- - `QueryMethodOptions.modifying` is now optional (defaults to `false` at runtime, matching the decorator's existing behavior when `options` is omitted entirely) — previously required at the type level even though omitting it worked fine
146
-
147
- ---
148
-
149
- ## [2.2.0] - 2026-09-06 (Português)
150
-
151
- ### Adicionado
152
- - **Option `singleResult`** no `@QueryMethod` e no `query()` — transforma um resultado em array no seu primeiro elemento (`null` se o array estiver vazio) em vez de deixá-lo como array. Não tem efeito em resultados que não são array (ex.: o número de linhas afetadas de uma query `modifying`). Útil para queries que já se sabe que retornam no máximo uma linha (um `SELECT ... LIMIT 1` ou uma busca por uma coluna única)
153
- - **Option `spreadArgs`** no `@QueryMethod` — recebe os valores dos placeholders SQL como argumentos posicionais separados (`method(a, b, c)`), no estilo do JpaRepository, em vez de um único objeto `QueryMethodArg` (`method({ args: [a, b, c] })`). Chamar um método declarado sem `spreadArgs` usando mais de um argumento agora lança um `VSRepoError` (`type: VALIDATOR`), já que o estilo de chamada com objeto único é o esperado
154
- - **`DbArg<T>` / `withDb()`** — embrulha um client ou transação do banco (`withDb(tx)`) para passá-lo como argumento final de uma chamada com `spreadArgs`, rodando aquela query contra `tx` em vez do client padrão do repository. Reconhecido via `instanceof`, então nunca é confundido com um argumento posicional comum, mesmo que esse argumento seja um objeto
155
- - Novo tipo público `QueryArgs<T, O>` — tipa a lista de parâmetros via spread de um `@QueryMethod` declarado com `{ spreadArgs: true }`: os valores de `T`, em ordem, seguidos de um `DbArg<O>` opcional
156
- - Testes de implementação cobrindo `singleResult` e `spreadArgs` (incluindo a extração de `DbArg`/`withDb` e o guard de arity da chamada), além de documentação nos READMEs e JSDoc para cada nova option, tipo e função
157
-
158
- ### Alterado
159
- - `QueryMethodOptions.modifying` agora é opcional (default `false` em runtime, alinhado ao comportamento já existente do decorator quando `options` é omitido por completo) — antes era obrigatório no nível de tipos, mesmo que omiti-lo já funcionasse normalmente
160
-
161
- ---
162
-
163
- ## [2.1.0] - 2026-09-04
164
-
165
- ### Added
166
- - **Atomic operations** — new `increment(pk, field, value)`, `decrement`, `multiply` and `divide` methods on `VSRepository`. They are evaluated **server-side** against the row's *current* value (`UPDATE ... SET field = field + value`), not as a client-side read-modify-write, and each returns the record reflecting the state *after* the write. The `value` argument accepts `number`, `bigint` or `DecimalLike` and is validated at runtime
167
- - **Aggregation methods** — new `sum`, `average`, `min` and `max` methods that compute the value across every record matching an optional `where` (all records if omitted). All four return `number | null` — `null` when no record matches, mirroring SQL's `SUM()`/`AVG()`/`MIN()`/`MAX()`, which return `NULL` (not `0`) over an empty set
168
- - **`VSRepoAdapter` contract extended** with the 8 corresponding abstract methods: `incrementOne`, `decrementOne`, `multiplyOne`, `divideOne`, `sum`, `average`, `min`, `max`
169
- - New public types: `NumericKeys<T>` (extracts the numeric fields eligible as `field`), `NumericLike` (`number | bigint | DecimalLike`), `DecimalLike` (structural shape of arbitrary-precision decimals such as Prisma's `Prisma.Decimal`), and `RestrictMethodOptions`
170
- - `Primitive` now also includes `DecimalLike`, so Decimal-typed fields are treated as scalar (non-relation) values when walking an entity's shape
171
- - Implementation and typing tests covering the atomic and aggregate methods, plus README docs and JSDoc for every new method and type
172
-
173
- > **Note for adapter authors:** the new abstract methods are **breaking** for anyone implementing a custom `VSRepoAdapter` — existing adapters must implement all 8 before they compile against 2.1.0. Published adapters (e.g. `@vsrepo/prisma7-adapter`) may not implement them yet; confirm the adapter version supports them before relying on `increment`/`sum`/etc.
174
-
175
- ### Changed
176
- - `total`, `has`, `removeList`, `softRemoveList` and `restoreList` now accept the narrowed `RestrictMethodOptions` (`db`/`see` only) instead of the full `MethodOptions` — these methods don't shape/return an `Entity`, so `select`/`relations` no longer apply at the type level
177
- - The `v1` folder was removed from the `main` branch — the v1 source and docs now live exclusively on the dedicated `v1` branch (READMEs updated to point there)
178
-
179
- ---
180
-
181
- ## [2.1.0] - 2026-09-04 (Português)
182
-
183
- ### Adicionado
184
- - **Operações atômicas** — novos métodos `increment(pk, field, value)`, `decrement`, `multiply` e `divide` no `VSRepository`. Elas são avaliadas **server-side** contra o valor *atual* do registro (`UPDATE ... SET field = field + value`), e não como um read-modify-write no cliente, e cada uma retorna o registro refletindo o estado *após* a escrita. O argumento `value` aceita `number`, `bigint` ou `DecimalLike` e é validado em tempo de execução
185
- - **Métodos de agregação** — novos métodos `sum`, `average`, `min` e `max` que calculam o valor entre todos os registros que correspondem a um `where` opcional (todos os registros se omitido). Os quatro retornam `number | null` — `null` quando nenhum registro corresponde, espelhando o `SUM()`/`AVG()`/`MIN()`/`MAX()` do SQL, que retornam `NULL` (não `0`) sobre um conjunto vazio
186
- - **Contrato do `VSRepoAdapter` estendido** com os 8 métodos abstratos correspondentes: `incrementOne`, `decrementOne`, `multiplyOne`, `divideOne`, `sum`, `average`, `min`, `max`
187
- - Novos tipos públicos: `NumericKeys<T>` (extrai os campos numéricos elegíveis como `field`), `NumericLike` (`number | bigint | DecimalLike`), `DecimalLike` (formato estrutural de decimais de alta precisão, como o `Prisma.Decimal` do Prisma) e `RestrictMethodOptions`
188
- - `Primitive` agora também inclui `DecimalLike`, então campos com tipo Decimal são tratados como valores escalares (não-relation) ao percorrer a forma da entidade
189
- - Testes de implementação e de tipagem cobrindo os métodos atômicos e de agregação, além de documentação nos READMEs e JSDoc para cada novo método e tipo
190
-
191
- > **Nota para autores de adapters:** os novos métodos abstratos são uma mudança **breaking** para quem implementa um `VSRepoAdapter` customizado — adapters existentes precisam implementar os 8 antes de compilarem contra a 2.1.0. Adapters publicados (ex.: `@vsrepo/prisma7-adapter`) podem ainda não os implementar; confirme que a versão do adapter suporta antes de usar `increment`/`sum`/etc.
192
-
193
- ### Alterado
194
- - `total`, `has`, `removeList`, `softRemoveList` e `restoreList` agora aceitam o `RestrictMethodOptions` restrito (somente `db`/`see`) em vez do `MethodOptions` completo — esses métodos não moldam/retornam uma `Entity`, então `select`/`relations` não se aplicam mais no nível de tipos
195
- - A pasta `v1` foi removida da branch `main` — o código-fonte e a documentação da v1 agora vivem exclusivamente na branch `v1` dedicada (READMEs atualizados para apontar para lá)
196
-
197
- ---
198
-
199
- ## [2.0.0] - 2026-09-01
200
-
201
- > Major rewrite. If you're upgrading from v1, see the ["What changed from v1"](./README.md#what-changed-from-v1) table in the README for the full breakdown before migrating.
202
-
203
- ### Changed
204
- - **BREAKING:** VSRepository is now **ORM-agnostic** — the core no longer talks to Prisma directly, it delegates every operation to a pluggable `VSRepoAdapter`. ORM support now ships as separate packages (e.g. `@vsrepo/prisma7-adapter`) instead of being bundled in the core `vsrepo` package
205
- - **BREAKING:** Repositories are now defined with a single **class-based** API — `extends VSRepository<Entity, PKType, OrmTypes>` — replacing the v1 functional `setupVSRepo<T, M>()({...}).build(prisma)` and the `DynamicRepository` class
206
- - **BREAKING:** Dynamic methods are now declared only with the `@DynamicMethod()` decorator on a `declare` field, replacing the `methods: { findByEmail: { map: true } }` config object
207
- - **BREAKING:** Data projections are now ad-hoc `select`/`relations` passed per call — named, reusable `selectModels`/`defaultSelectModel` were removed
208
- - **BREAKING:** Eager loading now uses an ORM-agnostic `relations` option instead of the Prisma-specific `include`/`includeModels`
209
- - **BREAKING:** `requiredWhere` was removed; global scoping is now limited to `softRemoveKey` + a `see: "active" | "removed" | "all"` option
210
- - **BREAKING:** The case-insensitive filter suffix was renamed from `Insensitive` to `IgnoreCase`
211
- - **BREAKING:** The `createMany` duplicate-handling suffix was renamed from `SkipDuplicates` to `IgnoreConflicts`
212
- - **BREAKING:** Error types were reworked — `VSRepoError` now carries a `type: VSRepoErrorType` field (`DECORATOR`, `RESOLVER`, `DYNAMIC`, `VALIDATOR`, `BASE`, `ADAPTER`); the old subclasses (`VSRepoConfigError`, `VSRepoBuildError`, `VSRepoExtendError`) were replaced by the new `VSRepoAdapterError`, which carries an `AdapterErrorCode` and the original ORM error
213
- - **BREAKING:** Debug logging changed from a `showWorking: true` boolean to a `logLevel: VSLogLevel` (`DEBUG`/`INFO`/`WARN`/`ERROR`) option, plus a new `logSlowThresholdMs` for slow-query warnings
214
- - **BREAKING:** The `vsrepo generate` CLI type-generation step is no longer part of the v2 core — types now come directly from your entity/ORM types
215
- - Runtime validation (ordering, pagination, where, adapter config) now uses `valibot` instead of `zod`, for a lighter footprint
216
- - Inline ordering can now be baked directly into a dynamic method name via `OrderBy<Field>Asc`/`OrderBy<Field>Desc` chains
217
- - v1 source and docs moved to a dedicated `v1` branch for anyone who still needs the previous Prisma-only release
218
-
219
- ### Added
220
- - An ad-hoc `query()` method for raw SQL queries, with transaction support via `db: tx`
221
- - `VSRepoAdapterError` with a dedicated `AdapterErrorCode`, including a new `INVALID_ADAPTER_CONFIG` code, for surfacing adapter-level failures
222
- - `VSLogger` exported for use inside custom adapters
223
- - JSDoc added to every public API surface (everything marked `@publicApi`)
224
- - First official adapter published: [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) (Prisma 7); other ORMs (Prisma 8, TypeORM, Drizzle) are planned but not yet published
225
-
226
- ### Fixed
227
- - The case-insensitive mode was being injected in the wrong place when combined with relation filters, producing an incorrect `where`
228
- - Corrected the argument-index preview shown when an argument is a `where` object
229
-
230
- ### Removed
231
- - `patchList` — for a batch partial update, use an `updateManyBy`/`updateManyWhere` dynamic method instead
232
- - `aggregate`/`groupBy` passthrough support — not implemented yet in v2
233
-
234
- ---
235
-
236
- ## [2.0.0] - 2026-09-01 (Português)
237
-
238
- > Reescrita major. Se você está migrando da v1, veja a tabela ["O que mudou da v1"](./README.pt-BR.md#o-que-mudou-da-v1) no README para o detalhamento completo antes de migrar.
239
-
240
- ### Alterado
241
- - **BREAKING:** O VSRepository agora é **agnóstico de ORM** — o core não conversa mais diretamente com o Prisma, delegando toda operação a um `VSRepoAdapter` plugável. O suporte a ORMs agora é publicado em pacotes separados (ex.: `@vsrepo/prisma7-adapter`) em vez de vir embutido no pacote core `vsrepo`
242
- - **BREAKING:** Repositories agora são definidos com uma única API **baseada em classes** — `extends VSRepository<Entity, PKType, OrmTypes>` — substituindo o `setupVSRepo<T, M>()({...}).build(prisma)` funcional da v1 e a classe `DynamicRepository`
243
- - **BREAKING:** Métodos dinâmicos agora são declarados somente com o decorator `@DynamicMethod()` em um campo `declare`, substituindo o objeto de config `methods: { findByEmail: { map: true } }`
244
- - **BREAKING:** Projeções de dados agora são `select`/`relations` ad-hoc passados em cada chamada — os `selectModels`/`defaultSelectModel` nomeados e reutilizáveis foram removidos
245
- - **BREAKING:** Eager loading agora usa uma option agnóstica de ORM chamada `relations`, no lugar do `include`/`includeModels` específico do Prisma
246
- - **BREAKING:** O `requiredWhere` foi removido; o escopo global agora se limita a `softRemoveKey` + uma option `see: "active" | "removed" | "all"`
247
- - **BREAKING:** O sufixo de filtro case-insensitive foi renomeado de `Insensitive` para `IgnoreCase`
248
- - **BREAKING:** O sufixo de tratamento de duplicados do `createMany` foi renomeado de `SkipDuplicates` para `IgnoreConflicts`
249
- - **BREAKING:** Os tipos de erro foram reformulados — `VSRepoError` agora carrega um campo `type: VSRepoErrorType` (`DECORATOR`, `RESOLVER`, `DYNAMIC`, `VALIDATOR`, `BASE`, `ADAPTER`); as antigas subclasses (`VSRepoConfigError`, `VSRepoBuildError`, `VSRepoExtendError`) foram substituídas pelo novo `VSRepoAdapterError`, que carrega um `AdapterErrorCode` e o erro original do ORM
250
- - **BREAKING:** O log de debug mudou de um boolean `showWorking: true` para uma option `logLevel: VSLogLevel` (`DEBUG`/`INFO`/`WARN`/`ERROR`), além de um novo `logSlowThresholdMs` para avisos de queries lentas
251
- - **BREAKING:** O passo de geração de tipos via CLI `vsrepo generate` não faz mais parte do core da v2 — os tipos agora vêm diretamente das suas entidades/tipos do ORM
252
- - A validação em tempo de execução (ordering, pagination, where, config do adapter) agora usa `valibot` em vez de `zod`, por ser mais leve
253
- - A ordenação inline agora pode ser embutida diretamente no nome do método dinâmico via cadeias `OrderBy<Campo>Asc`/`OrderBy<Campo>Desc`
254
- - O código-fonte e a documentação da v1 foram movidos para uma branch `v1` dedicada, para quem ainda precisar da release anterior baseada apenas em Prisma
255
-
256
- ### Adicionado
257
- - Um método `query()` ad-hoc para queries SQL raw, com suporte a transações via `db: tx`
258
- - `VSRepoAdapterError` com um `AdapterErrorCode` dedicado, incluindo um novo código `INVALID_ADAPTER_CONFIG`, para expor falhas em nível de adapter
259
- - `VSLogger` agora é exportado para uso dentro de adapters customizados
260
- - JSDoc adicionado a toda a API pública (tudo marcado com `@publicApi`)
261
- - Primeiro adapter oficial publicado: [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) (Prisma 7); outros ORMs (Prisma 8, TypeORM, Drizzle) estão planejados mas ainda não publicados
262
-
263
- ### Corrigido
264
- - O modo case-insensitive estava sendo injetado no lugar errado quando combinado com filtros de relação, gerando um `where` incorreto
265
- - Corrigida a preview do índice do argumento exibida quando um argumento é um objeto `where`
266
-
267
- ### Removido
268
- - `patchList` — para uma atualização parcial em lote, use um método dinâmico `updateManyBy`/`updateManyWhere`
269
- - Suporte de passthrough para `aggregate`/`groupBy` — ainda não implementado na v2
270
-
271
- ---
272
-
273
- ## [1.4.2] - 2026-09-02
274
-
275
- ### Fixed
276
- - `merge` method now strips `undefined` fields from the source object before merging — previously, when merging objects without relations, `undefined` values from the source were carried into the result, which could overwrite existing fields with `undefined`
277
-
278
- ---
279
-
280
- ## [1.4.2] - 2026-09-02 (Português)
281
-
282
- ### Corrigido
283
- - O método `merge` agora remove campos com valor `undefined` do objeto de origem antes de mesclar — antes, ao mesclar objetos sem relations, valores `undefined` do objeto de origem eram propagados para o resultado, o que poderia sobrescrever campos existentes com `undefined`
284
-
285
- ---
286
-
287
- ## [1.4.1] - 2026-09-01
288
-
289
- ### Fixed
290
- - `mode: "insensitive"` was being injected at the wrong level in relation filters — previously, `otherProps` (which includes `mode`) was being assigned to `path[argName]` (the nested relation object) instead of the current filter level, causing the insensitive mode to be placed incorrectly in the generated `where`
291
-
292
- ---
293
-
294
- ## [1.4.1] - 2026-09-01 (Português)
295
-
296
- ### Corrigido
297
- - `mode: "insensive"` estava sendo injetado no nível errado em filtros de relations — antes, `otherProps` (que inclui `mode`) era atribuído a `path[argName]` (o objeto da relation aninhada) em vez do nível atual do filtro, causando colocação incorreta do modo insensitive no `where` gerado
298
-
299
- ---
300
-
301
- ## [1.4.0] - 2026-08-11
302
-
303
- ### Fixed
304
- - Dynamic methods combining multiple filters on the **same relation** no longer lose all but the last filter — previously, filters like `findBy...AndEnderecoWithEstadoAndEnderecoWithCidadeNormalizadaStartsWith...` produced a `where` with only the last relation filter (`estado` was lost), because `resolveSpecificWhere` merged the generated paths with `Object.assign` (shallow merge). It now uses `deepmerge` (deep merge), so relation filters coexist correctly (e.g. `endereco: { is: { estado, cidadeNormalizada } }`)
305
-
306
- ### Added
307
- - Regression tests (`test/implementation/specific-where.test.ts`) covering multiple filters on the same relation in `resolveSpecificWhere`, including plain fields, relation filters, OR/AND groups, pure `With` combined with `WithField`, and `betweenMode` combined with another operator on the same field
308
-
309
- ---
310
-
311
- ## [1.4.0] - 2026-08-11 (Português)
312
-
313
- ### Corrigido
314
- - Métodos dinâmicos que combinam múltiplos filtros na **mesma relation** não perdem mais todos os filtros exceto o último — antes, filtros como `findBy...AndEnderecoWithEstadoAndEnderecoWithCidadeNormalizadaStartsWith...` geravam um `where` apenas com o último filtro da relation (`estado` era perdido), porque o `resolveSpecificWhere` mesclava os caminhos gerados com `Object.assign` (merge raso). Agora ele usa `deepmerge` (merge profundo), fazendo os filtros de relation coexistirem corretamente (ex.: `endereco: { is: { estado, cidadeNormalizada } }`)
315
-
316
- ### Adicionado
317
- - Testes de regressão (`test/implementation/specific-where.test.ts`) cobrindo múltiplos filtros na mesma relation em `resolveSpecificWhere`, incluindo campos simples, filtros de relation, grupos OR/AND, `With` puro combinado com `WithCampo`, e `betweenMode` combinado com outro operador no mesmo campo
318
-
319
- ---
320
-
321
- ## [1.3.9] - 2026-08-10
322
-
323
- ### Added
324
- - Now `README.md` and `README.pt-BR.md` include the `VSRepository` logo for visual identity.
325
-
326
- ---
327
-
328
- ## [1.3.9] - 2026-08-10 (Português)
329
-
330
- ### Adicionado
331
- - Agora `README.md` e `README.pt-BR.md` contém a logo do `VSRepository` para identidade visual.
332
-
333
- ---
334
-
335
- ## [1.3.8] - 2026-08-03
336
-
337
- ### Fixed
338
- - `vsrepo generate` now copies the README files from the `vsrepo` package root (`node_modules/vsrepo` or the repository itself) instead of the consumer project's root — previously it copied the consumer's own `README.md` and failed to find the other READMEs (`README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) when they didn't exist in the consumer project
339
-
340
- ### Changed
341
- - The `files` field in `package.json` now explicitly includes the README files (`README.md`, `README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) so they are shipped inside the published npm package — previously only `README.md` and `README.pt-BR.md` were included automatically by npm, leaving the `README-DynamicRepo*` files missing from the installed package
342
-
343
- ---
344
-
345
- ## [1.3.8] - 2026-08-03 (Português)
346
-
347
- ### Corrigido
348
- - `vsrepo generate` agora copia os READMEs da raiz do pacote `vsrepo` (`node_modules/vsrepo` ou o próprio repositório) em vez da raiz do projeto do consumidor — antes ele copiava o `README.md` do próprio consumidor e falhava ao não encontrar os demais READMEs (`README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) quando eles não existiam no projeto do consumidor
349
-
350
- ### Alterado
351
- - O campo `files` no `package.json` agora inclui explicitamente os arquivos README (`README.md`, `README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) para que sejam empacotados no pacote npm publicado — antes apenas `README.md` e `README.pt-BR.md` eram incluídos automaticamente pelo npm, deixando os arquivos `README-DynamicRepo*` ausentes do pacote instalado
352
-
353
- ---
354
-
355
- ## [1.3.7] - 2026-08-03
356
-
357
- ### Added
358
- - `vsrepo generate` now copies the project READMEs (`README.md`, `README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) to a `docs/` folder inside the generated output directory
359
-
360
- ### Changed
361
- - The generated output now includes a `docs/` directory containing the project documentation
362
-
363
- ---
364
-
365
- ## [1.3.7] - 2026-08-03 (Português)
366
-
367
- ### Adicionado
368
- - `vsrepo generate` agora copia os READMEs do projeto (`README.md`, `README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) para uma pasta `docs/` dentro do diretório de saída gerado
369
-
370
- ### Alterado
371
- - A saída gerada agora inclui um diretório `docs/` contendo a documentação do projeto
372
-
373
- ---
374
-
375
- ## [1.3.6] - 2026-08-01
376
-
377
- ### Added
378
- - `ordering` support in method options, replacing `ordenation` as the preferred name while keeping full backward compatibility — `ordenation` is now marked as deprecated
379
- - GitHub Actions CI workflow (`.github/workflows/ci.yml`) to lint, typecheck and test the project on every push and pull request
380
- - Error handling tests (`test/implementation/error-handling.test.ts`) covering the `VSRepoRuntimeError` error codes
381
- - Documentation of all `VSRepoRuntimeError` error codes in README.md and README.pt-BR.md
382
-
383
- ### Fixed
384
- - Generated `index.ts` now exports the `VSRepoDecoratorError` class (previously missing from the generated output, preventing consumers from importing it)
385
- - Fixed internal typo `dinamic` → `dynamic` in file names, constants and types (e.g. `dynamic-method-info`, `dynamic-method-customization`, `dynamic-methods-key`)
386
-
387
- ### Changed
388
- - Tests, examples and documentation updated to use `ordering` instead of `ordenation`
389
- - `ordenation` marked as deprecated in favor of `ordering` (still fully supported)
390
- - Reformatted Markdown documentation files for better consistency and readability
391
-
392
- ---
393
-
394
- ## [1.3.6] - 2026-08-01 (Português)
395
-
396
- ### Adicionado
397
- - Suporte a `ordering` nas options dos métodos, substituindo `ordenation` como nome preferido mantendo compatibilidade total com versões anteriores — `ordenation` agora está marcado como deprecated
398
- - Workflow de CI do GitHub Actions (`.github/workflows/ci.yml`) para executar lint, typecheck e testes a cada push e pull request
399
- - Testes de error handling (`test/implementation/error-handling.test.ts`) cobrindo os códigos de erro do `VSRepoRuntimeError`
400
- - Documentação de todos os códigos de erro do `VSRepoRuntimeError` no README.md e README.pt-BR.md
401
-
402
- ### Corrigido
403
- - O `index.ts` gerado agora exporta a classe `VSRepoDecoratorError` (antes ausente na saída gerada, impedindo que consumidores conseguissem importá-la)
404
- - Corrigido typo interno `dinamic` → `dynamic` em nomes de arquivos, constantes e tipos (ex.: `dynamic-method-info`, `dynamic-method-customization`, `dynamic-methods-key`)
405
-
406
- ### Alterado
407
- - Testes, exemplos e documentação atualizados para usar `ordering` no lugar de `ordenation`
408
- - `ordenation` marcado como deprecated em favor de `ordering` (ainda totalmente suportado)
409
- - Reformatados os arquivos de documentação Markdown para melhor consistência e legibilidade
410
-
411
- ---
412
-
413
- ## [1.3.5] - 2026-07-27
414
-
415
- ### Added
416
- - Raw `select` support in method options (`options.select`): pass a raw Prisma `select` directly in a method call, without registering it beforehand in `selectModels` — mirrors the existing raw `include` (`options.include`)
417
- - Full typing for `options.select`: works across all base methods (`get`, `getOrThrow`, `getList`, `remove`, `save`, `saveList`, `patch`, `patchList`, `merge`, `getAll`, `softRemove`, `restore`) and dynamics, narrows the return type to exactly the selected fields, and is mutually exclusive with `selectModel`, `includeModel` and `include`
418
- - `select` field added to `DynamicMethodOptions` (class-based `DynamicRepository` API)
419
- - Documentation for raw `select` in README.md, README-DynamicRepo.md and their Portuguese counterparts
420
- - Runtime validation for `QueryMethod`'s `value` parameter — throws `VSRepoDecoratorError` if it isn't a string
421
- - Reorganized the project's tests into a dedicated `test/` folder: `test/implementation` (Jest-based runtime tests, replacing the old root-level `teste.ts`/`teste-class.ts`) and `test/typing` (compile-time type tests checked via `tsc --noEmit`, using `@ts-expect-error` to assert invalid usages are rejected)
422
- - New npm scripts: `test`, `test:implementation`, `test:implementation:watch`, `test:typing`
423
- - Implementation and typing tests for raw `select`, covering both the functional (`setupVSRepo`) and class-based (`DynamicRepository`) APIs
424
-
425
- ### Fixed
426
- - Generated `VSRepoError.ts` now also exports `VSRepoDecoratorError` (previously missing from the generated output, causing consumers to be unable to import it)
427
-
428
- ### Changed
429
- - Updated the generated file tree diagram in the README to include the `DynamicRepository.ts`/`DynamicRepository.types.d.ts` files
430
-
431
- ---
432
-
433
- ## [1.3.5] - 2026-07-27 (Português)
434
-
435
- ### Adicionado
436
- - Suporte a `select` cru nas options dos métodos (`options.select`): permite passar um `select` bruto do Prisma diretamente na chamada, sem precisar registrá-lo antecipadamente em `selectModels` — espelha o `include` cru (`options.include`) já existente
437
- - Tipagem completa para `options.select`: funciona em todos os métodos base (`get`, `getOrThrow`, `getList`, `remove`, `save`, `saveList`, `patch`, `patchList`, `merge`, `getAll`, `softRemove`, `restore`) e dinâmicos, restringe o tipo de retorno exatamente aos campos selecionados, e é mutuamente exclusivo com `selectModel`, `includeModel` e `include`
438
- - Campo `select` adicionado ao `DynamicMethodOptions` (API baseada em classes `DynamicRepository`)
439
- - Documentação do `select` cru no README.md, README-DynamicRepo.md e suas versões em português
440
- - Validação em tempo de execução do parâmetro `value` do `QueryMethod` — lança `VSRepoDecoratorError` caso não seja uma string
441
- - Reorganização dos testes do projeto em uma pasta `test/` dedicada: `test/implementation` (testes de runtime com Jest, substituindo os antigos `teste.ts`/`teste-class.ts` na raiz) e `test/typing` (testes de tipagem em tempo de compilação, checados com `tsc --noEmit`, usando `@ts-expect-error` para garantir que usos inválidos são rejeitados)
442
- - Novos scripts npm: `test`, `test:implementation`, `test:implementation:watch`, `test:typing`
443
- - Testes de implementação e de tipagem para o `select` cru, cobrindo tanto a API funcional (`setupVSRepo`) quanto a baseada em classes (`DynamicRepository`)
444
-
445
- ### Corrigido
446
- - O `VSRepoError.ts` gerado agora também exporta `VSRepoDecoratorError` (antes ausente na saída gerada, impedindo que consumidores conseguissem importá-lo)
447
-
448
- ### Alterado
449
- - Atualizado o diagrama da árvore de arquivos gerados no README para incluir os arquivos `DynamicRepository.ts`/`DynamicRepository.types.d.ts`
450
-
451
- ---
452
-
453
- ## [1.3.4] - 2026-07-25
454
-
455
- ### Added
456
- - Query Methods: new `@QueryMethod` decorator (class-based) and `query` config (functional) for defining raw SQL query methods that bypass the name-parsing engine
457
- - Support for non-modifying queries (`$queryRawUnsafe`) and modifying queries (`$executeRawUnsafe`, `modifying: true`)
458
- - `QueryMethodArg` type for typing the `{ args, db? }` parameter
459
- - Transaction support for query methods via `db: tx` parameter
460
- - Query methods documentation
461
- - Query methods examples
462
- - Tests for query methods in both functional and class-based approaches
463
-
464
- ### Changed
465
- - Clarified in documentation that the `WRelations` generic in `DynamicRepository` is optional and explained when to use it
466
- - Translated documentation to Portuguese
467
-
468
- ---
469
-
470
- ## [1.3.4] - 2026-07-25 (Português)
471
-
472
- ### Adicionado
473
- - Query Methods: novo decorador `@QueryMethod` (abordagem class-based) e config `query` (abordagem funcional) para definir métodos de query SQL raw que ignoram o engine de parsing por nome
474
- - Suporte para queries não-modificantes (`$queryRawUnsafe`) e modificantes (`$executeRawUnsafe`, `modifying: true`)
475
- - Tipo `QueryMethodArg` para tipar o parâmetro `{ args, db? }`
476
- - Suporte a transações para query methods via parâmetro `db: tx`
477
- - Documentação dos query methods
478
- - Exemplos dos query methods
479
- - Testes para query methods nas abordagens funcional e class-based
480
-
481
- ### Alterado
482
- - Esclarecido na documentação que a generic `WRelations` no `DynamicRepository` é opcional e explicado quando utilizá-la
483
- - Documentação traduzida para português
484
-
485
- ---
486
-
487
- ## [1.3.3] - 2026-07-22
488
-
489
- ### Added
490
- - DynamicRepository: base structure for dynamic repository functionality
491
- - Complete typing for DynamicRepository and DynamicMethod
492
- - Native Prisma `include` support in method options typing
493
- - Real implementation for raw include support
494
- - Improved build logging
495
- - DynamicRepository documentation (README-DynamicRepo.md)
496
- - DynamicRepository examples
497
- - Tests for DynamicRepository and include parameter
498
-
499
- ### Fixed
500
- - Fixed typing for objects with relations
501
- - Fixed DynamicRepository typing
502
- - Fixed DynamicMethod typing
503
- - Fixed pushWhere error in some dynamic methods
504
-
505
- ### Changed
506
- - Translated package.json description to English
507
-
508
- ---
509
-
510
- ## [1.3.3] - 2026-07-22 (Português)
511
-
512
- ### Adicionado
513
- - DynamicRepository: estrutura base da funcionalidade de repositório dinâmico
514
- - Tipagem completa para DynamicRepository e DynamicMethod
515
- - Suporte nativo ao `include` do Prisma na tipagem das opções de método
516
- - Implementação real do suporte ao include raw
517
- - Melhoria nos logs de build
518
- - Documentação do DynamicRepository (README-DynamicRepo.md)
519
- - Exemplos para DynamicRepository
520
- - Testes para DynamicRepository e parâmetro include
521
-
522
- ### Corrigido
523
- - Correção da tipagem dos objetos com relations
524
- - Correção da tipagem do DynamicRepository
525
- - Correção da tipagem do DynamicMethod
526
- - Correção do erro do pushWhere em alguns métodos dinâmicos
527
-
528
- ### Alterado
529
- - Descrição do package.json traduzida para inglês
530
-
531
- ---
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ (Português) Todas as mudanças notáveis neste projeto serão documentadas neste arquivo.
6
+
7
+ ---
8
+
9
+ ## [2.7.0] - 2026-09-26
10
+
11
+ ### Added
12
+ - **`createRawQueryBuilder(db?)`** — new method on every `VSRepository` that returns a fluent, SQL-agnostic `VSRawQueryBuilder` for hand-written `SELECT` queries too SQL-specific (window functions, vendor-specific syntax, ad-hoc subqueries, CTEs, ...) for `createQueryBuilder()`'s `where`/`relations` model. Chain `select`, `from`, `innerJoin`/`leftJoin`/`rightJoin`/`fullJoin`, `where`/`andWhere`/`orWhere`, `groupBy`, `having`/`andHaving`/`orHaving`, `orderBy`, `limit` and `offset` — each accepting either a raw, trusted string (an identifier, or a parameter-free condition for `on`/`where`/`having`, e.g. `.andWhere("deleted_at is null")`) or a `VSSql` fragment for anything parameterized. `from()`/joins also accept another `VSRawQueryBuilder`, or a subquery function (`sub => sub.select(...)...`) that receives a fresh builder sharing the same `db`/adapter/logger, compiled inline as a subquery; any subquery can also be spliced directly into a `VSSql` fragment via `toVSSql()` (e.g. inside a `WHERE ... IN (...)`). `with(name, query, columns?)`/`withRecursive(name, query, columns?)` add named CTEs (a single `WITH RECURSIVE` clause once any CTE is recursive) that the rest of the query can reference like real tables. Run it with `toVSSql()` (the compiled `VSSql` fragment), `toSql()` (the plain SQL string, rendered with the adapter's placeholder syntax) or `execute<T>()` (runs it through the adapter and returns the result); all three require the adapter to implement `getPlaceholder()`. The builder respects `clone()` and lazy `setDb()`, same as `createQueryBuilder()`, and is exported as `VSRawQueryBuilder`/`VSRawQueryBuilderTarget`/`VSRawQueryBuilderCteQuery`. Every raw string accepted as an identifier, condition, alias or CTE name/column is validated as non-empty/non-blank as soon as it's passed, throwing a `VSRepoError` instead of silently compiling into broken SQL
13
+ - **`VSSql`** — ORM-agnostic, composable SQL fragments for raw queries: build one with `VSSql.sql` (a tagged template where every interpolated value becomes a bound parameter), `VSSql.raw` (inserts trusted, unparameterized text — for identifiers only, never user input), `VSSql.join` (builds a parameterized list, e.g. an `IN (...)`) and `VSSql.empty` (contributes no text/params, for conditional fragments). Fragments nest freely and the placeholder numbering stays correct; passing one to `VSRepository.query()` compiles it through `adapter.getPlaceholder()` — so `VSSql` works with every database and is safe from SQL injection by construction
14
+ - **`vsPlaceholders`** constructor option — when `true`, raw SQL strings passed to `query()` and `@QueryMethod` use VSRepository's own agnostic, 1-based, positional placeholders (`?1`, `?2`, ...) instead of the adapter's native syntax; the same index can repeat (`?1 ... ?1`) to reuse an argument. Requires the adapter to implement `getPlaceholder()` — enabling it without one throws a `VSRepoError`
15
+ - **`VSRepoAdapter.getPlaceholder?`** — new optional adapter method declaring the placeholder syntax for the Nth (0-based) bound parameter (e.g. `` `$${index + 1}` `` for PostgreSQL, `"?"` for SQLite/MySQL). Implementing it is what enables `VSSql` fragments and `vsPlaceholders`
16
+ - **Query method logs** — `query()` and `@QueryMethod` now log the compiled query and its args at `DEBUG` (the `db` is never logged) and time the execution (`Took Xms ...`, promoted to `WARN` above `logSlowThresholdMs`), like the rest of the library
17
+
18
+ ### Documentation
19
+ - New [Raw query builder](./docs/raw-query-builder.md) guide, covering `createRawQueryBuilder()`, building the query, subqueries (builder or function), CTEs with `with()`/`withRecursive()`, running it (`toVSSql`/`toSql`/`execute`), transactions/`setDb()`, cloning, validation and logs — added to both READMEs' documentation index, with a cross-link from the [Query builder](./docs/query-builder.md) guide
20
+
21
+ ## [2.7.0] - 2026-09-26 (Português)
22
+
23
+ ### Adicionado
24
+ - **`createRawQueryBuilder(db?)`** — novo método em todo `VSRepository` que retorna um `VSRawQueryBuilder` fluente e agnóstico de SQL para queries `SELECT` escritas à mão, específicas demais (funções de janela, sintaxe específica do banco, subqueries ad-hoc, CTEs, ...) para o modelo `where`/`relations` do `createQueryBuilder()`. Encadeie `select`, `from`, `innerJoin`/`leftJoin`/`rightJoin`/`fullJoin`, `where`/`andWhere`/`orWhere`, `groupBy`, `having`/`andHaving`/`orHaving`, `orderBy`, `limit` e `offset` — cada um aceitando uma string crua e confiável (um identificador, ou uma condição sem parâmetros para `on`/`where`/`having`, ex.: `.andWhere("deleted_at is null")`) ou um fragmento `VSSql` para qualquer coisa parametrizada. `from()`/joins também aceitam outro `VSRawQueryBuilder`, ou uma função de subquery (`sub => sub.select(...)...`) que recebe um builder novo compartilhando o mesmo `db`/adapter/logger, compilada inline como subquery; qualquer subquery também pode ser inserida diretamente num fragmento `VSSql` via `toVSSql()` (ex.: dentro de um `WHERE ... IN (...)`). `with(name, query, columns?)`/`withRecursive(name, query, columns?)` adicionam CTEs nomeadas (uma única cláusula `WITH RECURSIVE` quando qualquer CTE é recursiva) que o resto da query pode referenciar como tabelas normais. Execute com `toVSSql()` (o fragmento `VSSql` compilado), `toSql()` (a string SQL simples, renderizada com a sintaxe de placeholder do adapter) ou `execute<T>()` (executa através do adapter e retorna o resultado); os três exigem que o adapter implemente `getPlaceholder()`. O builder respeita `clone()` e `setDb()` lazy, igual ao `createQueryBuilder()`, e é exportado como `VSRawQueryBuilder`/`VSRawQueryBuilderTarget`/`VSRawQueryBuilderCteQuery`. Toda string crua aceita como identificador, condição, alias ou nome/coluna de CTE é validada como não-vazia/não-em-branco assim que é passada, lançando um `VSRepoError` em vez de compilar silenciosamente em SQL quebrado
25
+ - **`VSSql`** — fragmentos SQL agnósticos de ORM e componíveis para queries raw: monte um com `VSSql.sql` (um template literal com tag em que todo valor interpolado vira um parâmetro ligado), `VSSql.raw` (insere texto confiável e não parametrizado — só para identificadores, nunca input do usuário), `VSSql.join` (monta uma lista parametrizada, ex.: um `IN (...)`) e `VSSql.empty` (não contribui com texto nem parâmetros, para fragmentos condicionais). Fragmentos aninham livremente e a numeração dos placeholders continua correta; passar um para o `VSRepository.query()` compila via `adapter.getPlaceholder()` — então `VSSql` funciona com qualquer banco e é seguro contra SQL injection por construção
26
+ - **Option `vsPlaceholders`** no construtor — quando `true`, strings SQL cruas passadas para `query()` e `@QueryMethod` usam os placeholders próprios, agnósticos, posicionais e de base 1 do VSRepository (`?1`, `?2`, ...) em vez da sintaxe nativa do adapter; o mesmo índice pode se repetir (`?1 ... ?1`) para reutilizar um argumento. Exige que o adapter implemente `getPlaceholder()` — ligar essa option sem ele lança um `VSRepoError`
27
+ - **`VSRepoAdapter.getPlaceholder?`** — novo método opcional no adapter que declara a sintaxe de placeholder para o N-ésimo (base 0) parâmetro ligado (ex.: `` `$${index + 1}` `` para o PostgreSQL, `"?"` para SQLite/MySQL). Implementá-lo é o que habilita os fragmentos `VSSql` e o `vsPlaceholders`
28
+ - **Logs dos métodos de query** — `query()` e `@QueryMethod` agora logam a query compilada e seus args em `DEBUG` (o `db` nunca é logado) e medem a execução (`Took Xms ...`, promovido para `WARN` acima do `logSlowThresholdMs`), como no resto da biblioteca
29
+
30
+ ### Documentação
31
+ - Novo guia [Raw query builder](./docs/raw-query-builder.pt-BR.md), cobrindo o `createRawQueryBuilder()`, a construção da query, subqueries (builder ou função), CTEs com `with()`/`withRecursive()`, execução (`toVSSql`/`toSql`/`execute`), transações/`setDb()`, clonagem, validação e logs — adicionado ao índice de documentação dos dois READMEs, com um cross-link a partir do guia [Query builder](./docs/query-builder.pt-BR.md)
32
+
33
+ ## [2.6.0] - 2026-09-24
34
+
35
+ ### Added
36
+ - **`createQueryBuilder(db?)`** — new method on every `VSRepository` that returns a fluent query builder for queries assembled at runtime. Chain `select`, `relations`, `where`, `orderBy`, `limit`, `offset`, `distinctOn` and `see`, then run it with `getResult()`, `getOneResult()`, `getOneResultOrThrow()`, `getCount()`, `getExistence()` or `getResultAndCount()`. `where()` takes the same `VSRepoWhere` filter used by the rest of the library (including `AND`/`OR`/`NOT`). The last terminal method fetches a page and the total of records matching the `where` (ignoring `order`/`pagination`, so it can be used for pagination) in parallel. The builder respects soft-delete (`see("active")` by default), `clone()` derives independent builders from a common base, and `setDb()` lets you choose lazily where the query runs — e.g. build it first and run it inside a `transaction()`. `distinctOn` only affects `getResult()`, since `count` doesn't support `distinct`
37
+ - **`VSQueryBuilder`** — the class is exported from the package entry point, so builders can be typed (e.g. as a function parameter). All its public methods are documented with JSDoc
38
+ - **`VSRepoErrorType.QUERY_BUILDER`** — new error type, thrown as a `VSRepoError` when an invalid argument is passed to a query builder method
39
+ - **Query builder logs** — the builder uses the repository's logger: at `DEBUG` it traces every chained call and the resolved query of each terminal method (the `db` is never logged), and each terminal method is timed (`Took Xms to run query builder <method>`, promoted to `WARN` above `logSlowThresholdMs`)
40
+ - **`Equals` / `NotEquals`** field-filter suffixes for dynamic methods — same effect as no suffix and `Not`, respectively; useful to disambiguate a field name that ends at the same camelCase boundary as an existing keyword suffix (e.g. `findByCheckInEquals` resolves to the field `checkIn`, instead of the default `check` + `In` reading)
41
+ - **`lazyDynamicMethods`** constructor option — when `true`, postpones resolving `@DynamicMethod`/`@QueryMethod` methods until the subclass calls the `protected resolveDynamicMethods()` itself, instead of resolving them synchronously in the constructor. Useful for deferring the resolution cost to a more convenient point in the app's lifecycle (e.g. an async init hook), and lets fields annotated with `@DynamicMethod`/`@QueryMethod` skip the `declare` modifier as long as `resolveDynamicMethods()` is called after calls `supper()`. Calling `resolveDynamicMethods()` again after it already resolved once logs a `WARN`, since it's redundant
42
+
43
+ ### Changed
44
+ - `pagination` validation is now stricter: `limit` and `offset` must be non-negative integers. Negative, decimal and infinite values, previously accepted, are now rejected
45
+ - `select` and `relations` passed in the `options` of any method are now validated recursively: every value must be a `boolean` or a nested object (previously any object was accepted)
46
+ - Dynamic-method name parsing is significantly more robust (inspired by Spring Data JPA's `PartTree`): keywords and operators (`Or`, `And`, `AND`, `Not`, `In`, `With`, `Without`, `Some`, `Every`, `None`, `Optional`, ...) are now only recognized at a camelCase word boundary, so field names that merely contain one of these words — `organizationId`, `notes`, `orderId`, `instagramHandle`, `withdrawnAt`, `androidVersion`, `everyoneId`, and the like — are no longer misparsed
47
+ - Using an ordering/pagination suffix (`Paginated`/`Ordered`/`OrderBy...`), `Distinct` or `IgnoreConflicts` on a dynamic-method prefix that doesn't support it, or using `Or` after an `AND` (all caps) block, now throws a `VSRepoError` (`RESOLVER`) when the repository is constructed, instead of silently becoming part of the field name
48
+
49
+ ### Fixed
50
+ - A relation filter (`With`/`Without`/`Some`/`Every`/`None`) combined with equality and `IgnoreCase` (e.g. `findByAddressWithCityEqualsIgnoreCase`) now nests correctly as `{ equals, ignoreCase }`
51
+ - A dynamic-method name that places `Distinct` **after** `OrderBy` (e.g. `findByActiveOrderByCreatedAtDescDistinctName`) now throws a `VSRepoError` (`RESOLVER`) when the repository is constructed, instead of silently parsing `Distinct` as part of a non-existent ordering field
52
+
53
+ ### Documentation
54
+ - Both READMEs document the query builder: new "Query builder" section, a new row in the base methods table, `QUERY_BUILDER` in the error types tables, and a note about the builder in the Logging section
55
+ - Both READMEs document `Equals`/`NotEquals`, the camelCase-boundary rule for keyword collisions (with the `Equals`/`NotEquals` disambiguation example), and the new explicit errors for unsupported suffix/prefix combinations and for `Or` after `AND`
56
+ - New "Lazily resolving dynamic methods" section in the dynamic-methods guide, covering `lazyDynamicMethods`, why `declare` becomes unnecessary once resolution is deferred, and the `WARN` logged on a redundant `resolveDynamicMethods()` call; `lazyDynamicMethods` also added to the constructor options table in the base-methods guide
57
+ - **Docs restructured**: the root READMEs (EN/PT) are now a short overview — intro, what changed from v1, adapter status, installation, basic usage, development, requirements, contributing — with a documentation index. Feature-by-feature detail (base methods & configuration, soft-delete, `select`/`relations`, dynamic methods, query methods, query builder, transactions, utility types, writing an adapter, error handling, logging) moved into its own guide under [`docs/`](./docs), each in English and Portuguese, with more examples than before (e.g. concrete DEBUG/WARN log output in the logging guide, transaction return-value/rollback and query-builder examples in the transactions guide)
58
+
59
+ ---
60
+
61
+ ## [2.6.0] - 2026-09-24 (Português)
62
+
63
+ ### Adicionado
64
+ - **`createQueryBuilder(db?)`** — novo método em todo `VSRepository` que retorna um query builder fluente para queries montadas em tempo de execução. Encadeie `select`, `relations`, `where`, `orderBy`, `limit`, `offset`, `distinctOn` e `see`, e execute com `getResult()`, `getOneResult()`, `getOneResultOrThrow()`, `getCount()`, `getExistence()` ou `getResultAndCount()`. O `where()` recebe o mesmo filtro `VSRepoWhere` usado no resto da biblioteca (inclusive `AND`/`OR`/`NOT`). O último método terminal busca uma página e o total de registros que batem com o `where` (ignorando `order`/`pagination`, então serve para paginação) em paralelo. O builder respeita o soft-delete (`see("active")` por padrão), o `clone()` deriva builders independentes de uma base comum, e o `setDb()` permite escolher de forma lazy onde a query roda — ex.: montá-la antes e executá-la dentro de um `transaction()`. O `distinctOn` só afeta o `getResult()`, já que o `count` não suporta `distinct`
65
+ - **`VSQueryBuilder`** — a classe é exportada pelo ponto de entrada do pacote, então dá para tipar builders (ex.: como parâmetro de função). Todos os seus métodos públicos têm JSDoc
66
+ - **`VSRepoErrorType.QUERY_BUILDER`** — novo tipo de erro, lançado como `VSRepoError` quando um argumento inválido é passado para um método do query builder
67
+ - **Logs do query builder** — o builder usa o logger do repository: em `DEBUG` ele registra cada chamada encadeada e a query resolvida de cada método terminal (o `db` nunca é logado), e cada método terminal tem o tempo medido (`Took Xms to run query builder <método>`, promovido a `WARN` acima de `logSlowThresholdMs`)
68
+ - **Sufixos `Equals` / `NotEquals`** para métodos dinâmicos — mesmo efeito de sem sufixo e de `Not`, respectivamente; úteis para desambiguar um campo cujo nome termina na mesma fronteira de camelCase de um sufixo/palavra-chave já existente (ex.: `findByCheckInEquals` resolve para o campo `checkIn`, em vez da leitura padrão `check` + `In`)
69
+ - **Option `lazyDynamicMethods` do construtor** — quando `true`, adia a resolução dos métodos `@DynamicMethod`/`@QueryMethod` até que a própria subclasse chame o `protected resolveDynamicMethods()`, em vez de resolvê-los de forma síncrona no construtor. Útil para adiar o custo da resolução para um momento mais oportuno do ciclo de vida da aplicação (ex.: um hook de inicialização assíncrona), e permite que campos anotados com `@DynamicMethod`/`@QueryMethod` dispensem o modificador `declare`, desde que `resolveDynamicMethods()` seja chamado depois de chamar `super()`. Chamar `resolveDynamicMethods()` de novo depois que ele já resolveu uma vez registra um `WARN`, já que é redundante
70
+
71
+ ### Alterado
72
+ - A validação de `pagination` ficou mais estrita: `limit` e `offset` precisam ser inteiros não negativos. Valores negativos, decimais e infinitos, antes aceitos, agora são rejeitados
73
+ - `select` e `relations` passados nas `options` de qualquer método agora são validados recursivamente: todo valor precisa ser `boolean` ou um objeto aninhado (antes qualquer objeto era aceito)
74
+ - A resolução de nomes de métodos dinâmicos ficou bem mais robusta (inspirada no `PartTree` do Spring Data JPA): palavras-chave e operadores (`Or`, `And`, `AND`, `Not`, `In`, `With`, `Without`, `Some`, `Every`, `None`, `Optional`, ...) só são reconhecidos numa fronteira de camelCase, então campos cujo nome apenas contém uma dessas palavras — `organizationId`, `notes`, `orderId`, `instagramHandle`, `withdrawnAt`, `androidVersion`, `everyoneId` e afins — deixam de ser interpretados errado
75
+ - Usar um sufixo de ordenação/paginação (`Paginated`/`Ordered`/`OrderBy...`), `Distinct` ou `IgnoreConflicts` num prefixo de método dinâmico que não os suporta, ou usar `Or` depois de um bloco `AND` (maiúsculo), agora lança um `VSRepoError` (`RESOLVER`) ao construir o repository, em vez de virar silenciosamente parte do nome do campo
76
+
77
+ ### Corrigido
78
+ - Um filtro de relação (`With`/`Without`/`Some`/`Every`/`None`) combinado com igualdade e `IgnoreCase` (ex.: `findByAddressWithCityEqualsIgnoreCase`) agora aninha corretamente como `{ equals, ignoreCase }`
79
+ - Um nome de método dinâmico que coloca `Distinct` **depois** de `OrderBy` (ex.: `findByActiveOrderByCreatedAtDescDistinctName`) agora lança um `VSRepoError` (`RESOLVER`) ao construir o repository, em vez de silenciosamente interpretar o `Distinct` como parte de um campo de ordenação inexistente
80
+
81
+ ### Documentação
82
+ - Ambos os READMEs documentam o query builder: nova seção "Query builder", uma nova linha na tabela de métodos base, `QUERY_BUILDER` nas tabelas de tipos de erro, e uma observação sobre o builder na seção de Logging
83
+ - Ambos os READMEs documentam `Equals`/`NotEquals`, a regra de fronteira de camelCase para colisões de palavra-chave (com o exemplo de desambiguação via `Equals`/`NotEquals`), e os novos erros explícitos para combinações de sufixo/prefixo não suportadas e para `Or` depois de `AND`
84
+ - Nova seção "Resolução lazy dos métodos dinâmicos" no guia de métodos dinâmicos, cobrindo o `lazyDynamicMethods`, o porquê do `declare` deixar de ser necessário quando a resolução é adiada, e o `WARN` registrado numa chamada redundante de `resolveDynamicMethods()`; `lazyDynamicMethods` também foi adicionado à tabela de options do construtor no guia de métodos base
85
+ - **Documentação reestruturada**: os READMEs da raiz (EN/PT) agora são uma visão geral curta — intro, o que mudou da v1, status dos adapters, instalação, uso básico, desenvolvimento, requisitos, contribuição — com um índice de documentação. O detalhamento de cada funcionalidade (métodos base & configuração, soft-delete, `select`/`relations`, métodos dinâmicos, query methods, query builder, transações, tipos utilitários, escrevendo um adapter, tratamento de erros, logging) foi para um guia próprio dentro de [`docs/`](./docs), cada um em português e em inglês, com mais exemplos do que antes (ex.: saída real de log em DEBUG/WARN no guia de logging, exemplos de valor de retorno/rollback de transação e de query builder no guia de transações)
86
+
87
+ ---
88
+
89
+ ## [2.5.0] - 2026-09-20
90
+
91
+ > Promotes `2.5.0-beta` to stable.
92
+
93
+ ---
94
+
95
+ ## [2.5.0] - 2026-09-20 (Português)
96
+
97
+ > Promove `2.5.0-beta` para estável.
98
+
99
+ ---
100
+
101
+ ## [2.5.0-beta] - 2026-09-19
102
+
103
+ ### Added
104
+ - **`InferMethodReturn<T, Options>`** — new opt-in utility type for stricter return typing, exported from the package entry point. It narrows the type returned by a method (`Entity`, `Entity | null` or `Entity[]`) to the fields and relations actually requested through `select`/`relations`, instead of the whole entity: with no options only the scalar fields are returned; with `relations`, the scalar fields plus the requested relations (nested ones included); with `select`, only the selected fields (a relation set to `true` brings all of its scalar fields, and a nested `select` restricts it further). When both are passed, `select` takes precedence and `relations` is ignored. `null`/array-ness and optional (`?`) modifiers are preserved, and if the options are typed as a plain `MethodOptions<T>` (not narrowed) the whole entity is returned unchanged. The default typing of the methods is **not** changed
105
+ - **`InferMethodType<Args, Return, OrmTypes?>`** — new utility type, exported from the package entry point, to declare dynamic methods whose return type is inferred on each call from the `select`/`relations` passed in `options`: `@DynamicMethod() declare findByName: InferMethodType<[name: string], User[]>`. Calls without `options` return only the scalar fields. Unknown keys in `select`/`relations` (at any depth) are rejected at compile time, and the editor autocompletes them, just like with a plain `MethodOptions<T>` parameter. The third generic (`OrmTypes`) is optional and types the `db` option
106
+ - **`getPkName?(): string`** - new optional method that allows the adapter to declare the entity's primary key field to the repository. When instantiating a `VSRepository`, you can omit `pkName` from the constructor options, and it will be read from `adapter.getPkName()`. If you omit it and the adapter does not implement `getPkName()`, the constructor throws a `VSRepoError`
107
+
108
+ ### Documentation
109
+ - Both READMEs document the new types: new "Strict return typing with `InferMethodReturn`" and "Strict return typing with `InferMethodType`" sections, a pointer in the dynamic-methods intro, and two new rows in the utility types table
110
+ - Documents the new optional `getPkName?(): string` method of `VSRepoAdapter`
111
+
112
+ ### Fixed
113
+ - Fixed the `OrderByField` typing so it doesn't claim to accept nested ordering
114
+
115
+ ---
116
+
117
+ ## [2.5.0-beta] - 2026-09-19 (Português)
118
+
119
+ ### Adicionado
120
+ - **`InferMethodReturn<T, Options>`** — novo tipo utilitário opt-in para uma tipagem de retorno mais restrita, exportado pelo entry point do pacote. Ele estreita o tipo retornado por um método (`Entity`, `Entity | null` ou `Entity[]`) para os campos e relações realmente pedidos via `select`/`relations`, em vez da entidade inteira: sem options, apenas os campos escalares; com `relations`, os campos escalares mais as relações pedidas (inclusive as aninhadas); com `select`, apenas os campos selecionados (uma relação com `true` traz todos os seus campos escalares, e um `select` aninhado a restringe ainda mais). Quando os dois são passados, `select` tem precedência e `relations` é ignorado. `null`/array e os modificadores opcionais (`?`) são preservados, e se as options estiverem tipadas como um `MethodOptions<T>` genérico (sem estreitamento) a entidade inteira é retornada sem alterações. A tipagem padrão dos métodos **não** foi alterada
121
+ - **`InferMethodType<Args, Return, OrmTypes?>`** — novo tipo utilitário, exportado pelo entry point do pacote, para declarar métodos dinâmicos cujo tipo de retorno é inferido a cada chamada a partir do `select`/`relations` passados em `options`: `@DynamicMethod() declare findByName: InferMethodType<[name: string], User[]>`. Chamadas sem `options` retornam apenas os campos escalares. Chaves inexistentes em `select`/`relations` (em qualquer profundidade) são rejeitadas em tempo de compilação, e o editor as sugere via autocomplete, igual a um parâmetro `MethodOptions<T>` comum. A terceira generic (`OrmTypes`) é opcional e tipa a option `db`
122
+ - **`getPkName?(): string`** - novo método opcional permite que o adapter declare ao repository qual campo é a primary key da entidade. Ao instanciar um `VSRepository`, você pode omitir o `pkName` das options do construtor e ele será lido do `adapter.getPkName()`. Se você omitir e o adapter não implementar o `getPkName()`, o construtor lança um `VSRepoError`
123
+
124
+ ### Documentação
125
+ - Ambos os READMEs documentam os novos tipos: novas seções "Tipagem de retorno restrita com `InferMethodReturn`" e "Tipagem de retorno restrita com `InferMethodType`", uma indicação na introdução de métodos dinâmicos, e duas novas linhas na tabela de tipos utilitários
126
+ - Documenta o novo método opcional `getPkName?(): string` do `VSRepoAdapter`
127
+
128
+ ### Corrigido
129
+ - Corrigida a tipagem do `OrderByField` para não dizer que aceita nested ordering
130
+
131
+ ---
132
+
133
+ ## [2.4.0] - 2026-09-16
134
+
135
+ ### Added
136
+ - **`logSlowThresholdMs: false`** — passing `false` to `logSlowThresholdMs` (on `VSRepoOptions` or on the `VSLogger` constructor) now disables slow-operation warnings entirely, without having to set an arbitrarily large threshold. Passing `true` or omitting the option keeps the existing 300 ms default. The accepted type is now `number | boolean` instead of `number`
137
+
138
+ ### Changed
139
+ - `@vsrepo/drizzle-adapter` is now available as an **alpha** release on npm — install it with `npm i @vsrepo/drizzle-adapter@alpha`. The API may still change before the stable release; check the [`DrizzleAdapter`](https://github.com/jaobrabo123/VSRepoDrizzleAdapter) repository for the current status and known limitations
140
+
141
+ ### Documentation
142
+ - `proxyTo` decorator option now has a dedicated code example in both READMEs, showing the main use case: giving a method a custom name (e.g. a non-English name) while internally resolving it to a valid dynamic-method pattern
143
+ - `groupBy` is documented as **not planned** for v2; `aggregate` as a dynamic-method prefix is also unlikely to be added since the most common aggregate operations are already available as dedicated base methods (`sum`, `average`, `min`, `max`, `increment`, `decrement`, `multiply`, `divide`) — `@QueryMethod` with raw SQL is the recommended escape hatch for anything more complex
144
+ - Multiple README improvements: fixed and expanded the constructor-options table, corrected examples in the dynamic-methods section, improved descriptions across several utility-type entries, and removed the outdated TypeORM `relations` note from the `select`/`relations` section
145
+
146
+ ---
147
+
148
+ ## [2.4.0] - 2026-09-16 (Português)
149
+
150
+ ### Adicionado
151
+ - **`logSlowThresholdMs: false`** — passar `false` em `logSlowThresholdMs` (no `VSRepoOptions` ou no construtor do `VSLogger`) agora desabilita completamente os avisos de operação lenta, sem precisar definir um threshold arbitrariamente grande. Passar `true` ou omitir a option mantém o padrão existente de 300 ms. O tipo aceito agora é `number | boolean` em vez de `number`
152
+
153
+ ### Alterado
154
+ - `@vsrepo/drizzle-adapter` agora está disponível como versão **alpha** no npm — instale com `npm i @vsrepo/drizzle-adapter@alpha`. A API ainda pode mudar antes do release estável; veja o repositório do [`DrizzleAdapter`](https://github.com/jaobrabo123/VSRepoDrizzleAdapter) para o estado atual e limitações conhecidas
155
+
156
+ ### Documentação
157
+ - A option `proxyTo` do decorador agora tem um exemplo de código dedicado em ambos os READMEs, mostrando o principal caso de uso: dar um nome customizado a um método (ex.: um nome em outro idioma) enquanto ele resolve internamente para um padrão de método dinâmico válido
158
+ - `groupBy` está documentado como **não planejado** para a v2; `aggregate` como prefixo de método dinâmico também dificilmente será adicionado, já que as operações de agregação mais comuns já estão disponíveis como métodos base dedicados (`sum`, `average`, `min`, `max`, `increment`, `decrement`, `multiply`, `divide`) — `@QueryMethod` com SQL raw é o escape hatch recomendado para qualquer coisa mais complexa
159
+ - Diversas melhorias nos READMEs: tabela de constructor options corrigida e expandida, exemplos na seção de métodos dinâmicos corrigidos, descrições melhoradas em várias entradas de tipos utilitários, e remoção da nota desatualizada sobre TypeORM e `relations` na seção `select`/`relations`
160
+
161
+ ---
162
+
163
+ ## [2.3.0] - 2026-09-14
164
+
165
+ ### Added
166
+ - **`AdapterErrorCode.TRANSACTION_ROLLED_BACK`** — new adapter error code to signal that a database transaction was rolled back. Adapters can now throw `VSRepoAdapterError` with this code to give callers a clear, typed signal that the transaction did not commit
167
+
168
+ ### Fixed
169
+ - Documentation and JSDoc across READMEs and JavaDocs now correctly state that SQL placeholders are **database-specific** (e.g. `?` for MySQL, `$1`/`$2` for PostgreSQL) instead of implying a single universal syntax
170
+
171
+ ### Documentation
172
+ - Documented the current state of `VSRepoDrizzleAdapter` — available features, limitations, and planned work
173
+ - Documented the new `AdapterErrorCode.TRANSACTION_ROLLED_BACK` in all relevant READMEs and JSDoc
174
+
175
+ ---
176
+
177
+ ## [2.3.0] - 2026-09-14 (Português)
178
+
179
+ ### Adicionado
180
+ - **`AdapterErrorCode.TRANSACTION_ROLLED_BACK`** — novo código de erro de adapter para sinalizar que uma transação no banco de dados foi revertida (*rolled back*). Adapters agora podem lançar `VSRepoAdapterError` com esse código para dar ao chamador um sinal claro e tipado de que a transação não foi commitada
181
+
182
+ ### Corrigido
183
+ - A documentação e o JSDoc nos READMEs e JavaDocs agora informam corretamente que os placeholders de SQL são **específicos do banco de dados** (ex.: `?` para MySQL, `$1`/`$2` para PostgreSQL) em vez de implicar uma sintaxe universal única
184
+
185
+ ### Documentação
186
+ - Documentado o estado atual do `VSRepoDrizzleAdapter` — funcionalidades disponíveis, limitações e trabalho planejado
187
+ - Documentado o novo `AdapterErrorCode.TRANSACTION_ROLLED_BACK` em todos os READMEs e JSDoc relevantes
188
+
189
+ ---
190
+
191
+ ## [2.2.1] - 2026-09-09
192
+
193
+ ### Changed
194
+ - Build now generates **sourcemap files** (`sourceMap: true`) for easier debugging of the published package
195
+ - Added `stripInternal: true` to the build config — declarations for members marked `@internal` are now stripped from the published `.d.ts` files, keeping the public API surface clean
196
+ - Added `noImplicitOverride: true` to the TypeScript config, enforcing the `override` keyword on subclass members that override a parent
197
+
198
+ ### Fixed
199
+ - Documentation and JSDoc for `VSRepoErrorType.DYNAMIC` now correctly state that the error can be thrown by both **dynamic** and **query** methods (previously only mentioned dynamic methods)
200
+
201
+ ---
202
+
203
+ ## [2.2.1] - 2026-09-09 (Português)
204
+
205
+ ### Alterado
206
+ - A build agora gera **arquivos sourcemap** (`sourceMap: true`) para facilitar a depuração do pacote publicado
207
+ - Adicionado `stripInternal: true` na config de build — declarações de membros marcados com `@internal` agora são removidas dos arquivos `.d.ts` publicados, mantendo a superfície da API pública limpa
208
+ - Adicionado `noImplicitOverride: true` no config do TypeScript, forçando a palavra-chave `override` em membros de subclasses que sobrescrevem um pai
209
+
210
+ ### Corrigido
211
+ - A documentação e o JSDoc do `VSRepoErrorType.DYNAMIC` agora informam corretamente que o erro pode ser lançado tanto por métodos **dynamic** quanto por **query methods** (antes mencionava apenas métodos dinâmicos)
212
+
213
+ ---
214
+
215
+ ## [2.2.0] - 2026-09-06
216
+
217
+ ### Added
218
+ - **`singleResult` option** on `@QueryMethod` and `query()` — collapses an array result into its first element (`null` if the array is empty) instead of leaving it as an array. Has no effect on non-array results (e.g. a `modifying` query's affected-row count). Useful for queries known to return at most one row (a `SELECT ... LIMIT 1` or a lookup by a unique column)
219
+ - **`spreadArgs` option** on `@QueryMethod` — receive SQL placeholder values as separate positional arguments (`method(a, b, c)`), JpaRepository style, instead of a single `QueryMethodArg` object (`method({ args: [a, b, c] })`). Calling a method declared without `spreadArgs` using more than one argument now throws a `VSRepoError` (`type: VALIDATOR`), since the single-object call style is expected instead
220
+ - **`DbArg<T>` / `withDb()`** — wrap a database client or transaction (`withDb(tx)`) to pass it as the trailing argument of a `spreadArgs` call, running that query against `tx` instead of the repository's default client. Recognized via `instanceof`, so it never collides with a regular positional argument, even one that happens to be an object
221
+ - New public type `QueryArgs<T, O>` — types the spread parameter list of a `@QueryMethod` declared with `{ spreadArgs: true }`: `T`'s values in order, followed by an optional trailing `DbArg<O>`
222
+ - Implementation tests covering `singleResult` and `spreadArgs` (including the `DbArg`/`withDb` extraction and the call-arity guard), plus README docs and JSDoc for every new option, type and function
223
+
224
+ ### Changed
225
+ - `QueryMethodOptions.modifying` is now optional (defaults to `false` at runtime, matching the decorator's existing behavior when `options` is omitted entirely) — previously required at the type level even though omitting it worked fine
226
+
227
+ ---
228
+
229
+ ## [2.2.0] - 2026-09-06 (Português)
230
+
231
+ ### Adicionado
232
+ - **Option `singleResult`** no `@QueryMethod` e no `query()` — transforma um resultado em array no seu primeiro elemento (`null` se o array estiver vazio) em vez de deixá-lo como array. Não tem efeito em resultados que não são array (ex.: o número de linhas afetadas de uma query `modifying`). Útil para queries que já se sabe que retornam no máximo uma linha (um `SELECT ... LIMIT 1` ou uma busca por uma coluna única)
233
+ - **Option `spreadArgs`** no `@QueryMethod` — recebe os valores dos placeholders SQL como argumentos posicionais separados (`method(a, b, c)`), no estilo do JpaRepository, em vez de um único objeto `QueryMethodArg` (`method({ args: [a, b, c] })`). Chamar um método declarado sem `spreadArgs` usando mais de um argumento agora lança um `VSRepoError` (`type: VALIDATOR`), já que o estilo de chamada com objeto único é o esperado
234
+ - **`DbArg<T>` / `withDb()`** — embrulha um client ou transação do banco (`withDb(tx)`) para passá-lo como argumento final de uma chamada com `spreadArgs`, rodando aquela query contra `tx` em vez do client padrão do repository. Reconhecido via `instanceof`, então nunca é confundido com um argumento posicional comum, mesmo que esse argumento seja um objeto
235
+ - Novo tipo público `QueryArgs<T, O>` — tipa a lista de parâmetros via spread de um `@QueryMethod` declarado com `{ spreadArgs: true }`: os valores de `T`, em ordem, seguidos de um `DbArg<O>` opcional
236
+ - Testes de implementação cobrindo `singleResult` e `spreadArgs` (incluindo a extração de `DbArg`/`withDb` e o guard de arity da chamada), além de documentação nos READMEs e JSDoc para cada nova option, tipo e função
237
+
238
+ ### Alterado
239
+ - `QueryMethodOptions.modifying` agora é opcional (default `false` em runtime, alinhado ao comportamento já existente do decorator quando `options` é omitido por completo) — antes era obrigatório no nível de tipos, mesmo que omiti-lo já funcionasse normalmente
240
+
241
+ ---
242
+
243
+ ## [2.1.0] - 2026-09-04
244
+
245
+ ### Added
246
+ - **Atomic operations** — new `increment(pk, field, value)`, `decrement`, `multiply` and `divide` methods on `VSRepository`. They are evaluated **server-side** against the row's *current* value (`UPDATE ... SET field = field + value`), not as a client-side read-modify-write, and each returns the record reflecting the state *after* the write. The `value` argument accepts `number`, `bigint` or `DecimalLike` and is validated at runtime
247
+ - **Aggregation methods** — new `sum`, `average`, `min` and `max` methods that compute the value across every record matching an optional `where` (all records if omitted). All four return `number | null` — `null` when no record matches, mirroring SQL's `SUM()`/`AVG()`/`MIN()`/`MAX()`, which return `NULL` (not `0`) over an empty set
248
+ - **`VSRepoAdapter` contract extended** with the 8 corresponding abstract methods: `incrementOne`, `decrementOne`, `multiplyOne`, `divideOne`, `sum`, `average`, `min`, `max`
249
+ - New public types: `NumericKeys<T>` (extracts the numeric fields eligible as `field`), `NumericLike` (`number | bigint | DecimalLike`), `DecimalLike` (structural shape of arbitrary-precision decimals such as Prisma's `Prisma.Decimal`), and `RestrictMethodOptions`
250
+ - `Primitive` now also includes `DecimalLike`, so Decimal-typed fields are treated as scalar (non-relation) values when walking an entity's shape
251
+ - Implementation and typing tests covering the atomic and aggregate methods, plus README docs and JSDoc for every new method and type
252
+
253
+ > **Note for adapter authors:** the new abstract methods are **breaking** for anyone implementing a custom `VSRepoAdapter` — existing adapters must implement all 8 before they compile against 2.1.0. Published adapters (e.g. `@vsrepo/prisma7-adapter`) may not implement them yet; confirm the adapter version supports them before relying on `increment`/`sum`/etc.
254
+
255
+ ### Changed
256
+ - `total`, `has`, `removeList`, `softRemoveList` and `restoreList` now accept the narrowed `RestrictMethodOptions` (`db`/`see` only) instead of the full `MethodOptions` — these methods don't shape/return an `Entity`, so `select`/`relations` no longer apply at the type level
257
+ - The `v1` folder was removed from the `main` branch — the v1 source and docs now live exclusively on the dedicated `v1` branch (READMEs updated to point there)
258
+
259
+ ---
260
+
261
+ ## [2.1.0] - 2026-09-04 (Português)
262
+
263
+ ### Adicionado
264
+ - **Operações atômicas** — novos métodos `increment(pk, field, value)`, `decrement`, `multiply` e `divide` no `VSRepository`. Elas são avaliadas **server-side** contra o valor *atual* do registro (`UPDATE ... SET field = field + value`), e não como um read-modify-write no cliente, e cada uma retorna o registro refletindo o estado *após* a escrita. O argumento `value` aceita `number`, `bigint` ou `DecimalLike` e é validado em tempo de execução
265
+ - **Métodos de agregação** — novos métodos `sum`, `average`, `min` e `max` que calculam o valor entre todos os registros que correspondem a um `where` opcional (todos os registros se omitido). Os quatro retornam `number | null` — `null` quando nenhum registro corresponde, espelhando o `SUM()`/`AVG()`/`MIN()`/`MAX()` do SQL, que retornam `NULL` (não `0`) sobre um conjunto vazio
266
+ - **Contrato do `VSRepoAdapter` estendido** com os 8 métodos abstratos correspondentes: `incrementOne`, `decrementOne`, `multiplyOne`, `divideOne`, `sum`, `average`, `min`, `max`
267
+ - Novos tipos públicos: `NumericKeys<T>` (extrai os campos numéricos elegíveis como `field`), `NumericLike` (`number | bigint | DecimalLike`), `DecimalLike` (formato estrutural de decimais de alta precisão, como o `Prisma.Decimal` do Prisma) e `RestrictMethodOptions`
268
+ - `Primitive` agora também inclui `DecimalLike`, então campos com tipo Decimal são tratados como valores escalares (não-relation) ao percorrer a forma da entidade
269
+ - Testes de implementação e de tipagem cobrindo os métodos atômicos e de agregação, além de documentação nos READMEs e JSDoc para cada novo método e tipo
270
+
271
+ > **Nota para autores de adapters:** os novos métodos abstratos são uma mudança **breaking** para quem implementa um `VSRepoAdapter` customizado — adapters existentes precisam implementar os 8 antes de compilarem contra a 2.1.0. Adapters publicados (ex.: `@vsrepo/prisma7-adapter`) podem ainda não os implementar; confirme que a versão do adapter suporta antes de usar `increment`/`sum`/etc.
272
+
273
+ ### Alterado
274
+ - `total`, `has`, `removeList`, `softRemoveList` e `restoreList` agora aceitam o `RestrictMethodOptions` restrito (somente `db`/`see`) em vez do `MethodOptions` completo — esses métodos não moldam/retornam uma `Entity`, então `select`/`relations` não se aplicam mais no nível de tipos
275
+ - A pasta `v1` foi removida da branch `main` — o código-fonte e a documentação da v1 agora vivem exclusivamente na branch `v1` dedicada (READMEs atualizados para apontar para lá)
276
+
277
+ ---
278
+
279
+ ## [2.0.0] - 2026-09-01
280
+
281
+ > Major rewrite. If you're upgrading from v1, see the ["What changed from v1"](./README.md#what-changed-from-v1) table in the README for the full breakdown before migrating.
282
+
283
+ ### Changed
284
+ - **BREAKING:** VSRepository is now **ORM-agnostic** — the core no longer talks to Prisma directly, it delegates every operation to a pluggable `VSRepoAdapter`. ORM support now ships as separate packages (e.g. `@vsrepo/prisma7-adapter`) instead of being bundled in the core `vsrepo` package
285
+ - **BREAKING:** Repositories are now defined with a single **class-based** API — `extends VSRepository<Entity, PKType, OrmTypes>` — replacing the v1 functional `setupVSRepo<T, M>()({...}).build(prisma)` and the `DynamicRepository` class
286
+ - **BREAKING:** Dynamic methods are now declared only with the `@DynamicMethod()` decorator on a `declare` field, replacing the `methods: { findByEmail: { map: true } }` config object
287
+ - **BREAKING:** Data projections are now ad-hoc `select`/`relations` passed per call — named, reusable `selectModels`/`defaultSelectModel` were removed
288
+ - **BREAKING:** Eager loading now uses an ORM-agnostic `relations` option instead of the Prisma-specific `include`/`includeModels`
289
+ - **BREAKING:** `requiredWhere` was removed; global scoping is now limited to `softRemoveKey` + a `see: "active" | "removed" | "all"` option
290
+ - **BREAKING:** The case-insensitive filter suffix was renamed from `Insensitive` to `IgnoreCase`
291
+ - **BREAKING:** The `createMany` duplicate-handling suffix was renamed from `SkipDuplicates` to `IgnoreConflicts`
292
+ - **BREAKING:** Error types were reworked — `VSRepoError` now carries a `type: VSRepoErrorType` field (`DECORATOR`, `RESOLVER`, `DYNAMIC`, `VALIDATOR`, `BASE`, `ADAPTER`); the old subclasses (`VSRepoConfigError`, `VSRepoBuildError`, `VSRepoExtendError`) were replaced by the new `VSRepoAdapterError`, which carries an `AdapterErrorCode` and the original ORM error
293
+ - **BREAKING:** Debug logging changed from a `showWorking: true` boolean to a `logLevel: VSLogLevel` (`DEBUG`/`INFO`/`WARN`/`ERROR`) option, plus a new `logSlowThresholdMs` for slow-query warnings
294
+ - **BREAKING:** The `vsrepo generate` CLI type-generation step is no longer part of the v2 core — types now come directly from your entity/ORM types
295
+ - Runtime validation (ordering, pagination, where, adapter config) now uses `valibot` instead of `zod`, for a lighter footprint
296
+ - Inline ordering can now be baked directly into a dynamic method name via `OrderBy<Field>Asc`/`OrderBy<Field>Desc` chains
297
+ - v1 source and docs moved to a dedicated `v1` branch for anyone who still needs the previous Prisma-only release
298
+
299
+ ### Added
300
+ - An ad-hoc `query()` method for raw SQL queries, with transaction support via `db: tx`
301
+ - `VSRepoAdapterError` with a dedicated `AdapterErrorCode`, including a new `INVALID_ADAPTER_CONFIG` code, for surfacing adapter-level failures
302
+ - `VSLogger` exported for use inside custom adapters
303
+ - JSDoc added to every public API surface (everything marked `@publicApi`)
304
+ - First official adapter published: [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) (Prisma 7); other ORMs (Prisma 8, TypeORM, Drizzle) are planned but not yet published
305
+
306
+ ### Fixed
307
+ - The case-insensitive mode was being injected in the wrong place when combined with relation filters, producing an incorrect `where`
308
+ - Corrected the argument-index preview shown when an argument is a `where` object
309
+
310
+ ### Removed
311
+ - `patchList` — for a batch partial update, use an `updateManyBy`/`updateManyWhere` dynamic method instead
312
+ - `aggregate`/`groupBy` passthrough support — not implemented yet in v2
313
+
314
+ ---
315
+
316
+ ## [2.0.0] - 2026-09-01 (Português)
317
+
318
+ > Reescrita major. Se você está migrando da v1, veja a tabela ["O que mudou da v1"](./README.pt-BR.md#o-que-mudou-da-v1) no README para o detalhamento completo antes de migrar.
319
+
320
+ ### Alterado
321
+ - **BREAKING:** O VSRepository agora é **agnóstico de ORM** — o core não conversa mais diretamente com o Prisma, delegando toda operação a um `VSRepoAdapter` plugável. O suporte a ORMs agora é publicado em pacotes separados (ex.: `@vsrepo/prisma7-adapter`) em vez de vir embutido no pacote core `vsrepo`
322
+ - **BREAKING:** Repositories agora são definidos com uma única API **baseada em classes** — `extends VSRepository<Entity, PKType, OrmTypes>` — substituindo o `setupVSRepo<T, M>()({...}).build(prisma)` funcional da v1 e a classe `DynamicRepository`
323
+ - **BREAKING:** Métodos dinâmicos agora são declarados somente com o decorator `@DynamicMethod()` em um campo `declare`, substituindo o objeto de config `methods: { findByEmail: { map: true } }`
324
+ - **BREAKING:** Projeções de dados agora são `select`/`relations` ad-hoc passados em cada chamada — os `selectModels`/`defaultSelectModel` nomeados e reutilizáveis foram removidos
325
+ - **BREAKING:** Eager loading agora usa uma option agnóstica de ORM chamada `relations`, no lugar do `include`/`includeModels` específico do Prisma
326
+ - **BREAKING:** O `requiredWhere` foi removido; o escopo global agora se limita a `softRemoveKey` + uma option `see: "active" | "removed" | "all"`
327
+ - **BREAKING:** O sufixo de filtro case-insensitive foi renomeado de `Insensitive` para `IgnoreCase`
328
+ - **BREAKING:** O sufixo de tratamento de duplicados do `createMany` foi renomeado de `SkipDuplicates` para `IgnoreConflicts`
329
+ - **BREAKING:** Os tipos de erro foram reformulados — `VSRepoError` agora carrega um campo `type: VSRepoErrorType` (`DECORATOR`, `RESOLVER`, `DYNAMIC`, `VALIDATOR`, `BASE`, `ADAPTER`); as antigas subclasses (`VSRepoConfigError`, `VSRepoBuildError`, `VSRepoExtendError`) foram substituídas pelo novo `VSRepoAdapterError`, que carrega um `AdapterErrorCode` e o erro original do ORM
330
+ - **BREAKING:** O log de debug mudou de um boolean `showWorking: true` para uma option `logLevel: VSLogLevel` (`DEBUG`/`INFO`/`WARN`/`ERROR`), além de um novo `logSlowThresholdMs` para avisos de queries lentas
331
+ - **BREAKING:** O passo de geração de tipos via CLI `vsrepo generate` não faz mais parte do core da v2 — os tipos agora vêm diretamente das suas entidades/tipos do ORM
332
+ - A validação em tempo de execução (ordering, pagination, where, config do adapter) agora usa `valibot` em vez de `zod`, por ser mais leve
333
+ - A ordenação inline agora pode ser embutida diretamente no nome do método dinâmico via cadeias `OrderBy<Campo>Asc`/`OrderBy<Campo>Desc`
334
+ - O código-fonte e a documentação da v1 foram movidos para uma branch `v1` dedicada, para quem ainda precisar da release anterior baseada apenas em Prisma
335
+
336
+ ### Adicionado
337
+ - Um método `query()` ad-hoc para queries SQL raw, com suporte a transações via `db: tx`
338
+ - `VSRepoAdapterError` com um `AdapterErrorCode` dedicado, incluindo um novo código `INVALID_ADAPTER_CONFIG`, para expor falhas em nível de adapter
339
+ - `VSLogger` agora é exportado para uso dentro de adapters customizados
340
+ - JSDoc adicionado a toda a API pública (tudo marcado com `@publicApi`)
341
+ - Primeiro adapter oficial publicado: [`@vsrepo/prisma7-adapter`](https://github.com/jaobrabo123/VSRepoPrisma7Adapter) (Prisma 7); outros ORMs (Prisma 8, TypeORM, Drizzle) estão planejados mas ainda não publicados
342
+
343
+ ### Corrigido
344
+ - O modo case-insensitive estava sendo injetado no lugar errado quando combinado com filtros de relação, gerando um `where` incorreto
345
+ - Corrigida a preview do índice do argumento exibida quando um argumento é um objeto `where`
346
+
347
+ ### Removido
348
+ - `patchList` — para uma atualização parcial em lote, use um método dinâmico `updateManyBy`/`updateManyWhere`
349
+ - Suporte de passthrough para `aggregate`/`groupBy` — ainda não implementado na v2
350
+
351
+ ---
352
+
353
+ ## [1.4.2] - 2026-09-02
354
+
355
+ ### Fixed
356
+ - `merge` method now strips `undefined` fields from the source object before merging — previously, when merging objects without relations, `undefined` values from the source were carried into the result, which could overwrite existing fields with `undefined`
357
+
358
+ ---
359
+
360
+ ## [1.4.2] - 2026-09-02 (Português)
361
+
362
+ ### Corrigido
363
+ - O método `merge` agora remove campos com valor `undefined` do objeto de origem antes de mesclar — antes, ao mesclar objetos sem relations, valores `undefined` do objeto de origem eram propagados para o resultado, o que poderia sobrescrever campos existentes com `undefined`
364
+
365
+ ---
366
+
367
+ ## [1.4.1] - 2026-09-01
368
+
369
+ ### Fixed
370
+ - `mode: "insensitive"` was being injected at the wrong level in relation filters — previously, `otherProps` (which includes `mode`) was being assigned to `path[argName]` (the nested relation object) instead of the current filter level, causing the insensitive mode to be placed incorrectly in the generated `where`
371
+
372
+ ---
373
+
374
+ ## [1.4.1] - 2026-09-01 (Português)
375
+
376
+ ### Corrigido
377
+ - `mode: "insensive"` estava sendo injetado no nível errado em filtros de relations — antes, `otherProps` (que inclui `mode`) era atribuído a `path[argName]` (o objeto da relation aninhada) em vez do nível atual do filtro, causando colocação incorreta do modo insensitive no `where` gerado
378
+
379
+ ---
380
+
381
+ ## [1.4.0] - 2026-08-11
382
+
383
+ ### Fixed
384
+ - Dynamic methods combining multiple filters on the **same relation** no longer lose all but the last filter — previously, filters like `findBy...AndEnderecoWithEstadoAndEnderecoWithCidadeNormalizadaStartsWith...` produced a `where` with only the last relation filter (`estado` was lost), because `resolveSpecificWhere` merged the generated paths with `Object.assign` (shallow merge). It now uses `deepmerge` (deep merge), so relation filters coexist correctly (e.g. `endereco: { is: { estado, cidadeNormalizada } }`)
385
+
386
+ ### Added
387
+ - Regression tests (`test/implementation/specific-where.test.ts`) covering multiple filters on the same relation in `resolveSpecificWhere`, including plain fields, relation filters, OR/AND groups, pure `With` combined with `WithField`, and `betweenMode` combined with another operator on the same field
388
+
389
+ ---
390
+
391
+ ## [1.4.0] - 2026-08-11 (Português)
392
+
393
+ ### Corrigido
394
+ - Métodos dinâmicos que combinam múltiplos filtros na **mesma relation** não perdem mais todos os filtros exceto o último — antes, filtros como `findBy...AndEnderecoWithEstadoAndEnderecoWithCidadeNormalizadaStartsWith...` geravam um `where` apenas com o último filtro da relation (`estado` era perdido), porque o `resolveSpecificWhere` mesclava os caminhos gerados com `Object.assign` (merge raso). Agora ele usa `deepmerge` (merge profundo), fazendo os filtros de relation coexistirem corretamente (ex.: `endereco: { is: { estado, cidadeNormalizada } }`)
395
+
396
+ ### Adicionado
397
+ - Testes de regressão (`test/implementation/specific-where.test.ts`) cobrindo múltiplos filtros na mesma relation em `resolveSpecificWhere`, incluindo campos simples, filtros de relation, grupos OR/AND, `With` puro combinado com `WithCampo`, e `betweenMode` combinado com outro operador no mesmo campo
398
+
399
+ ---
400
+
401
+ ## [1.3.9] - 2026-08-10
402
+
403
+ ### Added
404
+ - Now `README.md` and `README.pt-BR.md` include the `VSRepository` logo for visual identity.
405
+
406
+ ---
407
+
408
+ ## [1.3.9] - 2026-08-10 (Português)
409
+
410
+ ### Adicionado
411
+ - Agora `README.md` e `README.pt-BR.md` contém a logo do `VSRepository` para identidade visual.
412
+
413
+ ---
414
+
415
+ ## [1.3.8] - 2026-08-03
416
+
417
+ ### Fixed
418
+ - `vsrepo generate` now copies the README files from the `vsrepo` package root (`node_modules/vsrepo` or the repository itself) instead of the consumer project's root — previously it copied the consumer's own `README.md` and failed to find the other READMEs (`README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) when they didn't exist in the consumer project
419
+
420
+ ### Changed
421
+ - The `files` field in `package.json` now explicitly includes the README files (`README.md`, `README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) so they are shipped inside the published npm package — previously only `README.md` and `README.pt-BR.md` were included automatically by npm, leaving the `README-DynamicRepo*` files missing from the installed package
422
+
423
+ ---
424
+
425
+ ## [1.3.8] - 2026-08-03 (Português)
426
+
427
+ ### Corrigido
428
+ - `vsrepo generate` agora copia os READMEs da raiz do pacote `vsrepo` (`node_modules/vsrepo` ou o próprio repositório) em vez da raiz do projeto do consumidor — antes ele copiava o `README.md` do próprio consumidor e falhava ao não encontrar os demais READMEs (`README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) quando eles não existiam no projeto do consumidor
429
+
430
+ ### Alterado
431
+ - O campo `files` no `package.json` agora inclui explicitamente os arquivos README (`README.md`, `README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) para que sejam empacotados no pacote npm publicado — antes apenas `README.md` e `README.pt-BR.md` eram incluídos automaticamente pelo npm, deixando os arquivos `README-DynamicRepo*` ausentes do pacote instalado
432
+
433
+ ---
434
+
435
+ ## [1.3.7] - 2026-08-03
436
+
437
+ ### Added
438
+ - `vsrepo generate` now copies the project READMEs (`README.md`, `README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) to a `docs/` folder inside the generated output directory
439
+
440
+ ### Changed
441
+ - The generated output now includes a `docs/` directory containing the project documentation
442
+
443
+ ---
444
+
445
+ ## [1.3.7] - 2026-08-03 (Português)
446
+
447
+ ### Adicionado
448
+ - `vsrepo generate` agora copia os READMEs do projeto (`README.md`, `README.pt-BR.md`, `README-DynamicRepo.md`, `README-DynamicRepo.pt-BR.md`) para uma pasta `docs/` dentro do diretório de saída gerado
449
+
450
+ ### Alterado
451
+ - A saída gerada agora inclui um diretório `docs/` contendo a documentação do projeto
452
+
453
+ ---
454
+
455
+ ## [1.3.6] - 2026-08-01
456
+
457
+ ### Added
458
+ - `ordering` support in method options, replacing `ordenation` as the preferred name while keeping full backward compatibility — `ordenation` is now marked as deprecated
459
+ - GitHub Actions CI workflow (`.github/workflows/ci.yml`) to lint, typecheck and test the project on every push and pull request
460
+ - Error handling tests (`test/implementation/error-handling.test.ts`) covering the `VSRepoRuntimeError` error codes
461
+ - Documentation of all `VSRepoRuntimeError` error codes in README.md and README.pt-BR.md
462
+
463
+ ### Fixed
464
+ - Generated `index.ts` now exports the `VSRepoDecoratorError` class (previously missing from the generated output, preventing consumers from importing it)
465
+ - Fixed internal typo `dinamic` → `dynamic` in file names, constants and types (e.g. `dynamic-method-info`, `dynamic-method-customization`, `dynamic-methods-key`)
466
+
467
+ ### Changed
468
+ - Tests, examples and documentation updated to use `ordering` instead of `ordenation`
469
+ - `ordenation` marked as deprecated in favor of `ordering` (still fully supported)
470
+ - Reformatted Markdown documentation files for better consistency and readability
471
+
472
+ ---
473
+
474
+ ## [1.3.6] - 2026-08-01 (Português)
475
+
476
+ ### Adicionado
477
+ - Suporte a `ordering` nas options dos métodos, substituindo `ordenation` como nome preferido mantendo compatibilidade total com versões anteriores — `ordenation` agora está marcado como deprecated
478
+ - Workflow de CI do GitHub Actions (`.github/workflows/ci.yml`) para executar lint, typecheck e testes a cada push e pull request
479
+ - Testes de error handling (`test/implementation/error-handling.test.ts`) cobrindo os códigos de erro do `VSRepoRuntimeError`
480
+ - Documentação de todos os códigos de erro do `VSRepoRuntimeError` no README.md e README.pt-BR.md
481
+
482
+ ### Corrigido
483
+ - O `index.ts` gerado agora exporta a classe `VSRepoDecoratorError` (antes ausente na saída gerada, impedindo que consumidores conseguissem importá-la)
484
+ - Corrigido typo interno `dinamic` → `dynamic` em nomes de arquivos, constantes e tipos (ex.: `dynamic-method-info`, `dynamic-method-customization`, `dynamic-methods-key`)
485
+
486
+ ### Alterado
487
+ - Testes, exemplos e documentação atualizados para usar `ordering` no lugar de `ordenation`
488
+ - `ordenation` marcado como deprecated em favor de `ordering` (ainda totalmente suportado)
489
+ - Reformatados os arquivos de documentação Markdown para melhor consistência e legibilidade
490
+
491
+ ---
492
+
493
+ ## [1.3.5] - 2026-07-27
494
+
495
+ ### Added
496
+ - Raw `select` support in method options (`options.select`): pass a raw Prisma `select` directly in a method call, without registering it beforehand in `selectModels` — mirrors the existing raw `include` (`options.include`)
497
+ - Full typing for `options.select`: works across all base methods (`get`, `getOrThrow`, `getList`, `remove`, `save`, `saveList`, `patch`, `patchList`, `merge`, `getAll`, `softRemove`, `restore`) and dynamics, narrows the return type to exactly the selected fields, and is mutually exclusive with `selectModel`, `includeModel` and `include`
498
+ - `select` field added to `DynamicMethodOptions` (class-based `DynamicRepository` API)
499
+ - Documentation for raw `select` in README.md, README-DynamicRepo.md and their Portuguese counterparts
500
+ - Runtime validation for `QueryMethod`'s `value` parameter — throws `VSRepoDecoratorError` if it isn't a string
501
+ - Reorganized the project's tests into a dedicated `test/` folder: `test/implementation` (Jest-based runtime tests, replacing the old root-level `teste.ts`/`teste-class.ts`) and `test/typing` (compile-time type tests checked via `tsc --noEmit`, using `@ts-expect-error` to assert invalid usages are rejected)
502
+ - New npm scripts: `test`, `test:implementation`, `test:implementation:watch`, `test:typing`
503
+ - Implementation and typing tests for raw `select`, covering both the functional (`setupVSRepo`) and class-based (`DynamicRepository`) APIs
504
+
505
+ ### Fixed
506
+ - Generated `VSRepoError.ts` now also exports `VSRepoDecoratorError` (previously missing from the generated output, causing consumers to be unable to import it)
507
+
508
+ ### Changed
509
+ - Updated the generated file tree diagram in the README to include the `DynamicRepository.ts`/`DynamicRepository.types.d.ts` files
510
+
511
+ ---
512
+
513
+ ## [1.3.5] - 2026-07-27 (Português)
514
+
515
+ ### Adicionado
516
+ - Suporte a `select` cru nas options dos métodos (`options.select`): permite passar um `select` bruto do Prisma diretamente na chamada, sem precisar registrá-lo antecipadamente em `selectModels` — espelha o `include` cru (`options.include`) já existente
517
+ - Tipagem completa para `options.select`: funciona em todos os métodos base (`get`, `getOrThrow`, `getList`, `remove`, `save`, `saveList`, `patch`, `patchList`, `merge`, `getAll`, `softRemove`, `restore`) e dinâmicos, restringe o tipo de retorno exatamente aos campos selecionados, e é mutuamente exclusivo com `selectModel`, `includeModel` e `include`
518
+ - Campo `select` adicionado ao `DynamicMethodOptions` (API baseada em classes `DynamicRepository`)
519
+ - Documentação do `select` cru no README.md, README-DynamicRepo.md e suas versões em português
520
+ - Validação em tempo de execução do parâmetro `value` do `QueryMethod` — lança `VSRepoDecoratorError` caso não seja uma string
521
+ - Reorganização dos testes do projeto em uma pasta `test/` dedicada: `test/implementation` (testes de runtime com Jest, substituindo os antigos `teste.ts`/`teste-class.ts` na raiz) e `test/typing` (testes de tipagem em tempo de compilação, checados com `tsc --noEmit`, usando `@ts-expect-error` para garantir que usos inválidos são rejeitados)
522
+ - Novos scripts npm: `test`, `test:implementation`, `test:implementation:watch`, `test:typing`
523
+ - Testes de implementação e de tipagem para o `select` cru, cobrindo tanto a API funcional (`setupVSRepo`) quanto a baseada em classes (`DynamicRepository`)
524
+
525
+ ### Corrigido
526
+ - O `VSRepoError.ts` gerado agora também exporta `VSRepoDecoratorError` (antes ausente na saída gerada, impedindo que consumidores conseguissem importá-lo)
527
+
528
+ ### Alterado
529
+ - Atualizado o diagrama da árvore de arquivos gerados no README para incluir os arquivos `DynamicRepository.ts`/`DynamicRepository.types.d.ts`
530
+
531
+ ---
532
+
533
+ ## [1.3.4] - 2026-07-25
534
+
535
+ ### Added
536
+ - Query Methods: new `@QueryMethod` decorator (class-based) and `query` config (functional) for defining raw SQL query methods that bypass the name-parsing engine
537
+ - Support for non-modifying queries (`$queryRawUnsafe`) and modifying queries (`$executeRawUnsafe`, `modifying: true`)
538
+ - `QueryMethodArg` type for typing the `{ args, db? }` parameter
539
+ - Transaction support for query methods via `db: tx` parameter
540
+ - Query methods documentation
541
+ - Query methods examples
542
+ - Tests for query methods in both functional and class-based approaches
543
+
544
+ ### Changed
545
+ - Clarified in documentation that the `WRelations` generic in `DynamicRepository` is optional and explained when to use it
546
+ - Translated documentation to Portuguese
547
+
548
+ ---
549
+
550
+ ## [1.3.4] - 2026-07-25 (Português)
551
+
552
+ ### Adicionado
553
+ - Query Methods: novo decorador `@QueryMethod` (abordagem class-based) e config `query` (abordagem funcional) para definir métodos de query SQL raw que ignoram o engine de parsing por nome
554
+ - Suporte para queries não-modificantes (`$queryRawUnsafe`) e modificantes (`$executeRawUnsafe`, `modifying: true`)
555
+ - Tipo `QueryMethodArg` para tipar o parâmetro `{ args, db? }`
556
+ - Suporte a transações para query methods via parâmetro `db: tx`
557
+ - Documentação dos query methods
558
+ - Exemplos dos query methods
559
+ - Testes para query methods nas abordagens funcional e class-based
560
+
561
+ ### Alterado
562
+ - Esclarecido na documentação que a generic `WRelations` no `DynamicRepository` é opcional e explicado quando utilizá-la
563
+ - Documentação traduzida para português
564
+
565
+ ---
566
+
567
+ ## [1.3.3] - 2026-07-22
568
+
569
+ ### Added
570
+ - DynamicRepository: base structure for dynamic repository functionality
571
+ - Complete typing for DynamicRepository and DynamicMethod
572
+ - Native Prisma `include` support in method options typing
573
+ - Real implementation for raw include support
574
+ - Improved build logging
575
+ - DynamicRepository documentation (README-DynamicRepo.md)
576
+ - DynamicRepository examples
577
+ - Tests for DynamicRepository and include parameter
578
+
579
+ ### Fixed
580
+ - Fixed typing for objects with relations
581
+ - Fixed DynamicRepository typing
582
+ - Fixed DynamicMethod typing
583
+ - Fixed pushWhere error in some dynamic methods
584
+
585
+ ### Changed
586
+ - Translated package.json description to English
587
+
588
+ ---
589
+
590
+ ## [1.3.3] - 2026-07-22 (Português)
591
+
592
+ ### Adicionado
593
+ - DynamicRepository: estrutura base da funcionalidade de repositório dinâmico
594
+ - Tipagem completa para DynamicRepository e DynamicMethod
595
+ - Suporte nativo ao `include` do Prisma na tipagem das opções de método
596
+ - Implementação real do suporte ao include raw
597
+ - Melhoria nos logs de build
598
+ - Documentação do DynamicRepository (README-DynamicRepo.md)
599
+ - Exemplos para DynamicRepository
600
+ - Testes para DynamicRepository e parâmetro include
601
+
602
+ ### Corrigido
603
+ - Correção da tipagem dos objetos com relations
604
+ - Correção da tipagem do DynamicRepository
605
+ - Correção da tipagem do DynamicMethod
606
+ - Correção do erro do pushWhere em alguns métodos dinâmicos
607
+
608
+ ### Alterado
609
+ - Descrição do package.json traduzida para inglês
610
+
611
+ ---