@boruto_vk7/stickengine 0.0.3-alpha → 0.0.4

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 CHANGED
@@ -1,135 +1,121 @@
1
- # StickEngine
1
+ # 🚀 StickEngine
2
2
 
3
- [![npm](https://img.shields.io/npm/v/@boruto_vk7/stickengine)](https://www.npmjs.com/package/@boruto_vk7/stickengine)
4
- [![license](https://img.shields.io/npm/l/@boruto_vk7/stickengine)](https://github.com/Borutovk7/StickEngine/blob/main/LICENSE)
3
+ **StickEngine** é um motor poderoso e leve para criação de figurinhas do WhatsApp (estáticas e animadas) com suporte integrado a filtros de imagem, adição de texto e remoção de fundo. Projetado para funcionar em qualquer lugar, do **Termux** a servidores dedicados.
5
4
 
6
- Módulo Node.js para criação de stickers para WhatsApp — feito pra funcionar em qualquer lugar, do **Termux no seu celular** até um servidor dedicado. Sem dependências nativas complicadas, sem dor de cabeça na instalação.
5
+ [![NPM Version](https://img.shields.io/npm/v/@boruto_vk7/stickengine?style=flat-square)](https://www.npmjs.com/package/@boruto_vk7/stickengine)
6
+ [![License](https://img.shields.io/npm/l/@boruto_vk7/stickengine?style=flat-square)](https://github.com/Borutovk7/StickEngine)
7
7
 
8
- > Sabe aquele sofrimento de tentar rodar um módulo de sticker no Termux e quebrar tudo por causa do `sharp` ou de alguma lib nativa? O StickEngine foi criado exatamente pra resolver isso. Aqui funciona.
8
+ ---
9
9
 
10
- ## Por que o StickEngine?
10
+ ## Funcionalidades
11
11
 
12
- - **Funciona no Termux** sem `sharp`, sem compilação nativa, sem erro de permissão
13
- - **Funciona em VPS, Replit, Railway, servidor dedicado** em qualquer ambiente
14
- - **Zero configuração extra** instala e já usa
15
- - **Suporte a ESM e CJS** compatível com qualquer projeto
16
- - **Entrada flexível** URL, Buffer ou caminho local, tanto faz
12
+ - 🎞️ **Figurinhas Animadas**: Suporte automático para GIFs e Vídeos (MP4).
13
+ - 🎨 **Filtros Profissionais**: Sépia, Tons de Cinza, Inversão e Desfoque (Blur).
14
+ - ✍️ **Texto Customizado**: Adicione legendas diretamente na figurinha.
15
+ - ✂️ **Remoção de Fundo**: Integração com a API `remove.bg`.
16
+ - 🧹 **Limpeza Automática**: Sistema de gerenciamento de arquivos temporários com o método `.clean()`.
17
+ - 🏷️ **Metadados (Exif)**: Personalize o nome do pacote e o autor sem complicação.
18
+ - 📱 **Termux Friendly**: Sem dependências nativas pesadas como `sharp`.
17
19
 
18
- ## Requisitos
20
+ ---
19
21
 
20
- - Node.js 16+
21
- - [ffmpeg](https://ffmpeg.org/) instalado no sistema
22
+ ## 🖼️ Exemplos Visuais
22
23
 
23
- ```bash
24
- # Termux
25
- pkg install ffmpeg
24
+ | Filtro Séia + Texto | Figurinha Animada (Mockup) |
25
+ | :---: | :---: |
26
+ | ![Sepia Preview](assets/preview_sepia.png) | ![Animated Preview](assets/preview_animated.png) |
26
27
 
27
- # Debian/Ubuntu/VPS
28
- sudo apt install ffmpeg
29
- ```
28
+ ---
30
29
 
31
- ## Instalação
30
+ ## 📦 Instalação
32
31
 
33
32
  ```bash
34
33
  npm install @boruto_vk7/stickengine
35
34
  ```
36
35
 
37
- ## Uso
36
+ > **Requisito:** Certifique-se de ter o [FFmpeg](https://ffmpeg.org/) instalado no seu sistema. No Termux: `pkg install ffmpeg`.
37
+
38
+ ---
38
39
 
39
- ### ESM
40
+ ## 🚀 Como Usar (Exemplos Técnicos)
40
41
 
42
+ ### 1. Criando uma Figurinha Estática Simples
41
43
  ```javascript
42
44
  import StickEngine from '@boruto_vk7/stickengine';
43
45
 
44
- const engine = new StickEngine({
45
- metadata: {
46
- pack: 'Meu Pack de Stickers',
47
- author: 'Borutovk7',
48
- emojis: ['✨', '🚀']
49
- },
50
- // Opcional: chaves da API remove.bg para remoção de fundo
51
- // transparent: ['SUA_API_KEY']
52
- });
46
+ const engine = new StickEngine();
47
+ engine.addFile('https://exemplo.com/foto.jpg');
53
48
 
54
- engine.on('st.start', (data) => console.log(`Processando:`, data.input));
55
- engine.on('st.data', (data) => console.log(`Sticker gerado:`, data.file));
56
- engine.on('st.error', (data) => console.error(`Erro:`, data.error));
49
+ const results = await engine.start();
50
+ console.log('Caminho do WebP:', results[0].value);
51
+ engine.clean();
52
+ ```
57
53
 
58
- const results = await engine
59
- .addFile('https://picsum.photos/512') // URL
60
- .addFile('caminho/para/video.mp4') // caminho local
61
- .addFile(buffer) // Buffer
62
- .start();
54
+ ### 2. Figurinha Animada (GIF ou Vídeo)
55
+ O motor detecta automaticamente a duração e converte para WebP animado.
56
+ ```javascript
57
+ const engine = new StickEngine({
58
+ fps: 20, // Aumenta a fluidez
59
+ quality: 70 // Otimiza o tamanho para o WhatsApp
60
+ });
63
61
 
64
- console.log(results);
62
+ engine.addFile('./video_engracado.mp4');
63
+ await engine.start();
64
+ engine.clean();
65
65
  ```
66
66
 
67
- ### CJS
68
-
67
+ ### 3. Aplicando Filtros e Texto
69
68
  ```javascript
70
- const StickEngine = require('@boruto_vk7/stickengine');
71
-
72
69
  const engine = new StickEngine({
73
- metadata: {
74
- pack: 'Meu Pack',
75
- author: 'Borutovk7',
76
- emojis: ['🎉']
70
+ edit: {
71
+ sepia: true,
72
+ blur: 5,
73
+ text: {
74
+ content: 'MUITO BOM!',
75
+ alignmentY: 2 // 0: Topo, 1: Meio, 2: Baixo
76
+ }
77
77
  }
78
78
  });
79
79
 
80
- engine.on('st.start', (data) => console.log(`Processando:`, data.input));
81
- engine.on('st.data', (data) => console.log(`Sticker gerado:`, data.file));
82
- engine.on('st.error', (data) => console.error(`Erro:`, data.error));
83
-
84
- engine.addFile('https://picsum.photos/200')
85
- .start()
86
- .then(results => console.log(results))
87
- .catch(err => console.error(err));
80
+ engine.addFile(bufferDeImagem);
81
+ await engine.start();
82
+ engine.clean();
88
83
  ```
89
84
 
90
- ## Eventos
91
-
92
- | Evento | Descrição |
93
- |--------|-----------|
94
- | `st.start` | Disparado ao iniciar o processamento de um arquivo |
95
- | `st.info` | Metadados do arquivo sendo processado |
96
- | `st.data` | Sticker gerado com sucesso |
97
- | `st.error` | Erro ao processar um arquivo |
98
-
99
- ## API
100
-
101
- ### `new StickEngine(options)`
102
-
103
- | Opção | Tipo | Descrição |
104
- |-------|------|-----------|
105
- | `metadata.pack` | `string` | Nome do pacote de stickers |
106
- | `metadata.author` | `string` | Nome do autor |
107
- | `metadata.emojis` | `string[]` | Emojis associados ao sticker |
108
- | `transparent` | `string[]` | Chaves da API remove.bg para remoção de fundo |
109
-
110
- ### `.addFile(input)`
111
-
112
- Adiciona um arquivo à fila. Aceita URL, Buffer ou caminho local. Retorna a instância para encadeamento.
85
+ ### 4. Remoção de Fundo (Remove.bg)
86
+ ```javascript
87
+ const engine = new StickEngine({
88
+ transparent: 'SUA_API_KEY_AQUI'
89
+ });
113
90
 
114
- ### `.start()`
91
+ engine.addFile('foto_com_fundo.png');
92
+ await engine.start();
93
+ engine.clean();
94
+ ```
115
95
 
116
- Inicia o processamento da fila. Retorna uma Promise com os resultados.
96
+ ---
117
97
 
118
- ### `getBuffer(url)`
98
+ ## ⚙️ Opções do Construtor
119
99
 
120
- Utilitário para baixar uma URL como Buffer.
100
+ | Opção | Tipo | Padrão | Descrição |
101
+ | :--- | :--- | :--- | :--- |
102
+ | `metadata` | `Object` | `{ pack: 'StickEngine', author: 'Borutovk7' }` | Nome do pacote e autor. |
103
+ | `edit` | `Object` | `false` | Filtros (`sepia`, `greyscale`, `invert`, `blur`) e `text`. |
104
+ | `transparent` | `String` | `false` | Chave da API `remove.bg` para remover fundo. |
105
+ | `autoClean` | `Boolean` | `true` | Habilita o rastreio de arquivos para limpeza. |
106
+ | `quality` | `Number` | `80` | Qualidade do WebP (1-100). |
107
+ | `fps` | `Number` | `15` | Frames por segundo para animações. |
121
108
 
122
- ```javascript
123
- import { getBuffer } from '@boruto_vk7/stickengine';
109
+ ---
124
110
 
125
- const buffer = await getBuffer('https://example.com/image.png');
126
- ```
111
+ ## 🤝 Contribuições
127
112
 
128
- ## Créditos
113
+ Contribuições são sempre bem-vindas! Sinta-se à vontade para abrir uma **Issue** ou enviar um **Pull Request**.
129
114
 
130
- - [Eduh dev](https://github.com/Borutovk7)
115
+ Desenvolvido por [Borutovk7](https://github.com/Borutovk7) e [Eduh Dev](https://github.com/EduhDev).
131
116
 
117
+ ---
132
118
 
133
- ## Licença
119
+ ## 📄 Licença
134
120
 
135
- ISC
121
+ Este projeto está sob a licença [ISC](LICENSE).
Binary file
Binary file
@@ -5,25 +5,46 @@ export interface StickerMetadata {
5
5
  author?: string;
6
6
  emojis?: string[];
7
7
  }
8
+ export interface JimpOptions {
9
+ greyscale?: boolean;
10
+ invert?: boolean;
11
+ sepia?: boolean;
12
+ blur?: number;
13
+ resize?: {
14
+ width: number;
15
+ height: number;
16
+ };
17
+ text?: {
18
+ content: string;
19
+ alignmentX?: number;
20
+ alignmentY?: number;
21
+ color?: string;
22
+ };
23
+ }
8
24
  export interface StickEngineOptions {
9
25
  webp?: boolean;
10
- edit?: string | boolean;
26
+ edit?: JimpOptions | boolean;
11
27
  convert?: boolean;
12
28
  transparent?: string | string[] | false;
13
29
  metadata?: StickerMetadata;
30
+ autoClean?: boolean;
31
+ fps?: number;
32
+ quality?: number;
14
33
  }
15
34
  /**
16
35
  * Faz GET em uma URL e retorna o corpo como Buffer.
17
- * Fornecido pelo usuário para integração.
18
36
  */
19
37
  export declare const getBuffer: (url: string, options?: AxiosRequestConfig) => Promise<Buffer>;
20
38
  export declare class StickEngine extends EventEmitter {
21
39
  options: StickEngineOptions;
22
40
  private tempDir;
23
41
  private queue;
42
+ private createdFiles;
24
43
  constructor(options?: StickEngineOptions);
25
44
  addFile(file: string | Buffer): this;
45
+ clean(): void;
26
46
  private processFile;
47
+ private applyJimpEdits;
27
48
  private getMediaInfo;
28
49
  private convertToWebp;
29
50
  private addExif;
@@ -7,13 +7,14 @@ import ffmpeg from 'fluent-ffmpeg';
7
7
  // @ts-ignore
8
8
  import webpMux from 'node-webpmux';
9
9
  // @ts-ignore
10
+ import Jimp from 'jimp';
11
+ // @ts-ignore
10
12
  import { removeBackgroundFromImageFile } from 'remove.bg';
11
13
  import { fileURLToPath } from 'url';
12
14
  const __filename = fileURLToPath(import.meta.url);
13
15
  const __dirname = path.dirname(__filename);
14
16
  /**
15
17
  * Faz GET em uma URL e retorna o corpo como Buffer.
16
- * Fornecido pelo usuário para integração.
17
18
  */
18
19
  export const getBuffer = async (url, options = {}) => {
19
20
  try {
@@ -32,7 +33,7 @@ export const getBuffer = async (url, options = {}) => {
32
33
  }
33
34
  catch (err) {
34
35
  console.error(`Erro em getBuffer: ${err}`);
35
- const errorImagePath = path.join(__dirname, 'src', 'emror.jpg');
36
+ const errorImagePath = path.join(__dirname, 'emror.jpg');
36
37
  if (fs.existsSync(errorImagePath)) {
37
38
  return fs.readFileSync(errorImagePath);
38
39
  }
@@ -43,6 +44,7 @@ export class StickEngine extends EventEmitter {
43
44
  options;
44
45
  tempDir;
45
46
  queue;
47
+ createdFiles;
46
48
  constructor(options = {}) {
47
49
  super();
48
50
  this.options = {
@@ -50,6 +52,9 @@ export class StickEngine extends EventEmitter {
50
52
  edit: false,
51
53
  convert: false,
52
54
  transparent: false,
55
+ autoClean: true,
56
+ fps: 15,
57
+ quality: 80,
53
58
  metadata: {
54
59
  pack: 'StickEngine',
55
60
  author: 'Borutovk7 & Eduh Dev',
@@ -62,15 +67,30 @@ export class StickEngine extends EventEmitter {
62
67
  fs.mkdirSync(this.tempDir, { recursive: true });
63
68
  }
64
69
  this.queue = [];
70
+ this.createdFiles = [];
65
71
  }
66
72
  addFile(file) {
67
73
  this.queue.push(file);
68
74
  return this;
69
75
  }
76
+ clean() {
77
+ for (const file of this.createdFiles) {
78
+ try {
79
+ if (fs.existsSync(file)) {
80
+ fs.unlinkSync(file);
81
+ }
82
+ }
83
+ catch (err) {
84
+ console.error(`Erro ao deletar arquivo temporário ${file}:`, err);
85
+ }
86
+ }
87
+ this.createdFiles = [];
88
+ }
70
89
  async processFile(input, index) {
71
- let filePath;
72
- let extension;
90
+ let filePath = '';
91
+ let extension = '';
73
92
  const timestamp = Date.now();
93
+ const localCreatedFiles = [];
74
94
  try {
75
95
  this.emit('st.start', { index, input });
76
96
  const ft = await import('file-type');
@@ -80,6 +100,7 @@ export class StickEngine extends EventEmitter {
80
100
  extension = type ? type.ext : 'bin';
81
101
  filePath = path.join(this.tempDir, `input_${timestamp}_${index}.${extension}`);
82
102
  fs.writeFileSync(filePath, input);
103
+ localCreatedFiles.push(filePath);
83
104
  }
84
105
  else if (typeof input === 'string' && input.startsWith('http')) {
85
106
  const buffer = await getBuffer(input);
@@ -87,18 +108,27 @@ export class StickEngine extends EventEmitter {
87
108
  extension = type ? type.ext : 'bin';
88
109
  filePath = path.join(this.tempDir, `input_${timestamp}_${index}.${extension}`);
89
110
  fs.writeFileSync(filePath, buffer);
111
+ localCreatedFiles.push(filePath);
90
112
  }
91
113
  else if (typeof input === 'string' && fs.existsSync(input)) {
92
- extension = path.extname(input).slice(1);
93
114
  filePath = input;
94
115
  }
95
116
  else {
96
117
  throw new Error('Tipo de entrada inválido ou arquivo não encontrado.');
97
118
  }
98
- const metadata = await this.getMediaInfo(filePath);
99
- this.emit('st.info', { index, ...metadata });
119
+ const mediaInfo = await this.getMediaInfo(filePath);
120
+ this.emit('st.info', { index, ...mediaInfo });
100
121
  let currentFile = filePath;
101
- if (this.options.transparent) {
122
+ const isAnimated = mediaInfo.duration > 0 || extension === 'gif' || extension === 'mp4' || extension === 'webp';
123
+ // Aplicar Edições Jimp (Apenas para Imagens Estáticas por enquanto)
124
+ if (this.options.edit && !isAnimated) {
125
+ const editedPath = path.join(this.tempDir, `edited_${timestamp}_${index}.png`);
126
+ await this.applyJimpEdits(currentFile, editedPath, this.options.edit);
127
+ localCreatedFiles.push(editedPath);
128
+ currentFile = editedPath;
129
+ }
130
+ // Remoção de fundo (Apenas para Imagens Estáticas)
131
+ if (this.options.transparent && !isAnimated) {
102
132
  const apiKey = Array.isArray(this.options.transparent)
103
133
  ? this.options.transparent[Math.floor(Math.random() * this.options.transparent.length)]
104
134
  : this.options.transparent;
@@ -111,60 +141,97 @@ export class StickEngine extends EventEmitter {
111
141
  type: 'auto'
112
142
  });
113
143
  fs.writeFileSync(bgRemovedPath, Buffer.from(result.base64img, 'base64'));
144
+ localCreatedFiles.push(bgRemovedPath);
114
145
  currentFile = bgRemovedPath;
115
146
  }
116
147
  }
148
+ // Conversão para WebP (Suporta Estático e Animado)
117
149
  const webpPath = path.join(this.tempDir, `sticker_${timestamp}_${index}.webp`);
118
- await this.convertToWebp(currentFile, webpPath);
150
+ await this.convertToWebp(currentFile, webpPath, isAnimated);
151
+ localCreatedFiles.push(webpPath);
119
152
  currentFile = webpPath;
153
+ // Adição de Metadados (Exif)
120
154
  if (this.options.metadata) {
121
155
  await this.addExif(currentFile, this.options.metadata);
122
156
  }
157
+ this.createdFiles.push(...localCreatedFiles);
123
158
  this.emit('st.data', { index, file: currentFile });
124
159
  return currentFile;
125
160
  }
126
161
  catch (error) {
127
162
  this.emit('st.error', { index, error: error.message });
163
+ for (const f of localCreatedFiles) {
164
+ if (fs.existsSync(f))
165
+ fs.unlinkSync(f);
166
+ }
128
167
  throw error;
129
168
  }
130
169
  }
170
+ async applyJimpEdits(input, output, options) {
171
+ const image = await Jimp.read(input);
172
+ if (options.greyscale)
173
+ image.greyscale();
174
+ if (options.invert)
175
+ image.invert();
176
+ if (options.sepia)
177
+ image.sepia();
178
+ if (options.blur)
179
+ image.blur(options.blur);
180
+ if (options.resize)
181
+ image.resize(options.resize.width, options.resize.height);
182
+ if (options.text) {
183
+ const font = await Jimp.loadFont(Jimp.FONT_SANS_32_WHITE);
184
+ image.print(font, 0, 0, {
185
+ text: options.text.content,
186
+ alignmentX: options.text.alignmentX || Jimp.HORIZONTAL_ALIGN_CENTER,
187
+ alignmentY: options.text.alignmentY || Jimp.VERTICAL_ALIGN_BOTTOM
188
+ }, image.bitmap.width, image.bitmap.height);
189
+ }
190
+ await image.writeAsync(output);
191
+ }
131
192
  getMediaInfo(file) {
132
- return new Promise((resolve, reject) => {
193
+ return new Promise((resolve) => {
133
194
  exec(`ffprobe -v error -select_streams v:0 -show_entries stream=width,height,duration -of csv=p=0:s=x ${file}`, (err, stdout) => {
134
195
  if (err)
135
- return reject(err);
136
- const [width, height, duration] = stdout.split('x');
196
+ return resolve({ width: 0, height: 0, duration: 0 });
197
+ const parts = stdout.trim().split('x');
137
198
  resolve({
138
- width: parseInt(width) || 0,
139
- height: parseInt(height) || 0,
140
- duration: parseFloat(duration) || 0
199
+ width: parseInt(parts[0]) || 0,
200
+ height: parseInt(parts[1]) || 0,
201
+ duration: parseFloat(parts[2]) || 0
141
202
  });
142
203
  });
143
204
  });
144
205
  }
145
- convertToWebp(input, output) {
206
+ convertToWebp(input, output, isAnimated) {
146
207
  return new Promise((resolve, reject) => {
147
- ffmpeg(input)
208
+ const ff = ffmpeg(input)
148
209
  .on('error', reject)
149
- .on('end', () => resolve())
150
- .addOutputOptions([
210
+ .on('end', () => resolve());
211
+ const videoOptions = [
151
212
  '-vcodec', 'libwebp',
152
- '-vf', 'scale=512:512:force_original_aspect_ratio=decrease,fps=15,pad=512:512:(ow-iw)/2:(oh-ih)/2:color=#00000000,setsar=1',
213
+ '-vf', `scale=512:512:force_original_aspect_ratio=decrease,fps=${this.options.fps},pad=512:512:(ow-iw)/2:(oh-ih)/2:color=#00000000,setsar=1`,
153
214
  '-lossless', '1',
154
215
  '-loop', '0',
155
216
  '-preset', 'default',
156
217
  '-an',
157
218
  '-vsync', '0'
158
- ])
219
+ ];
220
+ if (isAnimated) {
221
+ // Opções específicas para animação para manter o peso baixo (limite do WhatsApp é 1MB)
222
+ videoOptions.push('-t', '6'); // Limita a 6 segundos
223
+ videoOptions.push('-q:v', String(this.options.quality));
224
+ }
225
+ ff.addOutputOptions(videoOptions)
159
226
  .toFormat('webp')
160
227
  .save(output);
161
228
  });
162
229
  }
163
230
  async addExif(webpPath, metadata) {
164
231
  const json = {
165
- 'sticker-pack-id': 'StickEngine-Manus',
232
+ 'sticker-pack-id': 'StickEngine-Official',
166
233
  'sticker-pack-name': metadata.pack || 'StickEngine',
167
- 'sticker-pack-publisher': metadata.author || 'Borutovk7 & Eduh Dev',
234
+ 'sticker-pack-publisher': metadata.author || 'Borutovk7',
168
235
  'emojis': metadata.emojis || ['🥶']
169
236
  };
170
237
  const Image = webpMux.Image || (webpMux.default && webpMux.default.Image);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boruto_vk7/stickengine",
3
- "version": "0.0.3-alpha",
3
+ "version": "0.0.4",
4
4
  "description": "StickEngine module for creating WhatsApp stickers",
5
5
  "type": "module",
6
6
  "main": "dist/StickEngine.js",