@erikbernardo/white-label-icons 1.0.0 → 1.0.2

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 (3) hide show
  1. package/README.md +99 -33
  2. package/bin/cli.js +509 -93
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -2,74 +2,140 @@
2
2
 
3
3
  Biblioteca de ícones moderna, ultraleve, **100% White-Label** e agnóstica a frameworks.
4
4
 
5
- Permite que **qualquer empresa ou projeto** utilize sua própria identidade de tags (`<empresa-icone>` ou `<meuapp-icon>`), classes CSS (`<i class="empresa-bx-user"></i>`) e diretórios de assets com zero acoplamento de marca e máxima performance com carregamento sob demanda (Lazy Loading e In-Memory Caching).
5
+ Permite que **qualquer empresa ou projeto** utilize sua própria identidade de tags (`<empresa-icone>` ou `<meuapp-icon>`), classes CSS (`<i class="empresa-bx-user"></i>`) e rotas de assets com zero acoplamento de marca e máxima performance com carregamento sob demanda (Lazy Loading e In-Memory Caching).
6
+
7
+ 🌐 **Demonstração & Catálogo Oficial**: [https://erikbernard.github.io/white-label-icons/](https://erikbernard.github.io/white-label-icons/)
6
8
 
7
9
  ---
8
10
 
9
11
  ## ⚡ Início Rápido com CLI (Recomendado)
10
12
 
11
- O pacote inclui uma ferramenta CLI para configurar seu projeto em segundos (copiando os SVGs para a pasta de assets do seu projeto e gerando o arquivo de inicialização).
13
+ O pacote inclui uma ferramenta CLI que configura seu projeto em segundos. Para projetos Angular, o CLI **configura automaticamente o `angular.json`** para servir os SVGs direto do `node_modules` (sem poluir seu repositório Git com 7.000 arquivos).
14
+
15
+ ### 🌟 Como rodar o setup:
16
+
17
+ Execute no terminal da raiz do seu projeto:
12
18
 
13
- ### Modo Interativo (Perguntas no Terminal)
14
19
  ```bash
15
20
  npx @erikbernardo/white-label-icons init
16
21
  # ou
17
22
  npx wl-icons init
18
23
  ```
19
24
 
20
- ### Modo Direto (com Flags)
25
+ O CLI detecta automaticamente o ambiente do projeto ou exibe o menu interativo:
26
+
27
+ ```text
28
+ 1. Selecione o ambiente / framework do projeto:
29
+ [1] Angular 8 a 18 (NgModules / AppModule clássico)
30
+ [2] Angular 19 / 20+ (Standalone APIs / app.config.ts)
31
+ [3] React / Next.js / Vite
32
+ [4] Vue 2 / Vue 3 / Nuxt
33
+ [5] JavaScript Puro / Vanilla HTML
34
+ ```
35
+
36
+ ---
37
+
38
+ ### ⚡ Modo Direto (com Flags)
39
+
40
+ Você também pode rodar diretamente especificando o framework e prefixos sem perguntas interativas:
41
+
21
42
  ```bash
22
- npx wl-icons init --prefix=empresa --tag=empresa-icone --assets=src/assets/icones -y
43
+ # Angular 19 / 20+ (Standalone)
44
+ npx wl-icons init -f angular --prefix=minhaempresa -y
45
+
46
+ # React / Next.js / Vite
47
+ npx wl-icons init -f react --prefix=app -y
48
+
49
+ # Angular 8 a 18 (NgModule)
50
+ npx wl-icons init -f angular-legacy --prefix=empresa -y
51
+
52
+ # Vue 2 / Vue 3
53
+ npx wl-icons init -f vue --prefix=meuapp -y
23
54
  ```
24
55
 
25
- #### Opções do CLI:
26
- | Flag | Descrição | Padrão |
56
+ #### Opções e Flags do CLI:
57
+ | Flag | Descrição | Opções / Padrão |
27
58
  | :--- | :--- | :--- |
59
+ | `-f, --framework <tipo>` | Framework do seu projeto | `angular-legacy` (8-18), `angular` (19/20+), `react`, `vue`, `vanilla` |
28
60
  | `-p, --prefix <valor>` | Prefixo das classes CSS (`<i class="{prefix}-user">`) | `wl` |
29
61
  | `-t, --tag <valor>` | Nome da tag Web Component | `{prefix}-icone` |
30
- | `-a, --assets <pasta>` | Pasta onde os SVGs serão copiados | `src/assets/icones` |
31
- | `-i, --init-file <caminho>` | Arquivo de inicialização gerado | `src/icons-init.ts` |
32
- | `-y, --yes` | Pular perguntas e usar padrões/flags | `false` |
62
+ | `-b, --base-path <url>` | Rota pública base dos ícones (URL) | `/assets/icones/` (Angular) ou `/icones/` |
63
+ | `-i, --init-file <caminho>` | Arquivo customizado gerado para o framework | Auto-detectado por framework |
64
+ | `-y, --yes` | Pular perguntas e usar detecção automática | `false` |
65
+ | `--copy-svgs` | Forçar cópia de SVGs para disco (desnecessário no Angular) | `false` |
33
66
 
34
67
  ---
35
68
 
36
- ## 📦 Instalação Manual via NPM
69
+ ## 📦 Instalação Manual no Angular (Sem CLI)
70
+
71
+ Se preferir configurar manualmente sem o CLI:
37
72
 
73
+ ### 1. Instalar o pacote
38
74
  ```bash
39
75
  npm install @erikbernardo/white-label-icons
40
76
  ```
41
77
 
78
+ ### 2. Configurar o `angular.json`
79
+ No seu `angular.json`, dentro de `projects > [seu-projeto] > architect > build > options > assets`, adicione a regra de mapeamento:
80
+
81
+ ```json
82
+ "assets": [
83
+ "src/favicon.ico",
84
+ "src/assets",
85
+ {
86
+ "glob": "**/*.svg",
87
+ "input": "node_modules/@erikbernard/white-label-icons/icones",
88
+ "output": "/assets/icones/"
89
+ }
90
+ ]
91
+ ```
92
+ *(Repita também dentro de `architect > test > options > assets` caso queira suporte nos testes unitários).*
93
+
42
94
  ---
43
95
 
44
- ## 🚀 Como Usar no seu Framework
96
+ ## 🚀 Integração por Framework
45
97
 
46
- ### 1. Angular (Versões 8 a 20+)
98
+ ### 1. Angular 19 e 20+ (Standalone APIs / `app.config.ts`)
47
99
 
48
- #### Passo 1: Inicialização
49
- No seu `src/main.ts` (ou `app.config.ts`):
100
+ O CLI gera automaticamente o `src/app/icons.config.ts`. Adicione o provider no seu `src/app/app.config.ts`:
50
101
 
51
102
  ```typescript
52
- import { configureIcons } from '@erikbernardo/white-label-icons';
103
+ import { ApplicationConfig } from '@angular/core';
104
+ import { provideWhiteLabelIcons } from './icons.config';
105
+
106
+ export const appConfig: ApplicationConfig = {
107
+ providers: [
108
+ provideWhiteLabelIcons()
109
+ ]
110
+ };
111
+ ```
53
112
 
54
- configureIcons({
55
- prefix: 'empresa', // Classes: <i class="empresa-bx-user">
56
- tagName: 'empresa-icone', // Tag: <empresa-icone nome="bx-user">
57
- basePath: '/assets/icones/', // Caminho onde os SVGs foram colocados
58
- autoReplace: true // Converte automaticamente tags <i> no DOM
59
- });
113
+ No template HTML dos seus componentes:
114
+ ```html
115
+ <empresa-icone nome="bx-user" tamanho="24" cor="#3b82f6"></empresa-icone>
116
+ <i class="empresa-bx-user"></i>
117
+ ```
118
+
119
+ ---
120
+
121
+ ### 2. Angular 8 a 18 (NgModules / `AppModule` Clássico)
122
+
123
+ O CLI gera o `src/app/icons.module.ts` já com `CUSTOM_ELEMENTS_SCHEMA` e inicialização no boot. Basta importar no seu `src/app/app.module.ts`:
124
+
125
+ ```typescript
126
+ import { NgModule } from '@angular/core';
127
+ import { IconsModule } from './icons.module';
128
+
129
+ @NgModule({
130
+ imports: [
131
+ IconsModule,
132
+ // ...
133
+ ]
134
+ })
135
+ export class AppModule {}
60
136
  ```
61
137
 
62
- > **Dica Angular**: Adicione `CUSTOM_ELEMENTS_SCHEMA` no seu `AppModule` ou `@Component` se estiver usando a sintaxe de Custom Element (`<empresa-icone>`):
63
- > ```typescript
64
- > import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
65
- >
66
- > @NgModule({
67
- > schemas: [CUSTOM_ELEMENTS_SCHEMA]
68
- > })
69
- > export class AppModule {}
70
- > ```
71
-
72
- #### Passo 2: Utilização nos Templates HTML
138
+ #### Utilização nos Templates HTML:
73
139
 
74
140
  ```html
75
141
  <!-- Opção A: Via Custom Element Nativo -->
package/bin/cli.js CHANGED
@@ -20,39 +20,66 @@ const c = {
20
20
  blue: '\x1b[34m',
21
21
  magenta: '\x1b[35m',
22
22
  red: '\x1b[31m',
23
+ gray: '\x1b[90m',
23
24
  };
24
25
 
26
+ function getPackageInfo() {
27
+ try {
28
+ const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
29
+ return {
30
+ name: pkg.name || '@erikbernardo/white-label-icons',
31
+ version: pkg.version || '1.0.0',
32
+ };
33
+ } catch {
34
+ return {
35
+ name: '@erikbernardo/white-label-icons',
36
+ version: '1.0.0',
37
+ };
38
+ }
39
+ }
40
+
41
+ const { name: PACKAGE_NAME, version: PACKAGE_VERSION } = getPackageInfo();
42
+
25
43
  function printBanner() {
26
44
  console.log(`\n${c.cyan}${c.bright}======================================================${c.reset}`);
27
- console.log(`${c.magenta}${c.bright} 🎨 White-Label Icons CLI (@erikbernardo/white-label-icons) ${c.reset}`);
45
+ console.log(`${c.magenta}${c.bright} 🎨 White-Label Icons CLI (${PACKAGE_NAME}) ${c.reset}`);
28
46
  console.log(`${c.cyan}${c.bright}======================================================${c.reset}\n`);
29
47
  }
30
48
 
31
49
  function printHelp() {
32
50
  printBanner();
33
51
  console.log(`Uso:
34
- ${c.green}npx @erikbernardo/white-label-icons init${c.reset} [opções]
52
+ ${c.green}npx ${PACKAGE_NAME} init${c.reset} [opções]
35
53
  ${c.green}npx wl-icons init${c.reset} [opções]
36
54
 
37
55
  Opções:
38
- ${c.yellow}-p, --prefix <valor>${c.reset} Prefixo das classes CSS (ex: 'empresa' para <i class="empresa-bx-user">)
39
- ${c.yellow}-t, --tag <valor>${c.reset} Nome da tag Web Component (ex: 'empresa-icone' ou 'empresa-icon')
40
- ${c.yellow}-a, --assets <pasta>${c.reset} Caminho de destino para os arquivos SVG (padrão: 'src/assets/icones')
41
- ${c.yellow}-i, --init-file <caminho>${c.reset} Arquivo de inicialização a ser gerado (padrão: 'src/icons-init.ts')
42
- ${c.yellow}-y, --yes${c.reset} Aceitar todos os padrões sem perguntas interativas
43
- ${c.yellow}-h, --help${c.reset} Exibir esta ajuda
44
- ${c.yellow}-v, --version${c.reset} Exibir a versão instalada
56
+ ${c.yellow}-f, --framework <tipo>${c.reset} Ambiente do projeto:
57
+ ${c.bright}angular-legacy${c.reset} (Angular 8 a 18 - NgModule)
58
+ ${c.bright}angular${c.reset} (Angular 19/20+ - Standalone)
59
+ ${c.bright}react${c.reset} (React / Next.js / Vite)
60
+ ${c.bright}vue${c.reset} (Vue 2 / Vue 3 / Nuxt)
61
+ ${c.bright}vanilla${c.reset} (JavaScript Puro / HTML)
62
+ ${c.yellow}-p, --prefix <valor>${c.reset} Prefixo das classes CSS (ex: 'empresa' para <i class="empresa-bx-user">)
63
+ ${c.yellow}-t, --tag <valor>${c.reset} Nome da tag Web Component (ex: 'empresa-icone' ou 'empresa-icon')
64
+ ${c.yellow}-b, --base-path <url>${c.reset} Caminho público dos ícones (padrão: '/assets/icones/')
65
+ ${c.yellow}-i, --init-file <caminho>${c.reset}Arquivo gerado de configuração para o framework
66
+ ${c.yellow}-y, --yes${c.reset} Aceitar todos os padrões detectados sem perguntas interativas
67
+ ${c.yellow}--copy-svgs${c.reset} Forçar a cópia física dos arquivos SVG (não necessário para Angular)
68
+ ${c.yellow}-h, --help${c.reset} Exibir esta ajuda
69
+ ${c.yellow}-v, --version${c.reset} Exibir a versão instalada
45
70
  `);
46
71
  }
47
72
 
48
73
  function parseArgs(args) {
49
74
  const parsed = {
50
75
  command: 'init',
76
+ framework: '',
51
77
  prefix: '',
52
78
  tag: '',
53
- assets: '',
79
+ basePath: '',
54
80
  initFile: '',
55
81
  yes: false,
82
+ copySvgs: false,
56
83
  help: false,
57
84
  version: false,
58
85
  };
@@ -67,6 +94,12 @@ function parseArgs(args) {
67
94
  parsed.version = true;
68
95
  } else if (arg === '-y' || arg === '--yes') {
69
96
  parsed.yes = true;
97
+ } else if (arg === '--copy-svgs') {
98
+ parsed.copySvgs = true;
99
+ } else if (arg.startsWith('--framework=')) {
100
+ parsed.framework = arg.split('=')[1];
101
+ } else if (arg === '-f' && args[i + 1]) {
102
+ parsed.framework = args[++i];
70
103
  } else if (arg.startsWith('--prefix=')) {
71
104
  parsed.prefix = arg.split('=')[1];
72
105
  } else if (arg === '-p' && args[i + 1]) {
@@ -75,10 +108,10 @@ function parseArgs(args) {
75
108
  parsed.tag = arg.split('=')[1];
76
109
  } else if (arg === '-t' && args[i + 1]) {
77
110
  parsed.tag = args[++i];
78
- } else if (arg.startsWith('--assets=')) {
79
- parsed.assets = arg.split('=')[1];
80
- } else if (arg === '-a' && args[i + 1]) {
81
- parsed.assets = args[++i];
111
+ } else if (arg.startsWith('--base-path=') || arg.startsWith('--assets=')) {
112
+ parsed.basePath = arg.split('=')[1];
113
+ } else if ((arg === '-b' || arg === '-a') && args[i + 1]) {
114
+ parsed.basePath = args[++i];
82
115
  } else if (arg.startsWith('--init-file=')) {
83
116
  parsed.initFile = arg.split('=')[1];
84
117
  } else if (arg === '-i' && args[i + 1]) {
@@ -126,21 +159,364 @@ function copyDirectoryRecursive(src, dest) {
126
159
  return count;
127
160
  }
128
161
 
129
- function getPackageVersion() {
162
+ /**
163
+ * Detecta o ambiente do projeto no diretório atual.
164
+ */
165
+ function detectEnvironment() {
166
+ const cwd = process.cwd();
167
+ let pkg = {};
130
168
  try {
131
- const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
132
- return pkg.version || '1.0.0';
133
- } catch {
134
- return '1.0.0';
169
+ const pkgPath = path.join(cwd, 'package.json');
170
+ if (fs.existsSync(pkgPath)) {
171
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
172
+ }
173
+ } catch {}
174
+
175
+ const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
176
+
177
+ // Angular
178
+ if (fs.existsSync(path.join(cwd, 'angular.json')) || deps['@angular/core']) {
179
+ if (fs.existsSync(path.join(cwd, 'src/app/app.config.ts')) || (deps['@angular/core'] && deps['@angular/core'].match(/(\^|~)?(19|20|[2-9][0-9])/))) {
180
+ return 'angular'; // Standalone
181
+ }
182
+ return 'angular-legacy'; // NgModule (Angular 8-18)
183
+ }
184
+
185
+ // React
186
+ if (deps['react'] || deps['next'] || fs.existsSync(path.join(cwd, 'next.config.js')) || fs.existsSync(path.join(cwd, 'next.config.mjs'))) {
187
+ return 'react';
188
+ }
189
+
190
+ // Vue
191
+ if (deps['vue'] || deps['nuxt'] || fs.existsSync(path.join(cwd, 'nuxt.config.ts'))) {
192
+ return 'vue';
193
+ }
194
+
195
+ return 'vanilla';
196
+ }
197
+
198
+ function normalizeFramework(fw) {
199
+ if (!fw) return '';
200
+ const val = fw.toLowerCase().trim();
201
+ if (val === '1' || val === 'angular-legacy' || val === 'angular8' || val === 'angular-8' || val === 'angular-18' || val === 'ngmodule') {
202
+ return 'angular-legacy';
203
+ }
204
+ if (val === '2' || val === 'angular' || val === 'angular-standalone' || val === 'angular19' || val === 'angular20' || val === 'angular-19' || val === 'angular-20') {
205
+ return 'angular';
206
+ }
207
+ if (val === '3' || val === 'react' || val === 'next' || val === 'nextjs') {
208
+ return 'react';
209
+ }
210
+ if (val === '4' || val === 'vue' || val === 'vue3' || val === 'vue2' || val === 'nuxt') {
211
+ return 'vue';
212
+ }
213
+ if (val === '5' || val === 'vanilla' || val === 'js' || val === 'html') {
214
+ return 'vanilla';
215
+ }
216
+ return 'vanilla';
217
+ }
218
+
219
+ function getFrameworkLabel(fw) {
220
+ switch (fw) {
221
+ case 'angular-legacy': return 'Angular 8 a 18 (NgModules / AppModule)';
222
+ case 'angular': return 'Angular 19 / 20+ (Standalone APIs / app.config.ts)';
223
+ case 'react': return 'React / Next.js / Vite';
224
+ case 'vue': return 'Vue 2 / Vue 3 / Nuxt';
225
+ default: return 'JavaScript Puro / Vanilla HTML';
226
+ }
227
+ }
228
+
229
+ function getDefaultPathsForFramework(fw, isTs) {
230
+ let defaultBasePath = '/assets/icones/';
231
+ let defaultInitFile = isTs ? 'src/icons-init.ts' : 'src/icons-init.js';
232
+
233
+ switch (fw) {
234
+ case 'angular-legacy':
235
+ defaultBasePath = '/assets/icones/';
236
+ defaultInitFile = isTs ? 'src/app/icons.module.ts' : 'src/app/icons.module.js';
237
+ break;
238
+
239
+ case 'angular':
240
+ defaultBasePath = '/assets/icones/';
241
+ defaultInitFile = 'src/app/icons.config.ts';
242
+ break;
243
+
244
+ case 'react':
245
+ defaultBasePath = '/icones/';
246
+ defaultInitFile = isTs ? 'src/icons.tsx' : 'src/icons.jsx';
247
+ break;
248
+
249
+ case 'vue':
250
+ defaultBasePath = '/icones/';
251
+ defaultInitFile = isTs ? 'src/plugins/icons.ts' : 'src/plugins/icons.js';
252
+ break;
253
+
254
+ default: // vanilla
255
+ defaultBasePath = './icones/';
256
+ defaultInitFile = isTs ? 'src/icons-init.ts' : 'icons-init.js';
257
+ break;
258
+ }
259
+
260
+ return { defaultBasePath, defaultInitFile };
261
+ }
262
+
263
+ /**
264
+ * Atualiza o angular.json automaticamente para mapear os SVGs do node_modules
265
+ */
266
+ function configureAngularJson(basePath) {
267
+ const angularJsonPath = path.resolve(process.cwd(), 'angular.json');
268
+
269
+ if (!fs.existsSync(angularJsonPath)) {
270
+ return { success: false, reason: 'angular.json não encontrado' };
271
+ }
272
+
273
+ try {
274
+ const rawContent = fs.readFileSync(angularJsonPath, 'utf8');
275
+ const angularJson = JSON.parse(rawContent);
276
+ const projects = angularJson.projects || {};
277
+ let modified = false;
278
+
279
+ // Normaliza o caminho de saída (ex: '/assets/icones/' -> '/assets/icones/')
280
+ let outputDir = basePath;
281
+ if (!outputDir.startsWith('/')) outputDir = '/' + outputDir;
282
+ if (!outputDir.endsWith('/')) outputDir += '/';
283
+
284
+ const assetEntry = {
285
+ glob: '**/*.svg',
286
+ input: `node_modules/${PACKAGE_NAME}/icones`,
287
+ output: outputDir,
288
+ };
289
+
290
+ for (const [projectName, projectConfig] of Object.entries(projects)) {
291
+ const architect = projectConfig.architect || projectConfig.targets || {};
292
+
293
+ // 1. Configura no target "build"
294
+ if (architect.build && architect.build.options) {
295
+ if (!Array.isArray(architect.build.options.assets)) {
296
+ architect.build.options.assets = [];
297
+ }
298
+ const assets = architect.build.options.assets;
299
+ const exists = assets.some(
300
+ (a) => typeof a === 'object' && a.input && (a.input.includes(PACKAGE_NAME) || a.input.includes('white-label-icons') || a.input.includes('gt-controller-icones'))
301
+ );
302
+
303
+ if (!exists) {
304
+ assets.push(assetEntry);
305
+ modified = true;
306
+ }
307
+ }
308
+
309
+ // 2. Configura no target "test"
310
+ if (architect.test && architect.test.options) {
311
+ if (!Array.isArray(architect.test.options.assets)) {
312
+ architect.test.options.assets = [];
313
+ }
314
+ const assets = architect.test.options.assets;
315
+ const exists = assets.some(
316
+ (a) => typeof a === 'object' && a.input && (a.input.includes(PACKAGE_NAME) || a.input.includes('white-label-icons') || a.input.includes('gt-controller-icones'))
317
+ );
318
+
319
+ if (!exists) {
320
+ assets.push(assetEntry);
321
+ modified = true;
322
+ }
323
+ }
324
+ }
325
+
326
+ if (modified) {
327
+ fs.writeFileSync(angularJsonPath, JSON.stringify(angularJson, null, 2), 'utf8');
328
+ return { success: true, modified: true };
329
+ }
330
+
331
+ return { success: true, modified: false };
332
+ } catch (err) {
333
+ return { success: false, reason: err.message };
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Gera o código do arquivo de inicialização de acordo com o framework escolhido.
339
+ */
340
+ function generateInitFileContent(framework, prefix, tag, webBasePath, isTs) {
341
+ switch (framework) {
342
+ case 'angular-legacy':
343
+ return `/**
344
+ * Módulo de Ícones White-Label para Angular 8 a 18 (NgModule)
345
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
346
+ */
347
+ import { NgModule, CUSTOM_ELEMENTS_SCHEMA, APP_INITIALIZER } from '@angular/core';
348
+ import { configureIcons } from '${PACKAGE_NAME}';
349
+
350
+ export function initializeWhiteLabelIcons() {
351
+ return () => {
352
+ configureIcons({
353
+ prefix: '${prefix}',
354
+ tagName: '${tag}',
355
+ basePath: '${webBasePath}',
356
+ autoReplace: true,
357
+ });
358
+ };
359
+ }
360
+
361
+ @NgModule({
362
+ schemas: [CUSTOM_ELEMENTS_SCHEMA],
363
+ providers: [
364
+ {
365
+ provide: APP_INITIALIZER,
366
+ useFactory: initializeWhiteLabelIcons,
367
+ multi: true,
368
+ },
369
+ ],
370
+ })
371
+ export class IconsModule {}
372
+ `;
373
+
374
+ case 'angular':
375
+ return `/**
376
+ * Provider de Ícones White-Label para Angular 19 e 20+ (Standalone APIs)
377
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
378
+ */
379
+ import { EnvironmentProviders, makeEnvironmentProviders, ENVIRONMENT_INITIALIZER, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
380
+ import { configureIcons, IconOptions } from '${PACKAGE_NAME}';
381
+
382
+ /**
383
+ * Adicione este provider no seu app.config.ts:
384
+ * export const appConfig: ApplicationConfig = {
385
+ * providers: [provideWhiteLabelIcons(), ...]
386
+ * };
387
+ */
388
+ export function provideWhiteLabelIcons(options?: Partial<IconOptions>): EnvironmentProviders {
389
+ return makeEnvironmentProviders([
390
+ {
391
+ provide: ENVIRONMENT_INITIALIZER,
392
+ useValue: () => {
393
+ configureIcons({
394
+ prefix: '${prefix}',
395
+ tagName: '${tag}',
396
+ basePath: '${webBasePath}',
397
+ autoReplace: true,
398
+ ...options,
399
+ });
400
+ },
401
+ multi: true,
402
+ },
403
+ ]);
404
+ }
405
+
406
+ // Schemas para componentes standalone que usam a tag <${tag}>
407
+ export const ICONS_SCHEMAS = [CUSTOM_ELEMENTS_SCHEMA];
408
+ `;
409
+
410
+ case 'react':
411
+ return `/**
412
+ * Wrapper de Ícones White-Label para React / Next.js
413
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
414
+ */
415
+ import React from 'react';
416
+ import { configureIcons } from '${PACKAGE_NAME}';
417
+
418
+ // Inicializa no cliente
419
+ export function initIcons(): void {
420
+ configureIcons({
421
+ prefix: '${prefix}',
422
+ tagName: '${tag}',
423
+ basePath: '${webBasePath}',
424
+ autoReplace: true,
425
+ });
426
+ }
427
+
428
+ if (typeof window !== 'undefined') {
429
+ initIcons();
430
+ }
431
+
432
+ export interface IconProps extends React.HTMLAttributes<HTMLElement> {
433
+ name: string;
434
+ size?: number | string;
435
+ color?: string;
436
+ rotate?: number | string;
437
+ flip?: 'horizontal' | 'vertical' | 'ambos';
438
+ }
439
+
440
+ /**
441
+ * Componente React reutilizável para ícones
442
+ * Exemplo: <Icon name="bx-user" size={24} color="#3b82f6" />
443
+ */
444
+ export const Icon: React.FC<IconProps> = ({ name, size, color, rotate, flip, className, ...props }) => {
445
+ return React.createElement('${tag}', {
446
+ nome: name,
447
+ tamanho: size,
448
+ cor: color,
449
+ rotacao: rotate,
450
+ espelhar: flip,
451
+ class: className,
452
+ ...props,
453
+ });
454
+ };
455
+ `;
456
+
457
+ case 'vue':
458
+ return `/**
459
+ * Plugin de Ícones White-Label para Vue 2 / Vue 3
460
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
461
+ */
462
+ import { configureIcons } from '${PACKAGE_NAME}';
463
+
464
+ export const IconsPlugin = {
465
+ install(${isTs ? 'app: any' : 'app'}) {
466
+ configureIcons({
467
+ prefix: '${prefix}',
468
+ tagName: '${tag}',
469
+ basePath: '${webBasePath}',
470
+ autoReplace: true,
471
+ });
472
+ },
473
+ };
474
+
475
+ // Auto-inicializa se estiver no navegador
476
+ if (typeof window !== 'undefined') {
477
+ configureIcons({
478
+ prefix: '${prefix}',
479
+ tagName: '${tag}',
480
+ basePath: '${webBasePath}',
481
+ autoReplace: true,
482
+ });
483
+ }
484
+ `;
485
+
486
+ default: // vanilla
487
+ return `/**
488
+ * Configuração dos Ícones White-Label (JavaScript Puro / HTML)
489
+ * Gerado automaticamente pelo CLI ${PACKAGE_NAME}
490
+ */
491
+ import { configureIcons } from '${PACKAGE_NAME}';
492
+
493
+ export function initAppIcons()${isTs ? ': void' : ''} {
494
+ configureIcons({
495
+ prefix: '${prefix}',
496
+ tagName: '${tag}',
497
+ basePath: '${webBasePath}',
498
+ autoReplace: true,
499
+ });
500
+ }
501
+
502
+ // Inicializa automaticamente no navegador
503
+ if (typeof window !== 'undefined') {
504
+ initAppIcons();
505
+ }
506
+ `;
135
507
  }
136
508
  }
137
509
 
138
510
  async function runInit(options) {
139
511
  printBanner();
140
512
 
513
+ const isTs = fs.existsSync(path.resolve(process.cwd(), 'tsconfig.json'));
514
+ const detectedFw = detectEnvironment();
515
+
516
+ let framework = normalizeFramework(options.framework);
141
517
  let prefix = options.prefix;
142
518
  let tag = options.tag;
143
- let assetsPath = options.assets;
519
+ let basePath = options.basePath;
144
520
  let initFilePath = options.initFile;
145
521
 
146
522
  const isInteractive = !options.yes && process.stdin.isTTY;
@@ -151,94 +527,120 @@ async function runInit(options) {
151
527
  output: process.stdout,
152
528
  });
153
529
 
154
- console.log(`${c.bright}Vamos configurar a biblioteca White-Label para o seu projeto:${c.reset}\n`);
530
+ console.log(`${c.bright}Vamos configurar a biblioteca White-Label de acordo com o seu ambiente:${c.reset}\n`);
531
+
532
+ if (!framework) {
533
+ console.log(`${c.cyan}1. Selecione o ambiente / framework do projeto:${c.reset}`);
534
+ console.log(` ${c.yellow}[1]${c.reset} Angular 8 a 18 (NgModules / AppModule clássico)`);
535
+ console.log(` ${c.yellow}[2]${c.reset} Angular 19 / 20+ (Standalone APIs / app.config.ts)`);
536
+ console.log(` ${c.yellow}[3]${c.reset} React / Next.js / Vite`);
537
+ console.log(` ${c.yellow}[4]${c.reset} Vue 2 / Vue 3 / Nuxt`);
538
+ console.log(` ${c.yellow}[5]${c.reset} JavaScript Puro / Vanilla HTML\n`);
539
+
540
+ const fwChoiceMap = {
541
+ 'angular-legacy': '1',
542
+ 'angular': '2',
543
+ 'react': '3',
544
+ 'vue': '4',
545
+ 'vanilla': '5',
546
+ };
547
+ const defaultChoice = fwChoiceMap[detectedFw] || '1';
548
+
549
+ const answer = await askQuestion(rl, 'Digite o número correspondente', defaultChoice);
550
+ framework = normalizeFramework(answer) || detectedFw;
551
+ }
552
+
553
+ const { defaultBasePath, defaultInitFile } = getDefaultPathsForFramework(framework, isTs);
155
554
 
156
555
  if (!prefix) {
157
- prefix = await askQuestion(rl, '1. Qual prefixo de classe deseja usar para os ícones? (ex: empresa, app, wl)', 'wl');
556
+ prefix = await askQuestion(rl, '2. Qual prefixo de classe deseja usar para os ícones? (ex: empresa, app, wl)', 'wl');
158
557
  }
159
558
 
160
559
  if (!tag) {
161
560
  const defaultTag = `${prefix}-icone`;
162
- tag = await askQuestion(rl, `2. Qual tag Web Component deseja registrar?`, defaultTag);
561
+ tag = await askQuestion(rl, `3. Qual tag Web Component deseja registrar?`, defaultTag);
163
562
  }
164
563
 
165
- if (!assetsPath) {
166
- assetsPath = await askQuestion(rl, '3. Onde deseja copiar os arquivos SVG no seu projeto?', 'src/assets/icones');
564
+ if (!basePath) {
565
+ basePath = await askQuestion(rl, '4. Rota pública base dos ícones (URL):', defaultBasePath);
167
566
  }
168
567
 
169
568
  if (!initFilePath) {
170
- const isTs = fs.existsSync(path.resolve(process.cwd(), 'tsconfig.json'));
171
- const defaultInit = isTs ? 'src/icons-init.ts' : 'src/icons-init.js';
172
- initFilePath = await askQuestion(rl, '4. Caminho para o arquivo de inicialização:', defaultInit);
569
+ initFilePath = await askQuestion(rl, '5. Caminho para o arquivo de inicialização gerado:', defaultInitFile);
173
570
  }
174
571
 
175
572
  rl.close();
176
573
  console.log('');
177
574
  } else {
178
- // Defaults para modo não-interativo ou com flags parciais
575
+ // Modo não interativo
576
+ framework = framework || detectedFw || 'vanilla';
179
577
  prefix = prefix || 'wl';
180
578
  tag = tag || `${prefix}-icone`;
181
- assetsPath = assetsPath || 'src/assets/icones';
182
- if (!initFilePath) {
183
- const isTs = fs.existsSync(path.resolve(process.cwd(), 'tsconfig.json'));
184
- initFilePath = isTs ? 'src/icons-init.ts' : 'src/icons-init.js';
185
- }
579
+ const { defaultBasePath, defaultInitFile } = getDefaultPathsForFramework(framework, isTs);
580
+ basePath = basePath || defaultBasePath;
581
+ initFilePath = initFilePath || defaultInitFile;
186
582
  }
187
583
 
188
584
  // Normalização
189
- prefix = prefix.toLowerCase().replace(/[^a-z0-9_-]/g, '');
585
+ prefix = prefix.toLowerCase().replace(/[^a-z0-9_-]/g, '') || 'wl';
190
586
  if (!tag.includes('-')) {
191
587
  tag = `${tag}-icone`;
192
588
  }
193
589
 
194
- const targetAssetsDir = path.resolve(process.cwd(), assetsPath);
590
+ if (!basePath.startsWith('/') && !basePath.startsWith('./')) {
591
+ basePath = '/' + basePath;
592
+ }
593
+ if (!basePath.endsWith('/')) {
594
+ basePath += '/';
595
+ }
596
+
195
597
  const targetInitFile = path.resolve(process.cwd(), initFilePath);
196
598
 
197
599
  console.log(`${c.cyan}⚙️ Configurações selecionadas:${c.reset}`);
198
- console.log(` • Prefixo CSS: ${c.green}${prefix}${c.reset} (ex: <i class="${prefix}-bx-user"></i>)`);
199
- console.log(` • Tag Web Component: ${c.green}<${tag}>${c.reset} (ex: <${tag} nome="bx-user"></${tag}>)`);
200
- console.log(` • Pasta de SVGs: ${c.green}${assetsPath}${c.reset}`);
201
- console.log(` • Arquivo de Init: ${c.green}${initFilePath}${c.reset}\n`);
202
-
203
- // 1. Cópia de SVGs
204
- console.log(`${c.bright}📦 Copiando ícones SVG para "${assetsPath}"...${c.reset}`);
205
- try {
206
- const copiedCount = copyDirectoryRecursive(SOURCE_ICONS_DIR, targetAssetsDir);
207
- console.log(`${c.green}✔ ${copiedCount} ícones SVG copiados com sucesso!${c.reset}\n`);
208
- } catch (err) {
209
- console.error(`${c.red}❌ Falha ao copiar ícones:${c.reset}`, err.message);
210
- process.exit(1);
600
+ console.log(` • Ambiente / Framework: ${c.green}${getFrameworkLabel(framework)}${c.reset}`);
601
+ console.log(` • Prefixo CSS: ${c.green}${prefix}${c.reset} (ex: <i class="${prefix}-bx-user"></i>)`);
602
+ console.log(` • Tag Web Component: ${c.green}<${tag}>${c.reset} (ex: <${tag} nome="bx-user"></${tag}>)`);
603
+ console.log(` • Rota de Assets (URL): ${c.green}${basePath}${c.reset}`);
604
+ console.log(` • Arquivo de Init: ${c.green}${initFilePath}${c.reset}\n`);
605
+
606
+ // 1. Configuração Automática do angular.json (se for projeto Angular)
607
+ const isAngular = framework === 'angular' || framework === 'angular-legacy';
608
+ if (isAngular) {
609
+ console.log(`${c.bright}⚙️ Configurando mapeamento de assets no "angular.json"...${c.reset}`);
610
+ const ngResult = configureAngularJson(basePath);
611
+ if (ngResult.success) {
612
+ if (ngResult.modified) {
613
+ console.log(`${c.green}✔ "angular.json" atualizado com sucesso! (SVGs serão servidos direto do node_modules sem poluir o Git).${c.reset}\n`);
614
+ } else {
615
+ console.log(`${c.green}✔ "angular.json" já possuía a regra de assets configurada.${c.reset}\n`);
616
+ }
617
+ } else {
618
+ console.warn(`${c.yellow}⚠️ Aviso: Não foi possível atualizar o angular.json automaticamente (${ngResult.reason}).${c.reset}`);
619
+ console.warn(` Certifique-se de adicionar a seguinte regra manualmente em "assets":`);
620
+ console.warn(` {\n "glob": "**/*.svg",\n "input": "node_modules/${PACKAGE_NAME}/icones",\n "output": "${basePath}"\n }\n`);
621
+ }
211
622
  }
212
623
 
213
- // 2. Criação do arquivo de inicialização
214
- console.log(`${c.bright}📝 Gerando arquivo de inicialização em "${initFilePath}"...${c.reset}`);
215
-
216
- // Calcula o basePath web relativo esperado pelo navegador
217
- let webBasePath = assetsPath.replace(/^src\//, '').replace(/^public\//, '');
218
- if (!webBasePath.startsWith('/')) webBasePath = '/' + webBasePath;
219
- if (!webBasePath.endsWith('/')) webBasePath += '/';
220
-
221
- const isTypeScript = initFilePath.endsWith('.ts');
222
- const code = `/**
223
- * Configuração dos Ícones White-Label
224
- * Gerado automaticamente pelo CLI @erikbernardo/white-label-icons
225
- */
226
- import { configureIcons } from '@erikbernardo/white-label-icons';
227
-
228
- export function initAppIcons()${isTypeScript ? ': void' : ''} {
229
- configureIcons({
230
- prefix: '${prefix}',
231
- tagName: '${tag}',
232
- basePath: '${webBasePath}',
233
- autoReplace: true,
234
- });
235
- }
624
+ // 2. Cópia opcional para projetos não-Angular ou com flag --copy-svgs
625
+ if (options.copySvgs || (!isAngular && (framework === 'react' || framework === 'vue' || framework === 'vanilla'))) {
626
+ const publicDir = fs.existsSync(path.join(process.cwd(), 'public'))
627
+ ? path.join(process.cwd(), 'public/icones')
628
+ : path.join(process.cwd(), 'icones');
629
+
630
+ if (options.copySvgs) {
631
+ console.log(`${c.bright}📦 Copiando arquivos SVG para "${publicDir}" (--copy-svgs)...${c.reset}`);
632
+ try {
633
+ const copied = copyDirectoryRecursive(SOURCE_ICONS_DIR, publicDir);
634
+ console.log(`${c.green}✔ ${copied} ícones copiados para "${publicDir}".${c.reset}\n`);
635
+ } catch (err) {
636
+ console.warn(`${c.yellow}⚠️ Não foi possível copiar os ícones: ${err.message}${c.reset}\n`);
637
+ }
638
+ }
639
+ }
236
640
 
237
- // Inicializa automaticamente no navegador
238
- if (typeof window !== 'undefined') {
239
- initAppIcons();
240
- }
241
- `;
641
+ // 3. Criação do arquivo de inicialização específico do framework
642
+ console.log(`${c.bright}📝 Gerando arquivo de inicialização para ${getFrameworkLabel(framework)}...${c.reset}`);
643
+ const code = generateInitFileContent(framework, prefix, tag, basePath, isTs);
242
644
 
243
645
  try {
244
646
  fs.mkdirSync(path.dirname(targetInitFile), { recursive: true });
@@ -248,23 +650,36 @@ if (typeof window !== 'undefined') {
248
650
  console.error(`${c.red}❌ Falha ao criar arquivo de inicialização:${c.reset}`, err.message);
249
651
  }
250
652
 
251
- // 3. Verificação de angular.json
252
- const angularJsonPath = path.resolve(process.cwd(), 'angular.json');
253
- if (fs.existsSync(angularJsonPath)) {
254
- console.log(`${c.magenta}💡 Projeto Angular detectado!${c.reset}`);
255
- console.log(` Certifique-se de que a pasta "${assetsPath}" está incluída em "assets" no seu ${c.yellow}angular.json${c.reset}:`);
256
- console.log(` ${c.bright}"assets": ["src/favicon.ico", "src/assets", "${assetsPath}"]${c.reset}\n`);
653
+ // 4. Instruções Finais
654
+ console.log(`${c.cyan}${c.bright}🚀 Tudo pronto! Como utilizar no seu projeto:${c.reset}\n`);
655
+
656
+ if (framework === 'angular-legacy') {
657
+ console.log(`1. Importe o ${c.yellow}IconsModule${c.reset} no seu ${c.yellow}src/app/app.module.ts${c.reset}:`);
658
+ console.log(` ${c.green}import { IconsModule } from './icons.module';${c.reset}`);
659
+ console.log(` ${c.green}@NgModule({ imports: [IconsModule, ...], ... })${c.reset}\n`);
660
+ } else if (framework === 'angular') {
661
+ console.log(`1. Adicione o provider no seu ${c.yellow}src/app/app.config.ts${c.reset}:`);
662
+ console.log(` ${c.green}import { provideWhiteLabelIcons } from './icons.config';${c.reset}`);
663
+ console.log(` ${c.green}export const appConfig: ApplicationConfig = { providers: [provideWhiteLabelIcons(), ...] };${c.reset}\n`);
664
+ console.log(`2. Em componentes Standalone que usam a tag <${tag}>, inclua o schema:`);
665
+ console.log(` ${c.green}import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';${c.reset}`);
666
+ console.log(` ${c.green}@Component({ schemas: [CUSTOM_ELEMENTS_SCHEMA], ... })${c.reset}\n`);
667
+ } else if (framework === 'react') {
668
+ console.log(`1. Importe o componente no seu JSX/TSX:`);
669
+ console.log(` ${c.green}import { Icon } from './${path.basename(initFilePath, path.extname(initFilePath))}';${c.reset}`);
670
+ console.log(` ${c.green}<Icon name="bx-user" size={24} color="#3b82f6" />${c.reset}\n`);
671
+ } else if (framework === 'vue') {
672
+ console.log(`1. Registre o plugin no seu ${c.yellow}src/main.ts${c.reset} / ${c.yellow}src/main.js${c.reset}:`);
673
+ console.log(` ${c.green}import { IconsPlugin } from './plugins/icons';${c.reset}`);
674
+ console.log(` ${c.green}app.use(IconsPlugin);${c.reset}\n`);
675
+ } else {
676
+ console.log(`1. Importe o arquivo gerado no seu ponto de entrada (ex: ${c.yellow}index.html${c.reset} ou ${c.yellow}main.js${c.reset}):`);
677
+ console.log(` ${c.green}<script type="module" src="./${initFilePath}"></script>${c.reset}\n`);
257
678
  }
258
679
 
259
- // 4. Instruções de Uso
260
- console.log(`${c.cyan}${c.bright}🚀 Pronto! Como utilizar no seu projeto:${c.reset}`);
261
- console.log(`\n1. Importe o arquivo gerado no seu ponto de entrada (ex: ${c.yellow}src/main.ts${c.reset} ou ${c.yellow}src/index.js${c.reset}):`);
262
- console.log(` ${c.green}import './${path.relative(path.dirname(path.resolve(process.cwd(), 'src/main.ts')), targetInitFile).replace(/\\/g, '/').replace(/\.ts$/, '')}';${c.reset}`);
263
-
264
- console.log(`\n2. Use as tags no seu HTML / Templates:`);
265
- console.log(` ${c.green}<${tag} nome="bx-user" tamanho="24" cor="#3b82f6"></${tag}>${c.reset}`);
266
- console.log(` ${c.bright}ou simplesmente via classe CSS:${c.reset}`);
267
- console.log(` ${c.green}<i class="${prefix}-bx-user"></i>${c.reset}\n`);
680
+ console.log(`${c.bright}Uso nos Templates HTML:${c.reset}`);
681
+ console.log(` • Via Custom Element: ${c.green}<${tag} nome="bx-user" tamanho="24" cor="#3b82f6"></${tag}>${c.reset}`);
682
+ console.log(` • Via Classe CSS: ${c.green}<i class="${prefix}-bx-user"></i>${c.reset}\n`);
268
683
  }
269
684
 
270
685
  async function main() {
@@ -272,7 +687,7 @@ async function main() {
272
687
  const options = parseArgs(args);
273
688
 
274
689
  if (options.version) {
275
- console.log(`v${getPackageVersion()}`);
690
+ console.log(`v${PACKAGE_VERSION}`);
276
691
  process.exit(0);
277
692
  }
278
693
 
@@ -288,3 +703,4 @@ main().catch((err) => {
288
703
  console.error(`${c.red}Erro inesperado:${c.reset}`, err);
289
704
  process.exit(1);
290
705
  });
706
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@erikbernardo/white-label-icons",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "Biblioteca de ícones agnóstica de framework e 100% white-label (Angular, React, Vue, Web Components) com suporte a prefixos customizados e CLI de setup.",
5
5
  "type": "module",
6
6
  "main": "./index.js",