@attrx/role-morphic 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +301 -0
- package/dist/index.d.mts +1190 -0
- package/dist/index.d.ts +1190 -0
- package/dist/index.js +4680 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +4648 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +67 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,1190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RoleMorphic Types
|
|
3
|
+
*
|
|
4
|
+
* Sistema de tipos para conversão polimórfica de valores.
|
|
5
|
+
* Um valor pode assumir múltiplas formas (variantes) mantendo sua identidade semântica.
|
|
6
|
+
*
|
|
7
|
+
* Os 4 Pilares:
|
|
8
|
+
* - Cast: Normaliza input sujo para o tipo esperado
|
|
9
|
+
* - Validate: Verifica regras semânticas do valor
|
|
10
|
+
* - Convert: Transforma entre variantes (via base)
|
|
11
|
+
* - Format: Apresenta o valor como string legível
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Função que converte um valor para o formato base da role
|
|
15
|
+
*/
|
|
16
|
+
type ToBaseFn<TValue = unknown, TBase = unknown> = (value: TValue) => TBase;
|
|
17
|
+
/**
|
|
18
|
+
* Função que converte do formato base para uma variante específica
|
|
19
|
+
*/
|
|
20
|
+
type FromBaseFn<TBase = unknown, TValue = unknown> = (base: TBase) => TValue;
|
|
21
|
+
/**
|
|
22
|
+
* Função que tenta normalizar um input desconhecido para o tipo esperado
|
|
23
|
+
* Retorna null se não conseguir fazer o cast
|
|
24
|
+
*/
|
|
25
|
+
type CastFn<TValue = unknown> = (input: unknown) => TValue | null;
|
|
26
|
+
/**
|
|
27
|
+
* Resultado de uma operação de cast
|
|
28
|
+
*/
|
|
29
|
+
type CastResult<T> = {
|
|
30
|
+
ok: true;
|
|
31
|
+
value: T;
|
|
32
|
+
} | {
|
|
33
|
+
ok: false;
|
|
34
|
+
error: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Regras de validação para uma variante
|
|
38
|
+
*/
|
|
39
|
+
type ValidationRule = {
|
|
40
|
+
/** Valor mínimo permitido (para números) */
|
|
41
|
+
min?: number;
|
|
42
|
+
/** Valor máximo permitido (para números) */
|
|
43
|
+
max?: number;
|
|
44
|
+
/** Deve ser inteiro (para números) */
|
|
45
|
+
integer?: boolean;
|
|
46
|
+
/** Pattern regex (para strings) */
|
|
47
|
+
pattern?: RegExp;
|
|
48
|
+
/** Função de validação customizada - retorna mensagem de erro ou null se válido */
|
|
49
|
+
custom?: (value: unknown) => string | null;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Resultado de uma validação
|
|
53
|
+
*/
|
|
54
|
+
type ValidationResult = {
|
|
55
|
+
valid: boolean;
|
|
56
|
+
errors: string[];
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Opções base de formatação (compartilhadas por todas as roles)
|
|
60
|
+
*/
|
|
61
|
+
type BaseFormatOptions = {
|
|
62
|
+
/** Número de casas decimais */
|
|
63
|
+
decimals?: number;
|
|
64
|
+
/** Locale para formatação (ex: 'pt-BR', 'en-US') */
|
|
65
|
+
locale?: string;
|
|
66
|
+
/** Tipo de notação */
|
|
67
|
+
notation?: "standard" | "scientific" | "compact";
|
|
68
|
+
/** Usar nome completo ao invés de símbolo */
|
|
69
|
+
verbose?: boolean;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Opções de formatação genéricas
|
|
73
|
+
* @deprecated Use BaseFormatOptions ou tipos específicos (ColorFormatOptions, DateFormatOptions)
|
|
74
|
+
*/
|
|
75
|
+
type FormatOptions = BaseFormatOptions;
|
|
76
|
+
/**
|
|
77
|
+
* Função de formatação customizada
|
|
78
|
+
*/
|
|
79
|
+
type FormatFn<TValue = unknown> = (value: TValue, options?: BaseFormatOptions) => string;
|
|
80
|
+
/**
|
|
81
|
+
* Especificação de formatação para uma variante
|
|
82
|
+
*/
|
|
83
|
+
type FormatSpec<TValue = unknown> = {
|
|
84
|
+
/** Símbolo da unidade (ex: "m²", "ha", "°C") */
|
|
85
|
+
symbol: string;
|
|
86
|
+
/** Nome singular (ex: "meter", "hectare") */
|
|
87
|
+
singular?: string;
|
|
88
|
+
/** Nome plural (ex: "meters", "hectares") */
|
|
89
|
+
plural?: string;
|
|
90
|
+
/** Formatador customizado (override do padrão) */
|
|
91
|
+
formatter?: FormatFn<TValue>;
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Definição de uma variante dentro de uma role
|
|
95
|
+
*
|
|
96
|
+
* Cada variante implementa os 4 pilares:
|
|
97
|
+
* - Convert: toBase/fromBase (obrigatório)
|
|
98
|
+
* - Cast: cast (opcional, usa default por type)
|
|
99
|
+
* - Validate: validate (opcional)
|
|
100
|
+
* - Format: format (opcional)
|
|
101
|
+
*/
|
|
102
|
+
type VariantSpec<TValue = unknown, TBase = unknown> = {
|
|
103
|
+
/** Tipo primitivo do valor nesta variante */
|
|
104
|
+
type: "string" | "number" | "boolean" | "object" | "array";
|
|
105
|
+
/** Converte o valor desta variante para o formato base */
|
|
106
|
+
toBase: ToBaseFn<TValue, TBase>;
|
|
107
|
+
/** Converte do formato base para esta variante */
|
|
108
|
+
fromBase: FromBaseFn<TBase, TValue>;
|
|
109
|
+
/** Tenta normalizar um input desconhecido para o tipo esperado */
|
|
110
|
+
cast?: CastFn<TValue>;
|
|
111
|
+
/** Regras de validação semântica */
|
|
112
|
+
validate?: ValidationRule;
|
|
113
|
+
/** Especificação de formatação */
|
|
114
|
+
format?: FormatSpec<TValue>;
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
* Definição completa de uma Role
|
|
118
|
+
*
|
|
119
|
+
* Uma Role representa um conceito semântico (cor, área, data) que pode
|
|
120
|
+
* ser expresso em múltiplas variantes (hex, rgb, hsl para cor).
|
|
121
|
+
*/
|
|
122
|
+
type RoleSpec<TBase = unknown> = {
|
|
123
|
+
/** Nome da variante que serve como pivot para todas as conversões */
|
|
124
|
+
base: string;
|
|
125
|
+
/** Mapa de variantes disponíveis para esta role */
|
|
126
|
+
variants: Record<string, VariantSpec<unknown, TBase>>;
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Identificador de variante parseado
|
|
130
|
+
*
|
|
131
|
+
* "color:rgb:object" => { role: "color", variant: "rgb:object" }
|
|
132
|
+
*/
|
|
133
|
+
type ParsedVariantId = {
|
|
134
|
+
role: string;
|
|
135
|
+
variant: string;
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Resultado de uma conversão que pode falhar
|
|
139
|
+
*/
|
|
140
|
+
type ConversionResult<T> = {
|
|
141
|
+
ok: true;
|
|
142
|
+
value: T;
|
|
143
|
+
} | {
|
|
144
|
+
ok: false;
|
|
145
|
+
error: string;
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Resultado de validação de reversibilidade
|
|
149
|
+
*/
|
|
150
|
+
type ReversibilityResult = {
|
|
151
|
+
reversible: boolean;
|
|
152
|
+
original: unknown;
|
|
153
|
+
converted: unknown;
|
|
154
|
+
reconverted: unknown;
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* Função que transforma um valor de uma role para outra
|
|
158
|
+
*/
|
|
159
|
+
type MorpherFn<TFrom = unknown, TTo = unknown> = (value: TFrom) => TTo;
|
|
160
|
+
/**
|
|
161
|
+
* Chave de um morpher: "fromRole:fromVariant->toRole:toVariant"
|
|
162
|
+
*/
|
|
163
|
+
type MorpherKey = `${string}->${string}`;
|
|
164
|
+
/**
|
|
165
|
+
* Definição de um morpher
|
|
166
|
+
*/
|
|
167
|
+
type MorpherSpec<TFrom = unknown, TTo = unknown> = {
|
|
168
|
+
from: string;
|
|
169
|
+
to: string;
|
|
170
|
+
transform: MorpherFn<TFrom, TTo>;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* RoleMorphic
|
|
175
|
+
*
|
|
176
|
+
* Motor de conversão polimórfica de valores.
|
|
177
|
+
* Permite que um valor assuma múltiplas formas (variantes) mantendo sua identidade semântica.
|
|
178
|
+
*
|
|
179
|
+
* Arquitetura Hub-and-Spoke:
|
|
180
|
+
* - Cada role tem uma variante BASE que serve como pivot
|
|
181
|
+
* - Toda conversão passa pela base: origem -> base -> destino
|
|
182
|
+
* - Isso reduz a complexidade de N² para 2N conversões
|
|
183
|
+
*/
|
|
184
|
+
|
|
185
|
+
declare class RoleMorphic {
|
|
186
|
+
/** Registry de roles */
|
|
187
|
+
private roles;
|
|
188
|
+
/** Registry de morphers (transformações cross-role) */
|
|
189
|
+
private morphers;
|
|
190
|
+
/**
|
|
191
|
+
* Registra uma nova role
|
|
192
|
+
*/
|
|
193
|
+
register<TBase = unknown>(roleId: string, spec: RoleSpec<TBase>): this;
|
|
194
|
+
/**
|
|
195
|
+
* Remove uma role registrada
|
|
196
|
+
*/
|
|
197
|
+
unregister(roleId: string): boolean;
|
|
198
|
+
/**
|
|
199
|
+
* Verifica se uma role está registrada
|
|
200
|
+
*/
|
|
201
|
+
hasRole(roleId: string): boolean;
|
|
202
|
+
/**
|
|
203
|
+
* Obtém a spec de uma role
|
|
204
|
+
*/
|
|
205
|
+
getRole(roleId: string): RoleSpec | undefined;
|
|
206
|
+
/**
|
|
207
|
+
* Lista todas as roles registradas
|
|
208
|
+
*/
|
|
209
|
+
listRoles(): string[];
|
|
210
|
+
/**
|
|
211
|
+
* Parseia um identificador de variante
|
|
212
|
+
*
|
|
213
|
+
* "color:rgb:object" => { role: "color", variant: "rgb:object" }
|
|
214
|
+
* "area:m2" => { role: "area", variant: "m2" }
|
|
215
|
+
*/
|
|
216
|
+
parseVariantId(fullId: string): ParsedVariantId;
|
|
217
|
+
/**
|
|
218
|
+
* Verifica se uma variante existe
|
|
219
|
+
*/
|
|
220
|
+
hasVariant(fullId: string): boolean;
|
|
221
|
+
/**
|
|
222
|
+
* Obtém a spec de uma variante
|
|
223
|
+
*/
|
|
224
|
+
getVariant(fullId: string): VariantSpec | undefined;
|
|
225
|
+
/**
|
|
226
|
+
* Lista todas as variantes de uma role
|
|
227
|
+
*/
|
|
228
|
+
listVariants(roleId: string): string[];
|
|
229
|
+
/**
|
|
230
|
+
* Lista variantes para as quais uma variante pode converter
|
|
231
|
+
*/
|
|
232
|
+
getConvertibleVariants(fullId: string): string[];
|
|
233
|
+
/**
|
|
234
|
+
* Converte um valor de uma variante para outra (mesma role)
|
|
235
|
+
*
|
|
236
|
+
* @param from - Identificador da variante de origem (ex: "color:hex")
|
|
237
|
+
* @param to - Identificador da variante de destino (ex: "color:rgb:object")
|
|
238
|
+
* @param value - Valor a converter
|
|
239
|
+
* @returns Valor convertido
|
|
240
|
+
* @throws Error se a conversão não for possível
|
|
241
|
+
*/
|
|
242
|
+
convert<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): TTo;
|
|
243
|
+
/**
|
|
244
|
+
* Tenta converter, retornando Result ao invés de throw
|
|
245
|
+
*/
|
|
246
|
+
tryConvert<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): ConversionResult<TTo>;
|
|
247
|
+
/**
|
|
248
|
+
* Verifica se uma conversão é reversível (sem perda de dados)
|
|
249
|
+
*/
|
|
250
|
+
isReversible<T = unknown>(from: string, to: string, value: T): boolean;
|
|
251
|
+
/**
|
|
252
|
+
* Retorna detalhes sobre a reversibilidade de uma conversão
|
|
253
|
+
*/
|
|
254
|
+
checkReversibility<T = unknown>(from: string, to: string, value: T): ReversibilityResult;
|
|
255
|
+
/**
|
|
256
|
+
* Converte apenas se a conversão for reversível
|
|
257
|
+
*
|
|
258
|
+
* @throws Error se a conversão causar perda de dados
|
|
259
|
+
*/
|
|
260
|
+
convertSafe<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): TTo;
|
|
261
|
+
/**
|
|
262
|
+
* Registra um morpher para transformação entre roles diferentes
|
|
263
|
+
*/
|
|
264
|
+
registerMorpher<TFrom = unknown, TTo = unknown>(spec: MorpherSpec<TFrom, TTo>): this;
|
|
265
|
+
/**
|
|
266
|
+
* Remove um morpher
|
|
267
|
+
*/
|
|
268
|
+
unregisterMorpher(from: string, to: string): boolean;
|
|
269
|
+
/**
|
|
270
|
+
* Verifica se existe um morpher para a transformação
|
|
271
|
+
*/
|
|
272
|
+
hasMorpher(from: string, to: string): boolean;
|
|
273
|
+
/**
|
|
274
|
+
* Lista morphers disponíveis a partir de uma variante
|
|
275
|
+
*/
|
|
276
|
+
getMorphersFrom(from: string): string[];
|
|
277
|
+
/**
|
|
278
|
+
* Transforma um valor de uma role para outra usando um morpher registrado
|
|
279
|
+
*/
|
|
280
|
+
morph<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): TTo;
|
|
281
|
+
/**
|
|
282
|
+
* Tenta transformar, retornando Result ao invés de throw
|
|
283
|
+
*/
|
|
284
|
+
tryMorph<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): ConversionResult<TTo>;
|
|
285
|
+
/**
|
|
286
|
+
* Converte ou transforma automaticamente
|
|
287
|
+
*
|
|
288
|
+
* - Se mesma role: usa convert()
|
|
289
|
+
* - Se roles diferentes: usa morph()
|
|
290
|
+
*/
|
|
291
|
+
auto<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): TTo;
|
|
292
|
+
/**
|
|
293
|
+
* Converte um valor para a variante base da sua role
|
|
294
|
+
*/
|
|
295
|
+
toBase<T = unknown, TBase = unknown>(fullId: string, value: T): TBase;
|
|
296
|
+
/**
|
|
297
|
+
* Converte um valor da base para uma variante específica
|
|
298
|
+
*/
|
|
299
|
+
fromBase<TBase = unknown, T = unknown>(fullId: string, baseValue: TBase): T;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* IRole - Interface principal que todas as Roles devem implementar
|
|
304
|
+
*
|
|
305
|
+
* Define o contrato dos 4 pilares: Convert, Cast, Validate, Format
|
|
306
|
+
*
|
|
307
|
+
* @example
|
|
308
|
+
* class AreaRole implements IRole { ... }
|
|
309
|
+
* class ColorRole implements IRole { ... }
|
|
310
|
+
*/
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Resultado de operação que pode falhar
|
|
314
|
+
*/
|
|
315
|
+
type Result<T> = {
|
|
316
|
+
ok: true;
|
|
317
|
+
value: T;
|
|
318
|
+
} | {
|
|
319
|
+
ok: false;
|
|
320
|
+
error: string;
|
|
321
|
+
};
|
|
322
|
+
/**
|
|
323
|
+
* Interface que TODA Role deve implementar.
|
|
324
|
+
*
|
|
325
|
+
* Uma Role representa um conceito semântico (área, cor, data) que pode
|
|
326
|
+
* ser expresso em múltiplas variantes (m², hectare, acre).
|
|
327
|
+
*
|
|
328
|
+
* Os 4 pilares:
|
|
329
|
+
* - **Convert**: Transforma entre variantes (via base)
|
|
330
|
+
* - **Cast**: Normaliza input sujo para o tipo esperado
|
|
331
|
+
* - **Validate**: Verifica regras semânticas
|
|
332
|
+
* - **Format**: Apresenta como string legível
|
|
333
|
+
*/
|
|
334
|
+
interface IRole<TBase = unknown> {
|
|
335
|
+
/** Nome único da role (ex: "area", "color", "temperature") */
|
|
336
|
+
readonly name: string;
|
|
337
|
+
/** Nome da variante base/pivot (ex: "square_meter", "rgb_object") */
|
|
338
|
+
readonly base: string;
|
|
339
|
+
/** Retorna lista de todas as variantes disponíveis */
|
|
340
|
+
getVariants(): string[];
|
|
341
|
+
/** Verifica se uma variante existe */
|
|
342
|
+
hasVariant(variant: string): boolean;
|
|
343
|
+
/**
|
|
344
|
+
* Converte valor entre variantes da mesma role.
|
|
345
|
+
* Usa arquitetura hub-and-spoke: from → base → to
|
|
346
|
+
*
|
|
347
|
+
* @throws Error se variante não existir
|
|
348
|
+
*
|
|
349
|
+
* @example
|
|
350
|
+
* areaRole.convert('hectare', 'acre', 1) // 2.47105
|
|
351
|
+
*/
|
|
352
|
+
convert<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): TTo;
|
|
353
|
+
/**
|
|
354
|
+
* Versão safe do convert que retorna Result ao invés de throw
|
|
355
|
+
*
|
|
356
|
+
* @example
|
|
357
|
+
* const result = areaRole.tryConvert('hectare', 'acre', 1);
|
|
358
|
+
* if (result.ok) console.log(result.value);
|
|
359
|
+
*/
|
|
360
|
+
tryConvert<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): Result<TTo>;
|
|
361
|
+
/**
|
|
362
|
+
* Converte qualquer variante para a base
|
|
363
|
+
*
|
|
364
|
+
* @example
|
|
365
|
+
* areaRole.toBase('hectare', 1) // 10000 (m²)
|
|
366
|
+
*/
|
|
367
|
+
toBase<T = unknown>(variant: string, value: T): TBase;
|
|
368
|
+
/**
|
|
369
|
+
* Converte da base para qualquer variante
|
|
370
|
+
*
|
|
371
|
+
* @example
|
|
372
|
+
* areaRole.fromBase('hectare', 10000) // 1
|
|
373
|
+
*/
|
|
374
|
+
fromBase<T = unknown>(variant: string, baseValue: TBase): T;
|
|
375
|
+
/**
|
|
376
|
+
* Tenta normalizar um input desconhecido para o tipo esperado pela variante.
|
|
377
|
+
* Retorna null se não conseguir fazer o cast.
|
|
378
|
+
*
|
|
379
|
+
* @example
|
|
380
|
+
* areaRole.cast('hectare', "100 ha") // 100
|
|
381
|
+
* areaRole.cast('hectare', "100") // 100
|
|
382
|
+
* areaRole.cast('hectare', 100) // 100
|
|
383
|
+
* areaRole.cast('hectare', "invalid") // null
|
|
384
|
+
*/
|
|
385
|
+
cast<T = unknown>(variant: string, input: unknown): T | null;
|
|
386
|
+
/**
|
|
387
|
+
* Versão safe do cast que retorna Result
|
|
388
|
+
*
|
|
389
|
+
* @example
|
|
390
|
+
* const result = areaRole.tryCast('hectare', "100 ha");
|
|
391
|
+
* if (result.ok) console.log(result.value);
|
|
392
|
+
*/
|
|
393
|
+
tryCast<T = unknown>(variant: string, input: unknown): Result<T>;
|
|
394
|
+
/**
|
|
395
|
+
* Valida se um valor atende às regras semânticas da variante.
|
|
396
|
+
* Retorna objeto com valid: boolean e errors: string[]
|
|
397
|
+
*
|
|
398
|
+
* @example
|
|
399
|
+
* areaRole.validate('hectare', 100) // { valid: true, errors: [] }
|
|
400
|
+
* areaRole.validate('hectare', -5) // { valid: false, errors: ['Area cannot be negative'] }
|
|
401
|
+
*/
|
|
402
|
+
validate(variant: string, value: unknown): ValidationResult;
|
|
403
|
+
/**
|
|
404
|
+
* Versão simplificada que retorna apenas boolean
|
|
405
|
+
*
|
|
406
|
+
* @example
|
|
407
|
+
* areaRole.isValid('hectare', 100) // true
|
|
408
|
+
* areaRole.isValid('hectare', -5) // false
|
|
409
|
+
*/
|
|
410
|
+
isValid(variant: string, value: unknown): boolean;
|
|
411
|
+
/**
|
|
412
|
+
* Formata valor para apresentação humana.
|
|
413
|
+
*
|
|
414
|
+
* @example
|
|
415
|
+
* areaRole.format('hectare', 2.5) // "2.5 ha"
|
|
416
|
+
* areaRole.format('hectare', 2.5, { verbose: true }) // "2.5 hectares"
|
|
417
|
+
* areaRole.format('hectare', 1000, { locale: 'pt-BR' }) // "1.000 ha"
|
|
418
|
+
*/
|
|
419
|
+
format(variant: string, value: unknown, options?: BaseFormatOptions): string;
|
|
420
|
+
/**
|
|
421
|
+
* Gera RoleSpec para registro no RoleMorphic (backward compatible).
|
|
422
|
+
* Permite usar a nova arquitetura de classes com a API existente.
|
|
423
|
+
*
|
|
424
|
+
* @example
|
|
425
|
+
* const morph = new RoleMorphic();
|
|
426
|
+
* morph.register('area', areaRole.toSpec());
|
|
427
|
+
*/
|
|
428
|
+
toSpec(): RoleSpec<TBase>;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* IVariant - Interface para variantes de ComplexRole
|
|
433
|
+
*
|
|
434
|
+
* Cada variante complexa (hex, rgb:object, hsl:string) implementa esta interface.
|
|
435
|
+
* Usada quando variantes têm tipos/estruturas diferentes.
|
|
436
|
+
*
|
|
437
|
+
* @example
|
|
438
|
+
* class HexVariant implements IVariant<string, RGBA> { ... }
|
|
439
|
+
* class RgbObjectVariant implements IVariant<RGBA, RGBA> { ... }
|
|
440
|
+
*/
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Interface para uma variante de ComplexRole.
|
|
444
|
+
*
|
|
445
|
+
* @typeParam TValue - Tipo do valor nesta variante (ex: string para hex, RGBA para rgb:object)
|
|
446
|
+
* @typeParam TBase - Tipo da base da role (ex: RGBA para color)
|
|
447
|
+
*
|
|
448
|
+
* @example
|
|
449
|
+
* // Variante hex de Color
|
|
450
|
+
* class HexVariant implements IVariant<string, RGBA> {
|
|
451
|
+
* name = 'hex';
|
|
452
|
+
* type = 'string';
|
|
453
|
+
*
|
|
454
|
+
* toBase(hex: string): RGBA { ... }
|
|
455
|
+
* fromBase(rgba: RGBA): string { ... }
|
|
456
|
+
* cast(input: unknown): string | null { ... }
|
|
457
|
+
* validate(hex: string): ValidationResult { ... }
|
|
458
|
+
* format(hex: string, opts?): string { ... }
|
|
459
|
+
* }
|
|
460
|
+
*/
|
|
461
|
+
interface IVariant<TValue = unknown, TBase = unknown> {
|
|
462
|
+
/** Nome da variante (ex: "hex", "rgb:object", "hsl:string") */
|
|
463
|
+
readonly name: string;
|
|
464
|
+
/** Tipo primitivo do valor (ex: "string", "object") */
|
|
465
|
+
readonly type: "string" | "number" | "boolean" | "object" | "array";
|
|
466
|
+
/**
|
|
467
|
+
* Converte valor desta variante para o formato base da role.
|
|
468
|
+
*
|
|
469
|
+
* @example
|
|
470
|
+
* hexVariant.toBase('#ff0000') // { r: 255, g: 0, b: 0, a: 1 }
|
|
471
|
+
*/
|
|
472
|
+
toBase(value: TValue): TBase;
|
|
473
|
+
/**
|
|
474
|
+
* Converte do formato base para esta variante.
|
|
475
|
+
*
|
|
476
|
+
* @example
|
|
477
|
+
* hexVariant.fromBase({ r: 255, g: 0, b: 0, a: 1 }) // '#ff0000ff'
|
|
478
|
+
*/
|
|
479
|
+
fromBase(base: TBase): TValue;
|
|
480
|
+
/**
|
|
481
|
+
* Tenta normalizar um input desconhecido para o tipo desta variante.
|
|
482
|
+
* Retorna null se não conseguir.
|
|
483
|
+
*
|
|
484
|
+
* @example
|
|
485
|
+
* hexVariant.cast('ff0000') // '#ff0000'
|
|
486
|
+
* hexVariant.cast('red') // '#ff0000'
|
|
487
|
+
* hexVariant.cast('rgb(255,0,0)') // '#ff0000'
|
|
488
|
+
* hexVariant.cast(123) // null
|
|
489
|
+
*/
|
|
490
|
+
cast(input: unknown): TValue | null;
|
|
491
|
+
/**
|
|
492
|
+
* Versão safe que retorna Result
|
|
493
|
+
*/
|
|
494
|
+
tryCast(input: unknown): Result<TValue>;
|
|
495
|
+
/**
|
|
496
|
+
* Valida se um valor atende às regras desta variante.
|
|
497
|
+
*
|
|
498
|
+
* @example
|
|
499
|
+
* hexVariant.validate('#ff0000') // { valid: true, errors: [] }
|
|
500
|
+
* hexVariant.validate('#gg0000') // { valid: false, errors: ['Invalid hex character'] }
|
|
501
|
+
*/
|
|
502
|
+
validate(value: TValue): ValidationResult;
|
|
503
|
+
/**
|
|
504
|
+
* Versão simplificada que retorna boolean
|
|
505
|
+
*/
|
|
506
|
+
isValid(value: TValue): boolean;
|
|
507
|
+
/**
|
|
508
|
+
* Formata valor para apresentação humana.
|
|
509
|
+
*
|
|
510
|
+
* @example
|
|
511
|
+
* hexVariant.format('#ff0000') // '#ff0000'
|
|
512
|
+
* hexVariant.format('#ff0000', { uppercase: true }) // '#FF0000'
|
|
513
|
+
*/
|
|
514
|
+
format(value: TValue, options?: BaseFormatOptions): string;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* SimpleRole - Classe base abstrata para roles numéricas
|
|
519
|
+
*
|
|
520
|
+
* Para roles onde TODAS as variantes são do mesmo tipo (geralmente number).
|
|
521
|
+
* Implementa os 4 pilares com lógica compartilhada via fatores de conversão.
|
|
522
|
+
*
|
|
523
|
+
* Roles que estendem: Area, Length, Mass, Volume, Speed, Pressure, Energy, etc.
|
|
524
|
+
*
|
|
525
|
+
* @example
|
|
526
|
+
* class AreaRole extends SimpleRole<number> {
|
|
527
|
+
* readonly name = 'area';
|
|
528
|
+
* readonly base = 'square_meter';
|
|
529
|
+
* readonly factors = { square_meter: 1, hectare: 10000, acre: 4046.86 };
|
|
530
|
+
* readonly symbols = { square_meter: 'm²', hectare: 'ha', acre: 'ac' };
|
|
531
|
+
* }
|
|
532
|
+
*/
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Configuração de uma unidade em SimpleRole
|
|
536
|
+
*/
|
|
537
|
+
interface SimpleUnitConfig {
|
|
538
|
+
/** Fator de conversão para a base (ou função para temperatura) */
|
|
539
|
+
factor?: number;
|
|
540
|
+
/** Fórmula de conversão para base (para temperatura) */
|
|
541
|
+
toBase?: (value: number) => number;
|
|
542
|
+
/** Fórmula de conversão da base (para temperatura) */
|
|
543
|
+
fromBase?: (value: number) => number;
|
|
544
|
+
/** Símbolo da unidade (ex: "m²", "ha") */
|
|
545
|
+
symbol: string;
|
|
546
|
+
/** Nome singular (ex: "hectare") */
|
|
547
|
+
singular?: string;
|
|
548
|
+
/** Nome plural (ex: "hectares") */
|
|
549
|
+
plural?: string;
|
|
550
|
+
/** Se true, não adiciona espaço antes do símbolo (ex: 45° ao invés de 45 °) */
|
|
551
|
+
noSpace?: boolean;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Configuração de validação para SimpleRole
|
|
555
|
+
*/
|
|
556
|
+
interface SimpleValidationConfig {
|
|
557
|
+
/** Valor mínimo permitido */
|
|
558
|
+
min?: number;
|
|
559
|
+
/** Valor máximo permitido */
|
|
560
|
+
max?: number;
|
|
561
|
+
/** Deve ser inteiro */
|
|
562
|
+
integer?: boolean;
|
|
563
|
+
/** Mensagem de erro customizada para min */
|
|
564
|
+
minError?: string;
|
|
565
|
+
/** Mensagem de erro customizada para max */
|
|
566
|
+
maxError?: string;
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Alias para reconhecimento no cast
|
|
570
|
+
*/
|
|
571
|
+
type UnitAliases = Record<string, string>;
|
|
572
|
+
/**
|
|
573
|
+
* Classe base abstrata para roles numéricas simples.
|
|
574
|
+
*
|
|
575
|
+
* Subclasses devem definir:
|
|
576
|
+
* - name: Nome da role
|
|
577
|
+
* - base: Variante base
|
|
578
|
+
* - units: Configuração de cada unidade
|
|
579
|
+
* - aliases: (opcional) Aliases para cast
|
|
580
|
+
* - validation: (opcional) Regras de validação
|
|
581
|
+
*/
|
|
582
|
+
declare abstract class SimpleRole implements IRole<number> {
|
|
583
|
+
/** Nome único da role */
|
|
584
|
+
abstract readonly name: string;
|
|
585
|
+
/** Nome da variante base */
|
|
586
|
+
abstract readonly base: string;
|
|
587
|
+
/** Configuração de cada unidade */
|
|
588
|
+
abstract readonly units: Record<string, SimpleUnitConfig>;
|
|
589
|
+
/** Aliases para reconhecimento no cast (ex: "ha" → "hectare") */
|
|
590
|
+
readonly aliases: UnitAliases;
|
|
591
|
+
/** Regras de validação */
|
|
592
|
+
readonly validation: SimpleValidationConfig;
|
|
593
|
+
getVariants(): string[];
|
|
594
|
+
hasVariant(variant: string): boolean;
|
|
595
|
+
convert<TFrom = number, TTo = number>(from: string, to: string, value: TFrom): TTo;
|
|
596
|
+
tryConvert<TFrom = number, TTo = number>(from: string, to: string, value: TFrom): Result<TTo>;
|
|
597
|
+
toBase<T = number>(variant: string, value: T): number;
|
|
598
|
+
fromBase<T = number>(variant: string, baseValue: number): T;
|
|
599
|
+
cast<T = number>(variant: string, input: unknown): T | null;
|
|
600
|
+
tryCast<T = number>(variant: string, input: unknown): Result<T>;
|
|
601
|
+
/**
|
|
602
|
+
* Parseia string para número, detectando unidade se presente.
|
|
603
|
+
* Subclasses podem sobrescrever para lógica customizada.
|
|
604
|
+
*/
|
|
605
|
+
protected parseString(input: string, targetVariant: string): number | null;
|
|
606
|
+
/**
|
|
607
|
+
* Parseia string numérica considerando formatos brasileiro e americano
|
|
608
|
+
*/
|
|
609
|
+
protected parseNumber(numStr: string): number | null;
|
|
610
|
+
/**
|
|
611
|
+
* Detecta unidade a partir de string (símbolo ou alias)
|
|
612
|
+
*/
|
|
613
|
+
protected detectUnit(unitStr: string): string | null;
|
|
614
|
+
validate(variant: string, value: unknown): ValidationResult;
|
|
615
|
+
isValid(variant: string, value: unknown): boolean;
|
|
616
|
+
format(variant: string, value: unknown, options?: BaseFormatOptions): string;
|
|
617
|
+
toSpec(): RoleSpec<number>;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* ComplexRole - Classe base abstrata para roles com variantes heterogêneas
|
|
622
|
+
*
|
|
623
|
+
* Para roles onde cada variante tem tipo/estrutura diferente.
|
|
624
|
+
* Cada variante é implementada como sua própria classe (IVariant).
|
|
625
|
+
*
|
|
626
|
+
* Roles que estendem: Color, Date, etc.
|
|
627
|
+
*
|
|
628
|
+
* @example
|
|
629
|
+
* class ColorRole extends ComplexRole<RGBA> {
|
|
630
|
+
* readonly name = 'color';
|
|
631
|
+
* readonly base = 'rgb_object';
|
|
632
|
+
*
|
|
633
|
+
* protected createVariants() {
|
|
634
|
+
* return {
|
|
635
|
+
* 'hex': new HexVariant(),
|
|
636
|
+
* 'rgb_object': new RgbObjectVariant(),
|
|
637
|
+
* 'rgb_string': new RgbStringVariant(),
|
|
638
|
+
* 'hsl_object': new HslObjectVariant(),
|
|
639
|
+
* };
|
|
640
|
+
* }
|
|
641
|
+
* }
|
|
642
|
+
*/
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* Classe base abstrata para roles com variantes heterogêneas.
|
|
646
|
+
*
|
|
647
|
+
* Subclasses devem definir:
|
|
648
|
+
* - name: Nome da role
|
|
649
|
+
* - base: Variante base
|
|
650
|
+
* - createVariants(): Factory que retorna mapa de variantes
|
|
651
|
+
*
|
|
652
|
+
* @typeParam TBase - Tipo do valor na variante base
|
|
653
|
+
*/
|
|
654
|
+
declare abstract class ComplexRole<TBase = unknown> implements IRole<TBase> {
|
|
655
|
+
/** Nome único da role */
|
|
656
|
+
abstract readonly name: string;
|
|
657
|
+
/** Nome da variante base */
|
|
658
|
+
abstract readonly base: string;
|
|
659
|
+
/** Cache das variantes */
|
|
660
|
+
private _variants;
|
|
661
|
+
/**
|
|
662
|
+
* Factory method para criar variantes.
|
|
663
|
+
* Subclasses devem implementar.
|
|
664
|
+
*/
|
|
665
|
+
protected abstract createVariants(): Record<string, IVariant<unknown, TBase>>;
|
|
666
|
+
/**
|
|
667
|
+
* Retorna mapa de variantes (lazy initialization)
|
|
668
|
+
*/
|
|
669
|
+
protected get variants(): Map<string, IVariant<unknown, TBase>>;
|
|
670
|
+
/**
|
|
671
|
+
* Retorna uma variante específica
|
|
672
|
+
*/
|
|
673
|
+
protected getVariant(name: string): IVariant<unknown, TBase>;
|
|
674
|
+
getVariants(): string[];
|
|
675
|
+
hasVariant(variant: string): boolean;
|
|
676
|
+
convert<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): TTo;
|
|
677
|
+
tryConvert<TFrom = unknown, TTo = unknown>(from: string, to: string, value: TFrom): Result<TTo>;
|
|
678
|
+
toBase<T = unknown>(variant: string, value: T): TBase;
|
|
679
|
+
fromBase<T = unknown>(variant: string, baseValue: TBase): T;
|
|
680
|
+
cast<T = unknown>(variant: string, input: unknown): T | null;
|
|
681
|
+
tryCast<T = unknown>(variant: string, input: unknown): Result<T>;
|
|
682
|
+
validate(variant: string, value: unknown): ValidationResult;
|
|
683
|
+
isValid(variant: string, value: unknown): boolean;
|
|
684
|
+
format(variant: string, value: unknown, options?: BaseFormatOptions): string;
|
|
685
|
+
toSpec(): RoleSpec<TBase>;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* Area Role - Constants
|
|
690
|
+
*
|
|
691
|
+
* Fatores de conversão, símbolos e aliases para unidades de área.
|
|
692
|
+
*
|
|
693
|
+
* Fontes:
|
|
694
|
+
* - NIST SP 811 (2008)
|
|
695
|
+
* - International Yard and Pound Agreement (1959)
|
|
696
|
+
* - SI Brochure, 9th Edition (2019)
|
|
697
|
+
*/
|
|
698
|
+
|
|
699
|
+
type AreaUnit = "square_kilometer" | "hectare" | "are" | "square_meter" | "square_decimeter" | "square_centimeter" | "square_millimeter" | "square_mile" | "acre" | "square_yard" | "square_foot" | "square_inch";
|
|
700
|
+
|
|
701
|
+
declare class AreaRole extends SimpleRole {
|
|
702
|
+
readonly name = "area";
|
|
703
|
+
readonly base = "square_meter";
|
|
704
|
+
readonly units: Record<AreaUnit, SimpleUnitConfig>;
|
|
705
|
+
readonly aliases: UnitAliases;
|
|
706
|
+
readonly validation: SimpleValidationConfig;
|
|
707
|
+
}
|
|
708
|
+
/** Instância singleton da AreaRole */
|
|
709
|
+
declare const areaRole: AreaRole;
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* Length Role - Constants
|
|
713
|
+
*
|
|
714
|
+
* Fatores de conversão, símbolos e aliases para unidades de comprimento.
|
|
715
|
+
*
|
|
716
|
+
* Fontes:
|
|
717
|
+
* - NIST SP 811 (2008)
|
|
718
|
+
* - International Yard and Pound Agreement (1959)
|
|
719
|
+
* - SI Brochure, 9th Edition (2019)
|
|
720
|
+
*/
|
|
721
|
+
|
|
722
|
+
type LengthUnit = "kilometer" | "hectometer" | "decameter" | "meter" | "decimeter" | "centimeter" | "millimeter" | "micrometer" | "nanometer" | "inch" | "foot" | "yard" | "mile" | "nautical_mile" | "fathom" | "furlong" | "league";
|
|
723
|
+
|
|
724
|
+
declare class LengthRole extends SimpleRole {
|
|
725
|
+
readonly name = "length";
|
|
726
|
+
readonly base = "meter";
|
|
727
|
+
readonly units: Record<LengthUnit, SimpleUnitConfig>;
|
|
728
|
+
readonly aliases: UnitAliases;
|
|
729
|
+
}
|
|
730
|
+
/** Instância singleton da LengthRole */
|
|
731
|
+
declare const lengthRole: LengthRole;
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Mass Role - Constants
|
|
735
|
+
*
|
|
736
|
+
* Fatores de conversão, símbolos e aliases para unidades de massa.
|
|
737
|
+
*
|
|
738
|
+
* Fontes:
|
|
739
|
+
* - NIST SP 811 (2008)
|
|
740
|
+
* - International Yard and Pound Agreement (1959)
|
|
741
|
+
* - SI Brochure, 9th Edition (2019)
|
|
742
|
+
*
|
|
743
|
+
* Nota: Massa ≠ Peso
|
|
744
|
+
* - Massa: quantidade de matéria (invariante)
|
|
745
|
+
* - Peso: força gravitacional (varia com localização)
|
|
746
|
+
*/
|
|
747
|
+
|
|
748
|
+
type MassUnit = "metric_ton" | "kilogram" | "hectogram" | "decagram" | "gram" | "decigram" | "centigram" | "milligram" | "microgram" | "long_ton" | "short_ton" | "stone" | "pound" | "ounce" | "dram" | "grain" | "troy_pound" | "troy_ounce" | "pennyweight";
|
|
749
|
+
|
|
750
|
+
declare class MassRole extends SimpleRole {
|
|
751
|
+
readonly name = "mass";
|
|
752
|
+
readonly base = "kilogram";
|
|
753
|
+
readonly units: Record<MassUnit, SimpleUnitConfig>;
|
|
754
|
+
readonly aliases: UnitAliases;
|
|
755
|
+
readonly validation: SimpleValidationConfig;
|
|
756
|
+
}
|
|
757
|
+
/** Instância singleton da MassRole */
|
|
758
|
+
declare const massRole: MassRole;
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* Temperature Role - Constants
|
|
762
|
+
*
|
|
763
|
+
* Fórmulas de conversão, símbolos e aliases para unidades de temperatura.
|
|
764
|
+
*
|
|
765
|
+
* IMPORTANTE: Temperatura usa FÓRMULAS, não fatores multiplicativos.
|
|
766
|
+
* Isso porque as escalas têm offsets diferentes (0°C ≠ 0°F ≠ 0K).
|
|
767
|
+
*
|
|
768
|
+
* Fontes:
|
|
769
|
+
* - NIST SP 811 (2008)
|
|
770
|
+
* - SI Brochure, 9th Edition (2019)
|
|
771
|
+
*/
|
|
772
|
+
|
|
773
|
+
type TemperatureUnit = "celsius" | "fahrenheit" | "kelvin" | "rankine";
|
|
774
|
+
|
|
775
|
+
declare class TemperatureRole extends SimpleRole {
|
|
776
|
+
readonly name = "temperature";
|
|
777
|
+
readonly base = "celsius";
|
|
778
|
+
readonly units: Record<TemperatureUnit, SimpleUnitConfig>;
|
|
779
|
+
readonly aliases: UnitAliases;
|
|
780
|
+
readonly validation: SimpleValidationConfig;
|
|
781
|
+
/**
|
|
782
|
+
* Override validate para considerar o zero absoluto na escala correta
|
|
783
|
+
*/
|
|
784
|
+
validate(variant: string, value: unknown): {
|
|
785
|
+
valid: boolean;
|
|
786
|
+
errors: string[];
|
|
787
|
+
};
|
|
788
|
+
/**
|
|
789
|
+
* Retorna o zero absoluto na escala especificada
|
|
790
|
+
*/
|
|
791
|
+
private getAbsoluteZero;
|
|
792
|
+
}
|
|
793
|
+
/** Instância singleton da TemperatureRole */
|
|
794
|
+
declare const temperatureRole: TemperatureRole;
|
|
795
|
+
|
|
796
|
+
/**
|
|
797
|
+
* Angle Role - Constants
|
|
798
|
+
*
|
|
799
|
+
* Fatores de conversão, símbolos e aliases para unidades de ângulo.
|
|
800
|
+
*
|
|
801
|
+
* Base: degree (grau) - mais comum em aplicações práticas.
|
|
802
|
+
* Nota: Embora radiano seja a unidade SI, grau é mais intuitivo para a maioria dos casos.
|
|
803
|
+
*
|
|
804
|
+
* Fontes:
|
|
805
|
+
* - SI Brochure, 9th Edition (2019)
|
|
806
|
+
* - NIST SP 811 (2008)
|
|
807
|
+
*/
|
|
808
|
+
|
|
809
|
+
type AngleUnit = "turn" | "degree" | "arcminute" | "arcsecond" | "milliarcsecond" | "radian" | "milliradian" | "gradian";
|
|
810
|
+
|
|
811
|
+
declare class AngleRole extends SimpleRole {
|
|
812
|
+
readonly name = "angle";
|
|
813
|
+
readonly base = "degree";
|
|
814
|
+
readonly units: Record<AngleUnit, SimpleUnitConfig>;
|
|
815
|
+
readonly aliases: UnitAliases;
|
|
816
|
+
}
|
|
817
|
+
/** Instância singleton da AngleRole */
|
|
818
|
+
declare const angleRole: AngleRole;
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* Energy Role - Constants
|
|
822
|
+
*
|
|
823
|
+
* Fatores de conversão, símbolos e aliases para unidades de energia.
|
|
824
|
+
*
|
|
825
|
+
* Fontes:
|
|
826
|
+
* - NIST SP 811 (2008)
|
|
827
|
+
* - SI Brochure, 9th Edition (2019)
|
|
828
|
+
* - CODATA 2018 (electronvolt)
|
|
829
|
+
*/
|
|
830
|
+
|
|
831
|
+
type EnergyUnit = "gigajoule" | "megajoule" | "kilojoule" | "joule" | "millijoule" | "calorie" | "kilocalorie" | "watt_hour" | "kilowatt_hour" | "megawatt_hour" | "gigawatt_hour" | "btu" | "therm" | "electronvolt" | "kiloelectronvolt" | "megaelectronvolt" | "erg" | "foot_pound";
|
|
832
|
+
|
|
833
|
+
declare class EnergyRole extends SimpleRole {
|
|
834
|
+
readonly name = "energy";
|
|
835
|
+
readonly base = "joule";
|
|
836
|
+
readonly units: Record<EnergyUnit, SimpleUnitConfig>;
|
|
837
|
+
readonly aliases: UnitAliases;
|
|
838
|
+
readonly validation: SimpleValidationConfig;
|
|
839
|
+
}
|
|
840
|
+
/** Instância singleton da EnergyRole */
|
|
841
|
+
declare const energyRole: EnergyRole;
|
|
842
|
+
|
|
843
|
+
/**
|
|
844
|
+
* Power Role - Constants
|
|
845
|
+
*
|
|
846
|
+
* Fatores de conversão, símbolos e aliases para unidades de potência.
|
|
847
|
+
*
|
|
848
|
+
* Fontes:
|
|
849
|
+
* - NIST SP 811 (2008)
|
|
850
|
+
* - SI Brochure, 9th Edition (2019)
|
|
851
|
+
*/
|
|
852
|
+
|
|
853
|
+
type PowerUnit = "gigawatt" | "megawatt" | "kilowatt" | "watt" | "milliwatt" | "microwatt" | "horsepower_mechanical" | "horsepower_metric" | "horsepower_electric" | "horsepower_boiler" | "btu_per_hour" | "btu_per_second" | "ton_of_refrigeration" | "foot_pound_per_second" | "calorie_per_second" | "kilocalorie_per_hour";
|
|
854
|
+
|
|
855
|
+
declare class PowerRole extends SimpleRole {
|
|
856
|
+
readonly name = "power";
|
|
857
|
+
readonly base = "watt";
|
|
858
|
+
readonly units: Record<PowerUnit, SimpleUnitConfig>;
|
|
859
|
+
readonly aliases: UnitAliases;
|
|
860
|
+
readonly validation: SimpleValidationConfig;
|
|
861
|
+
}
|
|
862
|
+
/** Instância singleton da PowerRole */
|
|
863
|
+
declare const powerRole: PowerRole;
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Speed Role - Constants
|
|
867
|
+
*
|
|
868
|
+
* Fatores de conversão, símbolos e aliases para unidades de velocidade.
|
|
869
|
+
*
|
|
870
|
+
* Fontes:
|
|
871
|
+
* - NIST SP 811 (2008)
|
|
872
|
+
* - SI Brochure, 9th Edition (2019)
|
|
873
|
+
* - International Yard and Pound Agreement (1959)
|
|
874
|
+
*/
|
|
875
|
+
|
|
876
|
+
type SpeedUnit = "meter_per_second" | "kilometer_per_hour" | "mile_per_hour" | "foot_per_second" | "knot" | "mach" | "speed_of_light";
|
|
877
|
+
|
|
878
|
+
declare class SpeedRole extends SimpleRole {
|
|
879
|
+
readonly name = "speed";
|
|
880
|
+
readonly base = "meter_per_second";
|
|
881
|
+
readonly units: Record<SpeedUnit, SimpleUnitConfig>;
|
|
882
|
+
readonly aliases: UnitAliases;
|
|
883
|
+
}
|
|
884
|
+
/** Instância singleton da SpeedRole */
|
|
885
|
+
declare const speedRole: SpeedRole;
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* Date Role - Types
|
|
889
|
+
*
|
|
890
|
+
* Tipos para representação de datas nas diferentes variantes.
|
|
891
|
+
*/
|
|
892
|
+
/**
|
|
893
|
+
* Tipo base para Date: timestamp em milissegundos (como JavaScript Date.getTime())
|
|
894
|
+
*
|
|
895
|
+
* @example
|
|
896
|
+
* const ts: DateTimestamp = 1733425800000; // 2024-12-05T19:30:00.000Z
|
|
897
|
+
*/
|
|
898
|
+
type DateTimestamp = number;
|
|
899
|
+
/**
|
|
900
|
+
* Variante ISO 8601
|
|
901
|
+
*
|
|
902
|
+
* @example
|
|
903
|
+
* "2024-12-05T19:30:00.000Z"
|
|
904
|
+
* "2024-12-05T19:30:00.000-03:00"
|
|
905
|
+
* "2024-12-05"
|
|
906
|
+
*/
|
|
907
|
+
type DateIso = string;
|
|
908
|
+
/**
|
|
909
|
+
* Variante Epoch (segundos desde 1970-01-01T00:00:00Z)
|
|
910
|
+
*
|
|
911
|
+
* @example
|
|
912
|
+
* 1733425800 // 2024-12-05T19:30:00Z
|
|
913
|
+
*/
|
|
914
|
+
type DateEpoch = number;
|
|
915
|
+
type DateVariant = "iso" | "timestamp" | "epoch";
|
|
916
|
+
|
|
917
|
+
interface DateFormatOptions extends BaseFormatOptions {
|
|
918
|
+
/** Estilo de data: "full", "long", "medium", "short" */
|
|
919
|
+
dateStyle?: "full" | "long" | "medium" | "short";
|
|
920
|
+
/** Estilo de hora: "full", "long", "medium", "short" */
|
|
921
|
+
timeStyle?: "full" | "long" | "medium" | "short";
|
|
922
|
+
/** Timezone (ex: "America/Sao_Paulo", "UTC") */
|
|
923
|
+
timeZone?: string;
|
|
924
|
+
/** Se true, mostra apenas data (sem hora) */
|
|
925
|
+
dateOnly?: boolean;
|
|
926
|
+
/** Se true, mostra apenas hora (sem data) */
|
|
927
|
+
timeOnly?: boolean;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
/**
|
|
931
|
+
* DateRole - Role para conversão e manipulação de datas
|
|
932
|
+
*
|
|
933
|
+
* ComplexRole com 3 variantes:
|
|
934
|
+
* - iso: string ISO 8601 ("2024-12-05T19:30:00.000Z")
|
|
935
|
+
* - timestamp: number em milissegundos (1733425800000)
|
|
936
|
+
* - epoch: number em segundos (1733425800)
|
|
937
|
+
*
|
|
938
|
+
* @example
|
|
939
|
+
* const date = new DateRole();
|
|
940
|
+
* date.convert('iso', 'epoch', '2024-12-05T19:30:00.000Z') // 1733425800
|
|
941
|
+
* date.convert('epoch', 'iso', 1733425800) // '2024-12-05T19:30:00.000Z'
|
|
942
|
+
* date.cast('iso', '2024-12-05') // '2024-12-05T00:00:00.000Z'
|
|
943
|
+
* date.format('iso', '2024-12-05T19:30:00.000Z', { dateStyle: 'full', locale: 'pt-BR' })
|
|
944
|
+
*/
|
|
945
|
+
|
|
946
|
+
declare class DateRole extends ComplexRole<DateTimestamp> {
|
|
947
|
+
readonly name = "date";
|
|
948
|
+
readonly base = "timestamp";
|
|
949
|
+
protected createVariants(): Record<string, IVariant<unknown, DateTimestamp>>;
|
|
950
|
+
/**
|
|
951
|
+
* Override format to accept DateFormatOptions
|
|
952
|
+
*/
|
|
953
|
+
format(variant: string, value: unknown, options?: DateFormatOptions): string;
|
|
954
|
+
}
|
|
955
|
+
/** Instância singleton da DateRole */
|
|
956
|
+
declare const dateRole: DateRole;
|
|
957
|
+
|
|
958
|
+
/**
|
|
959
|
+
* Volume Role - Constants
|
|
960
|
+
*
|
|
961
|
+
* Fatores de conversão, símbolos e aliases para unidades de volume.
|
|
962
|
+
*
|
|
963
|
+
* Fontes:
|
|
964
|
+
* - NIST SP 811 (2008)
|
|
965
|
+
* - NIST Handbook 44 (2024)
|
|
966
|
+
* - SI Brochure, 9th Edition (2019)
|
|
967
|
+
*
|
|
968
|
+
* Notas:
|
|
969
|
+
* - Base: liter (L) - unidade aceita para uso com o SI
|
|
970
|
+
* - 1 L = 1 dm³ = 0.001 m³
|
|
971
|
+
* - Galão US vs UK: ~20% diferença (UK é maior)
|
|
972
|
+
*/
|
|
973
|
+
|
|
974
|
+
type VolumeUnit = "cubic_meter" | "cubic_decimeter" | "cubic_centimeter" | "cubic_millimeter" | "hectoliter" | "decaliter" | "liter" | "deciliter" | "centiliter" | "milliliter" | "microliter" | "gallon_us" | "quart_us" | "pint_us" | "cup_us" | "fluid_ounce_us" | "tablespoon_us" | "teaspoon_us" | "gallon_uk" | "quart_uk" | "pint_uk" | "fluid_ounce_uk" | "barrel_oil" | "cubic_inch" | "cubic_foot" | "cubic_yard";
|
|
975
|
+
|
|
976
|
+
declare class VolumeRole extends SimpleRole {
|
|
977
|
+
readonly name = "volume";
|
|
978
|
+
readonly base = "liter";
|
|
979
|
+
readonly units: Record<VolumeUnit, SimpleUnitConfig>;
|
|
980
|
+
readonly aliases: UnitAliases;
|
|
981
|
+
readonly validation: SimpleValidationConfig;
|
|
982
|
+
}
|
|
983
|
+
/** Instância singleton da VolumeRole */
|
|
984
|
+
declare const volumeRole: VolumeRole;
|
|
985
|
+
|
|
986
|
+
/**
|
|
987
|
+
* Time Role - Constants
|
|
988
|
+
*
|
|
989
|
+
* Fatores de conversão, símbolos e aliases para unidades de tempo/duração.
|
|
990
|
+
*
|
|
991
|
+
* Fontes:
|
|
992
|
+
* - SI Brochure, 9th Edition (2019)
|
|
993
|
+
* - Gregorian calendar (365.2425 dias/ano)
|
|
994
|
+
*/
|
|
995
|
+
|
|
996
|
+
type TimeUnit = "nanosecond" | "microsecond" | "millisecond" | "second" | "minute" | "hour" | "day" | "week" | "month" | "year" | "decade" | "century" | "millennium";
|
|
997
|
+
|
|
998
|
+
declare class TimeRole extends SimpleRole {
|
|
999
|
+
readonly name = "time";
|
|
1000
|
+
readonly base = "second";
|
|
1001
|
+
readonly units: Record<TimeUnit, SimpleUnitConfig>;
|
|
1002
|
+
readonly aliases: UnitAliases;
|
|
1003
|
+
readonly validation: SimpleValidationConfig;
|
|
1004
|
+
}
|
|
1005
|
+
/** Instância singleton da TimeRole */
|
|
1006
|
+
declare const timeRole: TimeRole;
|
|
1007
|
+
|
|
1008
|
+
/**
|
|
1009
|
+
* Digital Storage Role - Constants
|
|
1010
|
+
*
|
|
1011
|
+
* Fatores de conversão, símbolos e aliases para unidades de armazenamento digital.
|
|
1012
|
+
*
|
|
1013
|
+
* Fontes:
|
|
1014
|
+
* - IEC 60027-2 (prefixos binários)
|
|
1015
|
+
* - SI Brochure, 9th Edition (2019)
|
|
1016
|
+
*
|
|
1017
|
+
* IMPORTANTE: Esta biblioteca suporta AMBOS os sistemas:
|
|
1018
|
+
* - SI (decimal): kB, MB, GB, TB (base 1000)
|
|
1019
|
+
* - IEC (binário): KiB, MiB, GiB, TiB (base 1024)
|
|
1020
|
+
*/
|
|
1021
|
+
|
|
1022
|
+
type DigitalUnit = "bit" | "byte" | "kibibyte" | "mebibyte" | "gibibyte" | "tebibyte" | "pebibyte" | "exbibyte" | "kilobyte" | "megabyte" | "gigabyte" | "terabyte" | "petabyte" | "exabyte";
|
|
1023
|
+
|
|
1024
|
+
declare class DigitalRole extends SimpleRole {
|
|
1025
|
+
readonly name = "digital";
|
|
1026
|
+
readonly base = "byte";
|
|
1027
|
+
readonly units: Record<DigitalUnit, SimpleUnitConfig>;
|
|
1028
|
+
readonly aliases: UnitAliases;
|
|
1029
|
+
readonly validation: SimpleValidationConfig;
|
|
1030
|
+
}
|
|
1031
|
+
/** Instância singleton da DigitalRole */
|
|
1032
|
+
declare const digitalRole: DigitalRole;
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Frequency Role - Constants
|
|
1036
|
+
*
|
|
1037
|
+
* Fatores de conversão, símbolos e aliases para unidades de frequência.
|
|
1038
|
+
*
|
|
1039
|
+
* Fontes:
|
|
1040
|
+
* - SI Brochure, 9th Edition (2019)
|
|
1041
|
+
* - NIST SP 811
|
|
1042
|
+
*/
|
|
1043
|
+
|
|
1044
|
+
type FrequencyUnit = "terahertz" | "gigahertz" | "megahertz" | "kilohertz" | "hertz" | "millihertz" | "microhertz" | "rpm" | "bpm" | "radians_per_second" | "cycles_per_minute";
|
|
1045
|
+
|
|
1046
|
+
declare class FrequencyRole extends SimpleRole {
|
|
1047
|
+
readonly name = "frequency";
|
|
1048
|
+
readonly base = "hertz";
|
|
1049
|
+
readonly units: Record<FrequencyUnit, SimpleUnitConfig>;
|
|
1050
|
+
readonly aliases: UnitAliases;
|
|
1051
|
+
readonly validation: SimpleValidationConfig;
|
|
1052
|
+
}
|
|
1053
|
+
/** Instância singleton da FrequencyRole */
|
|
1054
|
+
declare const frequencyRole: FrequencyRole;
|
|
1055
|
+
|
|
1056
|
+
/**
|
|
1057
|
+
* Pressure Role - Constants
|
|
1058
|
+
*
|
|
1059
|
+
* Fatores de conversão, símbolos e aliases para unidades de pressão.
|
|
1060
|
+
*
|
|
1061
|
+
* Fontes:
|
|
1062
|
+
* - SI Brochure, 9th Edition (2019)
|
|
1063
|
+
* - NIST SP 811
|
|
1064
|
+
* - 10th CGPM (1954) - definição da atmosfera padrão
|
|
1065
|
+
*/
|
|
1066
|
+
|
|
1067
|
+
type PressureUnit = "megapascal" | "kilopascal" | "hectopascal" | "pascal" | "bar" | "millibar" | "atmosphere" | "torr" | "mmhg" | "inhg" | "psi" | "ksi" | "cmh2o" | "inh2o";
|
|
1068
|
+
|
|
1069
|
+
declare class PressureRole extends SimpleRole {
|
|
1070
|
+
readonly name = "pressure";
|
|
1071
|
+
readonly base = "pascal";
|
|
1072
|
+
readonly units: Record<PressureUnit, SimpleUnitConfig>;
|
|
1073
|
+
readonly aliases: UnitAliases;
|
|
1074
|
+
readonly validation: SimpleValidationConfig;
|
|
1075
|
+
}
|
|
1076
|
+
/** Instância singleton da PressureRole */
|
|
1077
|
+
declare const pressureRole: PressureRole;
|
|
1078
|
+
|
|
1079
|
+
/**
|
|
1080
|
+
* Color Role - Types
|
|
1081
|
+
*
|
|
1082
|
+
* Tipos para representação de cores nas diferentes variantes.
|
|
1083
|
+
*/
|
|
1084
|
+
/**
|
|
1085
|
+
* Tipo base para Color: objeto RGBA com valores 0-255 e alpha 0-1
|
|
1086
|
+
*
|
|
1087
|
+
* @example
|
|
1088
|
+
* const red: RGBA = { r: 255, g: 0, b: 0, a: 1 };
|
|
1089
|
+
* const semiTransparent: RGBA = { r: 0, g: 0, b: 255, a: 0.5 };
|
|
1090
|
+
*/
|
|
1091
|
+
interface RGBA {
|
|
1092
|
+
r: number;
|
|
1093
|
+
g: number;
|
|
1094
|
+
b: number;
|
|
1095
|
+
a: number;
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Variante Hex
|
|
1099
|
+
*
|
|
1100
|
+
* @example
|
|
1101
|
+
* "#ff0000" // RGB (6 chars)
|
|
1102
|
+
* "#ff0000ff" // RGBA (8 chars)
|
|
1103
|
+
* "#f00" // RGB shorthand (3 chars)
|
|
1104
|
+
* "#f00f" // RGBA shorthand (4 chars)
|
|
1105
|
+
*/
|
|
1106
|
+
type ColorHex = string;
|
|
1107
|
+
/**
|
|
1108
|
+
* Variante RGB Object
|
|
1109
|
+
*
|
|
1110
|
+
* @example
|
|
1111
|
+
* { r: 255, g: 0, b: 0 }
|
|
1112
|
+
* { r: 255, g: 0, b: 0, a: 0.5 }
|
|
1113
|
+
*/
|
|
1114
|
+
interface ColorRgbObject {
|
|
1115
|
+
r: number;
|
|
1116
|
+
g: number;
|
|
1117
|
+
b: number;
|
|
1118
|
+
a?: number;
|
|
1119
|
+
}
|
|
1120
|
+
/**
|
|
1121
|
+
* Variante RGB String
|
|
1122
|
+
*
|
|
1123
|
+
* @example
|
|
1124
|
+
* "rgb(255, 0, 0)"
|
|
1125
|
+
* "rgba(255, 0, 0, 0.5)"
|
|
1126
|
+
*/
|
|
1127
|
+
type ColorRgbString = string;
|
|
1128
|
+
/**
|
|
1129
|
+
* Variante HSL Object
|
|
1130
|
+
*
|
|
1131
|
+
* @example
|
|
1132
|
+
* { h: 0, s: 100, l: 50 } // Red
|
|
1133
|
+
* { h: 0, s: 100, l: 50, a: 0.5 } // Semi-transparent red
|
|
1134
|
+
*/
|
|
1135
|
+
interface ColorHslObject {
|
|
1136
|
+
h: number;
|
|
1137
|
+
s: number;
|
|
1138
|
+
l: number;
|
|
1139
|
+
a?: number;
|
|
1140
|
+
}
|
|
1141
|
+
/**
|
|
1142
|
+
* Variante HSL String
|
|
1143
|
+
*
|
|
1144
|
+
* @example
|
|
1145
|
+
* "hsl(0, 100%, 50%)"
|
|
1146
|
+
* "hsla(0, 100%, 50%, 0.5)"
|
|
1147
|
+
*/
|
|
1148
|
+
type ColorHslString = string;
|
|
1149
|
+
type ColorVariant = "hex" | "rgb_object" | "rgb_string" | "hsl_object" | "hsl_string";
|
|
1150
|
+
|
|
1151
|
+
interface ColorFormatOptions extends BaseFormatOptions {
|
|
1152
|
+
/** Se true, usa letras maiúsculas para hex */
|
|
1153
|
+
uppercase?: boolean;
|
|
1154
|
+
/** Se true, inclui alpha mesmo quando é 1 */
|
|
1155
|
+
includeAlpha?: boolean;
|
|
1156
|
+
/** Se true, usa formato compacto (shorthand hex, sem espaços em rgb) */
|
|
1157
|
+
compact?: boolean;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
/**
|
|
1161
|
+
* ColorRole - Role para conversão e manipulação de cores
|
|
1162
|
+
*
|
|
1163
|
+
* ComplexRole com 5 variantes:
|
|
1164
|
+
* - hex: string hexadecimal ("#ff0000", "#ff0000ff")
|
|
1165
|
+
* - rgb_object: objeto { r, g, b, a? }
|
|
1166
|
+
* - rgb_string: string "rgb(255, 0, 0)" ou "rgba(255, 0, 0, 0.5)"
|
|
1167
|
+
* - hsl_object: objeto { h, s, l, a? }
|
|
1168
|
+
* - hsl_string: string "hsl(0, 100%, 50%)" ou "hsla(0, 100%, 50%, 0.5)"
|
|
1169
|
+
*
|
|
1170
|
+
* @example
|
|
1171
|
+
* const color = new ColorRole();
|
|
1172
|
+
* color.convert('hex', 'rgb_object', '#ff0000') // { r: 255, g: 0, b: 0 }
|
|
1173
|
+
* color.convert('rgb_object', 'hsl_string', { r: 255, g: 0, b: 0 }) // "hsl(0, 100%, 50%)"
|
|
1174
|
+
* color.cast('hex', 'red') // '#ff0000'
|
|
1175
|
+
* color.format('hex', '#ff0000', { uppercase: true }) // '#FF0000'
|
|
1176
|
+
*/
|
|
1177
|
+
|
|
1178
|
+
declare class ColorRole extends ComplexRole<RGBA> {
|
|
1179
|
+
readonly name = "color";
|
|
1180
|
+
readonly base = "rgb_object";
|
|
1181
|
+
protected createVariants(): Record<string, IVariant<unknown, RGBA>>;
|
|
1182
|
+
/**
|
|
1183
|
+
* Override format to accept ColorFormatOptions
|
|
1184
|
+
*/
|
|
1185
|
+
format(variant: string, value: unknown, options?: ColorFormatOptions): string;
|
|
1186
|
+
}
|
|
1187
|
+
/** Instância singleton da ColorRole */
|
|
1188
|
+
declare const colorRole: ColorRole;
|
|
1189
|
+
|
|
1190
|
+
export { AngleRole, type AngleUnit, AreaRole, type AreaUnit, type BaseFormatOptions, type CastFn, type CastResult, type ColorHex, type ColorHslObject, type ColorHslString, type ColorRgbObject, type ColorRgbString, ColorRole, type ColorVariant, type ConversionResult, type DateEpoch, type DateIso, DateRole, type DateTimestamp, type DateVariant, DigitalRole, type DigitalUnit, EnergyRole, type EnergyUnit, type FormatFn, type FormatOptions, type FormatSpec, FrequencyRole, type FrequencyUnit, type FromBaseFn, LengthRole, type LengthUnit, MassRole, type MassUnit, type MorpherFn, type MorpherKey, type MorpherSpec, type ParsedVariantId, PowerRole, type PowerUnit, PressureRole, type PressureUnit, type RGBA, type ReversibilityResult, RoleMorphic, type RoleSpec, SpeedRole, type SpeedUnit, TemperatureRole, type TemperatureUnit, TimeRole, type TimeUnit, type ToBaseFn, type ValidationResult, type ValidationRule, type VariantSpec, VolumeRole, type VolumeUnit, angleRole, areaRole, colorRole, dateRole, digitalRole, energyRole, frequencyRole, lengthRole, massRole, powerRole, pressureRole, speedRole, temperatureRole, timeRole, volumeRole };
|