maskarajs 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,338 @@
1
+ # mask.js
2
+
3
+ Engine de máscaras declarativo para JavaScript — framework-agnostic, zero dependências, ~4kb.
4
+
5
+ ## Sintaxe
6
+
7
+ | Token | Aceita |
8
+ |---|---|
9
+ | `#` | qualquer dígito (0–9) |
10
+ | `@` | qualquer letra (a–z, A–Z, acentuados) |
11
+ | `*` | qualquer caractere |
12
+ | `[texto]` | literal fixo (inserido/removido automaticamente) |
13
+ | `{expr}` | slot livre — testa um char contra a expressão |
14
+
15
+ ### Modificador `{expr}`
16
+
17
+ ```
18
+ {4} → só o char '4'
19
+ {0-4} → intervalo: ch >= '0' && ch <= '4'
20
+ {013} → conjunto: '0', '1' ou '3'
21
+ {[0-9a-f]} → regex: qualquer char hex
22
+ {\d} → regex: qualquer dígito
23
+ {[^aeiou]} → regex: consoante
24
+ ```
25
+
26
+ ## API
27
+
28
+ ```js
29
+ import mask from './mask.js'
30
+
31
+ mask(pattern, value) // aplica máscara → string formatada
32
+ mask.raw(pattern, value) // valor limpo / resultado do transform
33
+ mask.is(pattern, value) // padrão completo? → boolean
34
+ mask.hint(pattern) // placeholder → string
35
+ mask.format(pattern, value) // alias semântico de mask()
36
+ mask.rawLength(pattern, value) // chars de input preenchidos → number
37
+ mask.patternLength(pattern) // tamanho mascarado completo → number
38
+ mask.define(name, definition) // registra máscara nomeada
39
+ mask.undefine(name) // remove do registry
40
+ mask.names() // lista nomes registrados → string[]
41
+ mask.defineSlot(symbol, definition)// cria/sobrescreve token de input
42
+ mask.undefineSlot(symbol) // remove token customizado
43
+ mask.slots() // lista tokens de input disponíveis
44
+ mask.on(input, pattern, options) // vincula a input DOM → cleanup()
45
+ mask.create(presets) // instância isolada com registry próprio
46
+ ```
47
+
48
+ ## Exemplos
49
+
50
+ ```js
51
+ // Padrão único
52
+ mask('###[.]###[.]###[-]##', '12345678909')
53
+ // → '123.456.789-09'
54
+
55
+ // Padrão dinâmico (array) — escolhe pelo tamanho do input
56
+ mask(['[(]##[)] ####[-]####', '[(]##[)] #####[-]####'], '11987654321')
57
+ // → '(11) 98765-4321'
58
+
59
+ // Slot com restrição
60
+ mask('{4}### #### #### ####', '4111111111111111')
61
+ // → '4111 1111 1111 1111' (só aceita Visa — começa com 4)
62
+
63
+ // Slot com regex
64
+ mask('{[0-9a-fA-F]}{[0-9a-fA-F]}{[0-9a-fA-F]}{[0-9a-fA-F]}{[0-9a-fA-F]}{[0-9a-fA-F]}', '1a2b3c')
65
+ // → '1a2b3c'
66
+ ```
67
+
68
+ ### Mais casos comuns
69
+
70
+ ```js
71
+ // CEP
72
+ mask('#####[-]###', '01310930')
73
+ // → '01310-930'
74
+
75
+ // CNPJ
76
+ mask('##[.]###[.]###[/]####[-]##', '11222333000181')
77
+ // → '11.222.333/0001-81'
78
+
79
+ // Cartão Visa
80
+ mask('{4}### #### #### ####', '5111111111111111')
81
+ // → '' (primeiro char não passou)
82
+
83
+ // Hex color com paste sujo
84
+ mask('{[0-9a-fA-F]}{[0-9a-fA-F]}{[0-9a-fA-F]}{[0-9a-fA-F]}{[0-9a-fA-F]}{[0-9a-fA-F]}', '1z2b3c')
85
+ // → '12b3c'
86
+ ```
87
+
88
+ ## mask.define — com transform
89
+
90
+ ```js
91
+ mask.define('date', {
92
+ pattern: '##[/]##[/]####',
93
+ validate: (raw, masked, complete) => {
94
+ if (raw.length < 4) return true
95
+ const month = Number(raw.slice(2, 4))
96
+ return month >= 1 && month <= 12
97
+ },
98
+ transform: (raw, masked, complete) => {
99
+ if (!complete) return null
100
+ const dt = new Date(`${raw.slice(4,8)}-${raw.slice(2,4)}-${raw.slice(0,2)}`)
101
+ return isNaN(dt) ? null : dt
102
+ },
103
+ })
104
+
105
+ mask('date', '01012025') // → '01/01/2025'
106
+ mask.raw('date', '01/01/2025') // → Date(2025-01-01)
107
+ mask.raw('date', '01/01') // → null (incompleto — transform decidiu)
108
+ mask.is('date', '01/01/2025') // → true
109
+ mask.hint('date') // → '00/00/0000'
110
+ mask.rawLength('date', '01/01') // → 4
111
+ mask.patternLength('date') // → 10
112
+ ```
113
+
114
+ ## validate — validação incremental
115
+
116
+ Use `validate` em máscaras nomeadas quando a regra depende do que já foi digitado.
117
+ Isso resolve casos onde a sintaxe caractere a caractere não é suficiente, como mês
118
+ entre `01` e `12`.
119
+
120
+ ```js
121
+ mask.define('month', {
122
+ pattern: '{0-1}#',
123
+ validate: (raw, masked, complete) => {
124
+ if (!complete) return true
125
+ const month = Number(raw)
126
+ return month >= 1 && month <= 12
127
+ },
128
+ })
129
+
130
+ mask('month', '12') // → '12'
131
+ mask('month', '19') // → '1' (o 9 é recusado)
132
+ mask.is('month', '12') // → true
133
+ mask.is('month', '19') // → false
134
+ ```
135
+
136
+ ## Slots customizados — sua própria linguagem de pattern
137
+
138
+ Além de `#`, `@`, `*` e `{expr}`, você pode criar símbolos que façam sentido
139
+ para o seu time. Isso ajuda quando o projeto quer uma linguagem mais expressiva,
140
+ mais curta ou alinhada ao domínio do produto.
141
+
142
+ ```js
143
+ mask.defineSlot('N', {
144
+ test: ch => /\d/.test(ch),
145
+ hint: '0',
146
+ })
147
+
148
+ mask('NNN[-]NN', '12345') // → '123-45'
149
+ mask.hint('NNN[-]NN') // → '000-00'
150
+ mask.slots() // → ['#', '@', '*', 'N']
151
+ ```
152
+
153
+ Você também pode passar uma `RegExp` direta ou apenas uma função:
154
+
155
+ ```js
156
+ mask.defineSlot('H', /[0-9a-f]/i)
157
+ mask.defineSlot('V', ch => 'AEIOUaeiou'.includes(ch))
158
+
159
+ mask('HHHHHH', '1a2b3c') // → '1a2b3c'
160
+ mask('VVV', 'mask') // → 'a'
161
+ ```
162
+
163
+ O registro global afeta o engine global. Para bibliotecas, design systems ou
164
+ produtos com regras próprias, prefira uma instância isolada:
165
+
166
+ ```js
167
+ const forge = mask.create()
168
+
169
+ forge.defineSlot('N', { test: ch => /\d/.test(ch), hint: '0' })
170
+ forge.defineSlot('#', { test: ch => /[1-9]/.test(ch), hint: '1' })
171
+
172
+ forge('NNN[-]NN', '12345') // → '123-45'
173
+ forge('#', '0') // → '' (# foi sobrescrito nesta instância)
174
+ mask('#', '0') // → '0' (global continua igual)
175
+ ```
176
+
177
+ Se um símbolo registrado precisar aparecer como texto fixo, escape com
178
+ colchetes:
179
+
180
+ ```js
181
+ mask.defineSlot('N', /\d/)
182
+
183
+ mask('[N]##', '45') // → 'N45'
184
+ mask('N##', '145') // → '145'
185
+ ```
186
+
187
+ ## mask.on — qualquer framework
188
+
189
+ ```js
190
+ // Vanilla JS
191
+ const off = mask.on(inputEl, 'cpf', {
192
+ onValue: raw => setState(raw),
193
+ onMasked: masked => setLabel(masked),
194
+ })
195
+ off() // remove listeners
196
+
197
+ // React
198
+ useEffect(() => {
199
+ return mask.on(ref.current, 'date', {
200
+ onValue: (date) => setValue(date), // Date | null
201
+ })
202
+ }, [])
203
+
204
+ // Vue
205
+ onMounted(() => {
206
+ mask.on(inputRef.value, 'phone', {
207
+ onValue: v => emit('update:modelValue', v),
208
+ })
209
+ })
210
+
211
+ // Svelte action
212
+ function maskAction(node, pattern) {
213
+ const off = mask.on(node, pattern)
214
+ return { destroy: off }
215
+ }
216
+ ```
217
+
218
+ ## mask.create — instâncias isoladas
219
+
220
+ ```js
221
+ export const maskBR = mask.create({
222
+ cpf: { pattern: '###[.]###[.]###[-]##' },
223
+ cnpj: { pattern: '##[.]###[.]###[/]####[-]##' },
224
+ phone: { pattern: ['[(]##[)] ####[-]####', '[(]##[)] #####[-]####'] },
225
+ cep: { pattern: '#####[-]###', transform: (r, m, c) => c ? r : null },
226
+ date: {
227
+ pattern: '##[/]##[/]####',
228
+ transform: (raw, masked, complete) => {
229
+ if (!complete) return null
230
+ const dt = new Date(`${raw.slice(4,8)}-${raw.slice(2,4)}-${raw.slice(0,2)}`)
231
+ return isNaN(dt) ? null : dt
232
+ },
233
+ },
234
+ money: {
235
+ pattern: '########[,]##',
236
+ transform: raw => parseInt(raw || '0', 10) / 100,
237
+ },
238
+ })
239
+
240
+ export const maskUS = mask.create({
241
+ ssn: { pattern: '###[-]##[-]####' },
242
+ zip: { pattern: '#####[-]####' },
243
+ phone: { pattern: '[(]###[)] ###[-]####' },
244
+ })
245
+
246
+ // Mesma API, registries isolados — alterações em maskBR não afetam maskUS
247
+ maskBR('cpf', '12345678909') // → '123.456.789-09'
248
+ maskBR.raw('date', '01/01/2025') // → Date
249
+ maskBR.names() // → ['cpf', 'cnpj', 'phone', 'cep', 'date', 'money']
250
+ maskUS.names() // → ['ssn', 'zip', 'phone']
251
+ ```
252
+
253
+ ## rawLength e patternLength
254
+
255
+ ```js
256
+ const filled = mask.rawLength('cpf', value) // chars preenchidos (sem literais)
257
+ const total = mask.patternLength('cpf') // tamanho total mascarado
258
+
259
+ const pct = mask('cpf', value).length / total * 100
260
+ const ready = mask.is('cpf', value) // habilita submit
261
+ const label = `${filled} raw chars` // "7 raw chars"
262
+ ```
263
+
264
+ `patternLength` conta o tamanho final mascarado, incluindo literais. Exemplos:
265
+
266
+ ```js
267
+ mask.patternLength('##[/]##[/]####') // → 10
268
+ mask.patternLength('###[.]###[.]###[-]##') // → 14
269
+ mask.patternLength('{4}### #### #### ####') // → 19
270
+ ```
271
+
272
+ ## Showcase visual
273
+
274
+ O projeto `maskforge-showcase` demonstra a lib com:
275
+
276
+ - playground destacado com máscara aplicada enquanto o usuário digita;
277
+ - visualização do pattern em blocos: slot, literal e expressão;
278
+ - exemplos para React, Vue e Vanilla;
279
+ - receitas interativas para `validate`, `define` e `create`;
280
+ - análise de benchmark local.
281
+
282
+ ```bash
283
+ cd maskforge-showcase
284
+ npm install
285
+ npm run dev
286
+ ```
287
+
288
+ ## Benchmark local
289
+
290
+ Benchmark simples rodado em Node/WSL com 200.000 iterações por caso após warmup.
291
+ Os valores variam por máquina, mas ajudam a orientar expectativas de uso em input.
292
+
293
+ | Caso | Resultado |
294
+ |---|---:|
295
+ | CPF format | 39.705 ops/s |
296
+ | Phone dynamic | 32.455 ops/s |
297
+ | Date validate | 64.572 ops/s |
298
+ | Raw extraction | 44.729 ops/s |
299
+
300
+ ```js
301
+ const iterations = 200000
302
+ for (let i = 0; i < iterations; i++) {
303
+ mask('###[.]###[.]###[-]##', '12345678909')
304
+ }
305
+ ```
306
+
307
+ ## transform — contrato
308
+
309
+ ```js
310
+ // transform(raw, masked, complete) => T
311
+ // validate(raw, masked, complete) => boolean
312
+ //
313
+ // raw → string com os chars de input sem literais
314
+ // masked → string formatada com a máscara
315
+ // complete → true quando todos os slots estão preenchidos
316
+ //
317
+ // Sem transform → mask.raw() retorna string crua, sempre
318
+ // Com transform → mask.raw() retorna o que transform devolver, sempre
319
+ // O transform decide o que fazer com input parcial
320
+
321
+ mask.define('money', {
322
+ pattern: '########[,]##',
323
+ transform: raw => parseInt(raw || '0', 10) / 100,
324
+ // retorna number sempre — mesmo parcial
325
+ })
326
+
327
+ mask.define('date', {
328
+ pattern: '##[/]##[/]####',
329
+ transform: (raw, masked, complete) => {
330
+ if (!complete) return null // null enquanto incompleto
331
+ return new Date(...) // Date quando completo
332
+ },
333
+ })
334
+ ```
335
+
336
+ ## Licença
337
+
338
+ MIT