@atlantjs/arch 15.6.7 → 15.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 (106) hide show
  1. package/index.js +60 -0
  2. package/package.json +4 -3
  3. package/{tsconfig.tsbuildinfo → tsconfig.build.tsbuildinfo} +1 -1
  4. package/src/@tool-box/tests/builder.abstract.util.js +0 -39
  5. package/src/@tool-box/tests/builders/datetime/datetime.edge.builder.js +0 -15
  6. package/src/@tool-box/tests/builders/failures/dummies/failure.dummy.js +0 -13
  7. package/src/@tool-box/tests/builders/failures/failure.builder.js +0 -17
  8. package/src/@tool-box/tests/builders/metadata/metadata-uv.builder.js +0 -18
  9. package/src/@tool-box/tests/builders/metadata/metadata.edge.builder.js +0 -15
  10. package/src/@tool-box/tests/builders/user/email.edge.builder.js +0 -15
  11. package/src/@tool-box/tests/builders/user/username.edge.builder.js +0 -15
  12. package/src/@tool-box/tests/faker/faker.js +0 -208
  13. package/src/@tool-box/utils/convert-units/convert-units.js +0 -154
  14. package/src/@tool-box/utils/datatypes/boolean-utils.js +0 -155
  15. package/src/@tool-box/utils/datatypes/generic-types.js +0 -3
  16. package/src/@tool-box/utils/datatypes/plainify.js +0 -2
  17. package/src/@tool-box/utils/datatypes/string-utils.js +0 -292
  18. package/src/@tool-box/utils/datetime/mappers/month.mapper.js +0 -58
  19. package/src/@tool-box/utils/datetime/mappers/points/month-abbreviation.enum.js +0 -18
  20. package/src/@tool-box/utils/datetime/mappers/points/month-number.enum.js +0 -18
  21. package/src/@tool-box/utils/ducts/common.js +0 -47
  22. package/src/@tool-box/utils/ducts/optional-type.js +0 -128
  23. package/src/@tool-box/utils/ducts/return-type.js +0 -67
  24. package/src/@tool-box/utils/http-provider/http-provider-failure-response.js +0 -19
  25. package/src/@tool-box/utils/http-provider/http-provider-success-response.js +0 -20
  26. package/src/@tool-box/utils/http-provider/http-provider.js +0 -85
  27. package/src/@tool-box/utils/logger/index.js +0 -31
  28. package/src/@tool-box/utils/map/map.abstract.js +0 -84
  29. package/src/@tool-box/utils/random/random.js +0 -260
  30. package/src/@tool-box/utils/type-guard/guardian-exception.js +0 -6
  31. package/src/@tool-box/utils/type-guard/guardian.js +0 -625
  32. package/src/@tool-box/utils/type-guard/guardian.type.js +0 -2
  33. package/src/@tool-box/utils/validators/is-cron-expression.js +0 -39
  34. package/src/@tool-box/utils/validators/is-date-string.js +0 -42
  35. package/src/@tool-box/utils/validators/is-password-match.js +0 -27
  36. package/src/@tool-box/utils/validators/is-password-policy.validator.js +0 -30
  37. package/src/@tool-box/utils/validators/is-schedule.js +0 -43
  38. package/src/@tool-box/utils/validators/is-time-string.js +0 -39
  39. package/src/@tool-box/utils/validators/is-ulid.js +0 -39
  40. package/src/index.js +0 -179
  41. package/src/objects/@common/edges/email.edge.js +0 -94
  42. package/src/objects/@common/edges/ulid.sketch.edge.js +0 -91
  43. package/src/objects/@common/edges/url.edge.js +0 -269
  44. package/src/objects/@common/edges/username.edge.js +0 -41
  45. package/src/objects/@common/edges/uuid.sketch.edge.js +0 -145
  46. package/src/objects/@common/points/environment.point.js +0 -10
  47. package/src/objects/@common/points/header-token-name.point.js +0 -10
  48. package/src/objects/@common/points/http-status-codes.point.js +0 -244
  49. package/src/objects/amount/amount-value.edge.js +0 -76
  50. package/src/objects/amount/amount.edge.js +0 -626
  51. package/src/objects/amount/amount.polygon.js +0 -2
  52. package/src/objects/amount/amount.uv.js +0 -29
  53. package/src/objects/amount/points/duration-unit.point.js +0 -15
  54. package/src/objects/amount/points/energy-unit.point.js +0 -10
  55. package/src/objects/amount/points/length-unit.point.js +0 -10
  56. package/src/objects/amount/points/mass-unit.point.js +0 -11
  57. package/src/objects/amount/points/month-name.point.js +0 -18
  58. package/src/objects/amount/points/object-unit.point.js +0 -7
  59. package/src/objects/amount/points/units.point.js +0 -2
  60. package/src/objects/amount/points/volume-unit.point.js +0 -8
  61. package/src/objects/amount/points/week-day.point.js +0 -13
  62. package/src/objects/datetime/edges/datetime.edge.js +0 -672
  63. package/src/objects/datetime/edges/locale/day/day-name-to-english.mapper.js +0 -19
  64. package/src/objects/datetime/edges/locale/day/day-name-to-portuguese.mapper.js +0 -19
  65. package/src/objects/datetime/edges/locale/day/today-to-language.mapper.js +0 -15
  66. package/src/objects/datetime/edges/locale/holidays-country.type.js +0 -2
  67. package/src/objects/datetime/edges/locale/month/month-to-english.mapper.js +0 -24
  68. package/src/objects/datetime/edges/locale/month/month-to-portuguese.mapper.js +0 -24
  69. package/src/objects/datetime/points/month-name.enum.js +0 -18
  70. package/src/objects/datetime/points/week-day.enum.js +0 -13
  71. package/src/objects/failure/edges/failure.abstract.js +0 -24
  72. package/src/objects/failure/edges/failure.abstract.polygon.js +0 -2
  73. package/src/objects/language/points/language.point.js +0 -135
  74. package/src/objects/metadata/metadata.edge.js +0 -25
  75. package/src/objects/metadata/metadata.polygon.js +0 -2
  76. package/src/objects/metadata/metadata.uv.js +0 -29
  77. package/src/objects/password/password.edge.js +0 -175
  78. package/src/objects/password/password.polygon.js +0 -2
  79. package/src/objects/password/steps/not-allowing-consecutive-chars-step.js +0 -34
  80. package/src/objects/password/steps/not-allowing-date-step.js +0 -61
  81. package/src/objects/password/steps/not-allowing-phone-step.js +0 -27
  82. package/src/objects/password/steps/not-allowing-repeated-chars-step.js +0 -34
  83. package/src/objects/password/steps/not-allowing-string-step.js +0 -19
  84. package/src/objects/password/steps/not-allowing-these-chars-step.js +0 -17
  85. package/src/objects/password/steps/numeric-step.js +0 -13
  86. package/src/objects/password/steps/with-at-least-one-letter-step.js +0 -14
  87. package/src/objects/password/steps/with-at-least-one-number-digit-step.js +0 -14
  88. package/src/objects/password/steps/with-at-least-one-special-char-step.js +0 -14
  89. package/src/objects/password/steps/with-length-step.js +0 -18
  90. package/src/objects/password/validation-step.js +0 -9
  91. package/src/objects/password/validation-step.type.js +0 -2
  92. package/src/objects/primitives/boolean.edge.sketch.js +0 -147
  93. package/src/objects/primitives/datetime.edge.sketch.js +0 -7
  94. package/src/objects/primitives/number.edge.sketch.js +0 -346
  95. package/src/objects/primitives/string.edge.sketch.js +0 -218
  96. package/src/objects/scheduling/scheduling.edge.failure.js +0 -14
  97. package/src/objects/scheduling/scheduling.edge.js +0 -280
  98. package/src/objects/time/time.edge.js +0 -447
  99. package/src/objects-interface/edges/edge.abstract.js +0 -6
  100. package/src/objects-interface/face.abstract.js +0 -6
  101. package/src/objects-interface/solid.abstract.js +0 -11
  102. package/src/objects-interface/uv.abstract.js +0 -6
  103. package/src/objects-interface/vertices/vertex.abstract.js +0 -11
  104. package/src/shared/payload.abstract.js +0 -6
  105. package/src/shared/request.abstract.js +0 -3
  106. package/src/shared/response.abstract.js +0 -6
@@ -1,85 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.HttpProvider = void 0;
7
- const axios_1 = __importDefault(require("axios"));
8
- const return_type_1 = require("#/@tool-box/utils/ducts/return-type");
9
- const http_provider_failure_response_1 = require("#/@tool-box/utils/http-provider/http-provider-failure-response");
10
- const http_provider_success_response_1 = require("#/@tool-box/utils/http-provider/http-provider-success-response");
11
- const http_status_codes_point_1 = require("#/objects/@common/points/http-status-codes.point");
12
- function replaceUrlParams(url, params) {
13
- return url.replace(/:([a-zA-Z0-9_]+)/g, (_, key) => {
14
- const value = params[key];
15
- if (value === undefined) {
16
- throw new Error(`Parâmetro "${key}" não encontrado em params`);
17
- }
18
- return encodeURIComponent(String(value));
19
- });
20
- }
21
- class HttpProvider {
22
- constructor(baseUrl) {
23
- this.baseUrl = baseUrl;
24
- this.axios = axios_1.default.create({
25
- baseURL: baseUrl,
26
- });
27
- }
28
- setDefaultHeader(key, value) {
29
- this.axios.defaults.headers.common[key] = value;
30
- }
31
- removeDefaultHeader(key) {
32
- delete this.axios.defaults.headers.common[key];
33
- }
34
- setBearerToken(token) {
35
- this.setDefaultHeader("Authorization", `Bearer ${token}`);
36
- }
37
- async request(request) {
38
- let resolvedUrl = request.url;
39
- try {
40
- if (request.params) {
41
- resolvedUrl = replaceUrlParams(resolvedUrl, request.params);
42
- }
43
- const response = await this.axios.request({
44
- url: resolvedUrl,
45
- method: request.method,
46
- params: request.queryParams,
47
- data: request.payload,
48
- headers: request.headers,
49
- responseType: request.responseType,
50
- validateStatus: () => true,
51
- });
52
- if (!this.isSuccessStatus(response.status)) {
53
- return (0, return_type_1.Failure)(this.buildFailureFromResponse(response, resolvedUrl));
54
- }
55
- return (0, return_type_1.Success)(new http_provider_success_response_1.HttpProviderSuccessResponse(response.status, response.data));
56
- }
57
- catch (error) {
58
- if (axios_1.default.isAxiosError(error) && error.response) {
59
- return (0, return_type_1.Failure)(this.buildFailureFromResponse(error.response, resolvedUrl));
60
- }
61
- return (0, return_type_1.Failure)(new http_provider_failure_response_1.HttpProviderFailureResponse("The request could not be completed. The server is currently unavailable.", http_status_codes_point_1.HttpStatusCodes.SERVICE_UNAVAILABLE, resolvedUrl));
62
- }
63
- }
64
- isSuccessStatus(status) {
65
- return status >= 200 && status < 300;
66
- }
67
- buildFailureFromResponse(response, url) {
68
- return new http_provider_failure_response_1.HttpProviderFailureResponse(this.extractErrorMessage(response.data, response.statusText), response.status, url);
69
- }
70
- extractErrorMessage(data, fallback) {
71
- if (typeof data === "string" && data.trim().length > 0) {
72
- return data;
73
- }
74
- if (data && typeof data === "object") {
75
- const maybeMessage = data.message;
76
- if (typeof maybeMessage === "string" && maybeMessage.trim().length > 0) {
77
- return maybeMessage;
78
- }
79
- }
80
- return fallback?.trim()
81
- ? fallback
82
- : "The request failed. Please try again later.";
83
- }
84
- }
85
- exports.HttpProvider = HttpProvider;
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.c = void 0;
4
- exports.c = {
5
- log: (prefix, value) => {
6
- console.log(prefix, JSON.stringify(value, (key, val) => {
7
- if (val && typeof val === "object" && val.constructor !== Object) {
8
- const symbolKeys = Object.getOwnPropertySymbols(val);
9
- const symbolProps = symbolKeys.reduce((acc, sym) => {
10
- acc[sym.toString()] = val[sym];
11
- return acc;
12
- }, {});
13
- return { ...val, ...symbolProps };
14
- }
15
- return val;
16
- }, 2));
17
- },
18
- warn: (prefix, value) => {
19
- console.warn(prefix, JSON.stringify(value, (key, val) => {
20
- if (val && typeof val === "object" && val.constructor !== Object) {
21
- const symbolKeys = Object.getOwnPropertySymbols(val);
22
- const symbolProps = symbolKeys.reduce((acc, sym) => {
23
- acc[sym.toString()] = val[sym];
24
- return acc;
25
- }, {});
26
- return { ...val, ...symbolProps };
27
- }
28
- return val;
29
- }, 2));
30
- },
31
- };
@@ -1,84 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MapAbstract = void 0;
4
- class MapAbstract {
5
- /**
6
- * Mantido por compatibilidade.
7
- * Retorna o valor mapeado para a chave ou lança erro.
8
- */
9
- toMap(key) {
10
- return this.getOrThrow(key);
11
- }
12
- /**
13
- * Retorna o valor mapeado para a chave ou lança erro.
14
- */
15
- get(key) {
16
- return this.getOrThrow(key);
17
- }
18
- /**
19
- * Retorna true se a chave existir no map.
20
- */
21
- has(key) {
22
- return this.map.has(key);
23
- }
24
- /**
25
- * Retorna o valor ou undefined.
26
- */
27
- getOrUndefined(key) {
28
- return this.map.get(key);
29
- }
30
- /**
31
- * Retorna a quantidade de itens.
32
- */
33
- size() {
34
- return this.map.size;
35
- }
36
- /**
37
- * Retorna true se o map estiver vazio.
38
- */
39
- isEmpty() {
40
- return this.map.size === 0;
41
- }
42
- /**
43
- * Retorna todas as chaves.
44
- */
45
- keys() {
46
- return Array.from(this.map.keys());
47
- }
48
- /**
49
- * Retorna todos os valores.
50
- */
51
- values() {
52
- return Array.from(this.map.values());
53
- }
54
- /**
55
- * Retorna todas as entradas.
56
- */
57
- entries() {
58
- return Array.from(this.map.entries());
59
- }
60
- getOrDefault(key, defaultValue) {
61
- // bug fix: usar has() evita confundir chave existente com valor undefined
62
- if (!this.map.has(key)) {
63
- return defaultValue;
64
- }
65
- return this.map.get(key);
66
- }
67
- getOrThrow(key, errorMessage = "Key not mapped") {
68
- // bug fix: validar existência da chave com has(), não pelo valor retornado
69
- if (!this.map.has(key)) {
70
- throw new Error(errorMessage);
71
- }
72
- return this.map.get(key);
73
- }
74
- set(key, value) {
75
- this.map.set(key, value);
76
- }
77
- delete(key) {
78
- return this.map.delete(key);
79
- }
80
- clear() {
81
- this.map.clear();
82
- }
83
- }
84
- exports.MapAbstract = MapAbstract;
@@ -1,260 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Random = void 0;
4
- class Random {
5
- // ==================== Números ====================
6
- /**
7
- * Gera um número inteiro aleatório dentro de um intervalo (inclusivo).
8
- * @param min - Valor mínimo do intervalo
9
- * @param max - Valor máximo do intervalo
10
- * @returns Número inteiro aleatório entre min e max
11
- * @example
12
- * Random.number(1, 10) // pode retornar qualquer inteiro entre 1 e 10
13
- */
14
- static number(min, max) {
15
- return Math.floor(Math.random() * (max - min + 1)) + min;
16
- }
17
- /**
18
- * Gera um número decimal (float) aleatório dentro de um intervalo.
19
- * @param min - Valor mínimo do intervalo
20
- * @param max - Valor máximo do intervalo
21
- * @param precision - Número de casas decimais (padrão: 2)
22
- * @returns Número decimal aleatório entre min e max
23
- * @example
24
- * Random.float(1, 10) // pode retornar algo como 4.73
25
- * Random.float(1, 10, 4) // pode retornar algo como 4.7312
26
- */
27
- static float(min, max, precision = 2) {
28
- const value = Math.random() * (max - min) + min;
29
- return Number(value.toFixed(precision));
30
- }
31
- /**
32
- * Gera um número inteiro positivo aleatório até um valor máximo.
33
- * @param max - Valor máximo do intervalo (padrão: 100)
34
- * @returns Número inteiro positivo aleatório entre 1 e max
35
- * @example
36
- * Random.positiveNumber() // pode retornar qualquer inteiro entre 1 e 100
37
- * Random.positiveNumber(50) // pode retornar qualquer inteiro entre 1 e 50
38
- */
39
- static positiveNumber(max = 100) {
40
- return Random.number(1, max);
41
- }
42
- /**
43
- * Gera um número inteiro negativo aleatório até um valor mínimo.
44
- * @param min - Valor mínimo do intervalo (padrão: -100)
45
- * @returns Número inteiro negativo aleatório entre min e -1
46
- * @example
47
- * Random.negativeNumber() // pode retornar qualquer inteiro entre -100 e -1
48
- * Random.negativeNumber(-50) // pode retornar qualquer inteiro entre -50 e -1
49
- */
50
- static negativeNumber(min = -100) {
51
- return Random.number(min, -1);
52
- }
53
- // ==================== Enums ====================
54
- /**
55
- * Retorna um valor aleatório de um enum.
56
- * @template T - Tipo do enum
57
- * @param anEnum - Enum do qual será selecionado o valor aleatório
58
- * @returns Um valor aleatório do enum
59
- * @example
60
- * enum Color { Red, Green, Blue }
61
- * Random.enum(Color) // pode retornar Color.Red, Color.Green ou Color.Blue
62
- */
63
- static enum(anEnum) {
64
- const keys = Object.keys(anEnum).filter((x) => Number.isNaN(Number(x)));
65
- const randomKeyIndex = Math.floor(Math.random() * keys.length);
66
- const randomKey = keys[randomKeyIndex];
67
- return anEnum[randomKey];
68
- }
69
- /**
70
- * Retorna um valor aleatório de um enum, excluindo valores específicos.
71
- * @template T - Tipo do enum
72
- * @param anEnum - Enum do qual será selecionado o valor aleatório
73
- * @param excepts - Array de valores do enum que devem ser excluídos da seleção
74
- * @returns Um valor aleatório do enum que não está nos excepts
75
- * @throws {Error} Se não houver valores válidos após aplicar as exclusões
76
- * @example
77
- * enum Color { Red, Green, Blue }
78
- * Random.enumExcluding(Color, [Color.Red]) // retorna Green ou Blue
79
- */
80
- static enumExcluding(anEnum, excepts) {
81
- const exceptKeys = excepts.map((value) => Object.keys(anEnum).find((key) => anEnum[key] === value));
82
- const validKeys = Object.keys(anEnum).filter((key) => Number.isNaN(Number(key)) && !exceptKeys.includes(key));
83
- if (validKeys.length === 0) {
84
- throw new Error("No valid enum keys available after excluding 'excepts'.");
85
- }
86
- const randomKeyIndex = Math.floor(Math.random() * validKeys.length);
87
- const randomKey = validKeys[randomKeyIndex];
88
- return anEnum[randomKey];
89
- }
90
- // ==================== Strings ====================
91
- /**
92
- * Gera uma string aleatória de caracteres alfanuméricos.
93
- * @param length - Comprimento da string a ser gerada (padrão: 8)
94
- * @returns String aleatória com o comprimento especificado
95
- * @example
96
- * Random.string() // pode retornar "aB3xKp9z"
97
- * Random.string(4) // pode retornar "kR2m"
98
- */
99
- static string(length = 8) {
100
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
101
- return Array.from({ length }, () => chars.charAt(Math.floor(Math.random() * chars.length))).join("");
102
- }
103
- /**
104
- * Gera uma string aleatória contendo apenas letras (sem números).
105
- * @param length - Comprimento da string a ser gerada (padrão: 8)
106
- * @returns String aleatória com apenas letras
107
- * @example
108
- * Random.letters() // pode retornar "AbCdEfGh"
109
- * Random.letters(4) // pode retornar "kRmZ"
110
- */
111
- static letters(length = 8) {
112
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
113
- return Array.from({ length }, () => chars.charAt(Math.floor(Math.random() * chars.length))).join("");
114
- }
115
- /**
116
- * Gera um UUID v4 aleatório no formato padrão.
117
- * @returns UUID no formato xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
118
- * @example
119
- * Random.uuid() // pode retornar "550e8400-e29b-41d4-a716-446655440000"
120
- */
121
- static uuid() {
122
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
123
- const random = (Math.random() * 16) | 0;
124
- const value = char === "x" ? random : (random & 0x3) | 0x8;
125
- return value.toString(16);
126
- });
127
- }
128
- // ==================== Booleanos ====================
129
- /**
130
- * Gera um valor booleano aleatório (true ou false).
131
- * @returns true ou false aleatoriamente
132
- * @example
133
- * Random.boolean() // pode retornar true ou false
134
- */
135
- static boolean() {
136
- return Math.random() < 0.5;
137
- }
138
- /**
139
- * Gera um valor booleano aleatório com uma probabilidade específica de ser true.
140
- * @param probability - Probabilidade de retornar true (0 a 1, padrão: 0.5)
141
- * @returns true com a probabilidade fornecida, false caso contrário
142
- * @example
143
- * Random.booleanWithProbability(0.8) // 80% de chance de retornar true
144
- * Random.booleanWithProbability(0.2) // 20% de chance de retornar true
145
- */
146
- static booleanWithProbability(probability = 0.5) {
147
- return Math.random() < probability;
148
- }
149
- // ==================== Arrays ====================
150
- /**
151
- * Retorna um elemento aleatório de um array.
152
- * @template T - Tipo dos elementos do array
153
- * @param array - Array do qual será selecionado um elemento
154
- * @returns Um elemento aleatório do array
155
- * @throws {Error} Se o array estiver vazio
156
- * @example
157
- * Random.arrayElement([1, 2, 3, 4]) // pode retornar 1, 2, 3 ou 4
158
- * Random.arrayElement(["a", "b", "c"]) // pode retornar "a", "b" ou "c"
159
- */
160
- static arrayElement(array) {
161
- if (array.length === 0) {
162
- throw new Error("Cannot get a random element from an empty array.");
163
- }
164
- return array[Math.floor(Math.random() * array.length)];
165
- }
166
- /**
167
- * Retorna um elemento aleatório de um array, excluindo valores específicos.
168
- * @template T - Tipo dos elementos do array
169
- * @param array - Array do qual será selecionado um elemento
170
- * @param excepts - Array de valores que devem ser excluídos da seleção
171
- * @returns Um elemento aleatório do array que não está nos excepts
172
- * @throws {Error} Se não houver elementos válidos após aplicar as exclusões
173
- * @example
174
- * Random.arrayElementExcluding([1, 2, 3, 4], [2, 4]) // pode retornar 1 ou 3
175
- */
176
- static arrayElementExcluding(array, excepts) {
177
- const validElements = array.filter((item) => !excepts.includes(item));
178
- if (validElements.length === 0) {
179
- throw new Error("No valid elements available after excluding 'excepts'.");
180
- }
181
- return Random.arrayElement(validElements);
182
- }
183
- /**
184
- * Retorna múltiplos elementos aleatórios únicos de um array.
185
- * @template T - Tipo dos elementos do array
186
- * @param array - Array do qual serão selecionados os elementos
187
- * @param count - Quantidade de elementos a retornar
188
- * @returns Array com elementos aleatórios únicos
189
- * @throws {Error} Se count for maior que o tamanho do array
190
- * @example
191
- * Random.arrayElements([1, 2, 3, 4, 5], 3) // pode retornar [3, 1, 5]
192
- */
193
- static arrayElements(array, count) {
194
- if (count > array.length) {
195
- throw new Error(`Cannot pick ${count} elements from an array of ${array.length}.`);
196
- }
197
- const shuffled = [...array].sort(() => Math.random() - 0.5);
198
- return shuffled.slice(0, count);
199
- }
200
- /**
201
- * Retorna uma cópia do array com a ordem dos elementos embaralhada.
202
- * @template T - Tipo dos elementos do array
203
- * @param array - Array a ser embaralhado
204
- * @returns Novo array com os mesmos elementos em ordem aleatória
205
- * @example
206
- * Random.shuffle([1, 2, 3, 4]) // pode retornar [3, 1, 4, 2]
207
- */
208
- static shuffle(array) {
209
- const shuffled = [...array];
210
- for (let i = shuffled.length - 1; i > 0; i--) {
211
- const j = Math.floor(Math.random() * (i + 1));
212
- [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
213
- }
214
- return shuffled;
215
- }
216
- // ==================== Datas ====================
217
- /**
218
- * Gera uma data aleatória dentro de um intervalo.
219
- * @param start - Data inicial do intervalo
220
- * @param end - Data final do intervalo
221
- * @returns Data aleatória entre start e end
222
- * @example
223
- * Random.date(new Date("2020-01-01"), new Date("2024-12-31"))
224
- * // pode retornar qualquer data entre 2020 e 2024
225
- */
226
- static date(start, end) {
227
- const startTime = start.getTime();
228
- const endTime = end.getTime();
229
- return new Date(startTime + Math.random() * (endTime - startTime));
230
- }
231
- /**
232
- * Gera uma data aleatória no passado a partir da data atual.
233
- * @param daysAgo - Quantidade máxima de dias no passado (padrão: 365)
234
- * @returns Data aleatória entre daysAgo dias atrás e hoje
235
- * @example
236
- * Random.pastDate() // data aleatória no último ano
237
- * Random.pastDate(30) // data aleatória nos últimos 30 dias
238
- */
239
- static pastDate(daysAgo = 365) {
240
- const now = new Date();
241
- const past = new Date();
242
- past.setDate(past.getDate() - daysAgo);
243
- return Random.date(past, now);
244
- }
245
- /**
246
- * Gera uma data aleatória no futuro a partir da data atual.
247
- * @param daysAhead - Quantidade máxima de dias no futuro (padrão: 365)
248
- * @returns Data aleatória entre hoje e daysAhead dias à frente
249
- * @example
250
- * Random.futureDate() // data aleatória no próximo ano
251
- * Random.futureDate(30) // data aleatória nos próximos 30 dias
252
- */
253
- static futureDate(daysAhead = 365) {
254
- const now = new Date();
255
- const future = new Date();
256
- future.setDate(future.getDate() + daysAhead);
257
- return Random.date(now, future);
258
- }
259
- }
260
- exports.Random = Random;
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GuardianException = void 0;
4
- class GuardianException extends Error {
5
- }
6
- exports.GuardianException = GuardianException;