Merge pull request #129 from leifermendez/feature/monorepo

Feature/monorepo
This commit is contained in:
Leifer Mendez
2022-12-01 09:53:28 +01:00
committed by GitHub
20 changed files with 1055 additions and 28 deletions

View File

@@ -4,5 +4,5 @@
"reporter": ["html"],
"report-dir": "./coverage",
"check-coverage": true,
"lines": 95
"lines": 90
}

6
.gitignore vendored
View File

@@ -21,7 +21,9 @@ log
lib
tmp/
.yarn/*
!.yarn/releases
.fleet/
example-app/
example-app*/
qr.svg
package-lock.json
package-lock.json
yarn-error.log

View File

@@ -1,4 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
yarn run format:check && yarn run format:write && git add .
yarn run format:write && git add .

807
.yarn/releases/yarn-3.3.0.cjs vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,3 +1,3 @@
nodeLinker: node-modules
npmPublishRegistry: "https://registry.npmjs.org"
yarnPath: .yarn/releases/yarn-3.3.0.cjs
npmPublishRegistry: 'https://registry.npmjs.org'
yarnPath: .yarn/releases/yarn-3.3.0.cjs

View File

@@ -0,0 +1,39 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## 0.1.0 (2022-11-29)
### ⚠ BREAKING CHANGES
* 🧨 NO
### Features
* (🎸) add onClick prop to component ([4ae3898](https://github.com/leifermendez/bot-whatsapp/commit/4ae389846d38c133f6bb2129ae373eed39d9d08d))
### Bug Fixes
* **ci:** ci ([f55cfae](https://github.com/leifermendez/bot-whatsapp/commit/f55cfae6e4ccc1df949212999406680020d27f9c))
* **ci:** ci ([671c5b3](https://github.com/leifermendez/bot-whatsapp/commit/671c5b37f33360e8cb754625b8dd6e83bce9014d))
* (💍) Is justa test! ([37d04e9](https://github.com/leifermendez/bot-whatsapp/commit/37d04e9e89d3f01fdc367654ba60fb11ab2614c4))
#### Actualización 14 Ene 2022
- npm update
- remove ora and chalk
- add env
- add mysql
- add dialogflow
- add scan qr from webpage
- update route with middleware
- fix send message to story
- external download
- easy deploy heroku
- add support for ubuntu/linux
https://stackoverflow.com/questions/51855169/dialogflow-403-iam-permission-dialogflow-sessions-detectintent

View File

@@ -1,7 +1,8 @@
# CONTRIBUTING
__Requerimientos:__
- Node v16 o superior __[descargar node](https://nodejs.org/es/download/)__
- Necesitas __[yarn](https://classic.yarnpkg.com/lang/en/docs/install/#windows-stable)__ como gestor de paquetes. En el link conseguiras las intrucciones para instalar yarn.
- __[Yarn](https://classic.yarnpkg.com/lang/en/docs/install/#windows-stable)__ como gestor de paquetes. En el link conseguiras las intrucciones para instalar yarn.
- Se usara la rama __dev__ *(https://github.com/leifermendez/bot-whatsapp/tree/dev)* como rama principal hasta que se haga oficialmente el lanzamiento de la V2
>💡 Se usa la version 3.3.0 o superior de Yarn para establecer esta version simplemente ejecuta el siguiente comando: `yarn set version 3.3.0`
@@ -15,20 +16,14 @@ __Instalar dependencias__
cd bot-whatsapp
yarn set version 3.3.0
yarn install
npx husky install && npx prettier --write .
```
> __ATENCIÓN__ Si esta estas en ubuntu/linux ejecutar lo siguiente comandos adicionales.
```sheell
npx husky install
chmod ug+x .husky/*
```
__Commit y Push__
El proyecto tiene implementado __[husky](https://typicode.github.io/husky/#/)__ es una herramienta que dispara unas acciones al momento de hacer commit y hacer push
__commit:__ Los commit son semanticos esto quiere decir que deben cumplir un standar al momento de escribirlos ejemplo ` feat(adapter): new adapter myqsl ` puede ver más info sobre esto __[aquí](https://github.com/conventional-changelog/commitlint/#what-is-commitlint)__
__Compilar (build)__
Para compilar la aplicación es necesario ejecutar, eso te genera dentro de packages del monorepo un directorio `lib`
@@ -42,7 +37,36 @@ packages/cli/lib
packages/database/lib
packages/provider/lib
```
__Linking__
```
yarn link.dist
```
__Example-app__
```
yarn run cli
```
Abrir carpeta example-app-base
```
npm link @bot-whatsapp/bot -S
npm link @bot-whatsapp/provider -S
npm link @bot-whatsapp/database -S
npm i
npm start
```
__Commit y Push__
El proyecto tiene implementado __[husky](https://typicode.github.io/husky/#/)__ es una herramienta que dispara unas acciones al momento de hacer commit y hacer push
__commit:__ Los commit son semanticos esto quiere decir que deben cumplir un standar al momento de escribirlos ejemplo ` feat(adapter): new adapter myqsl ` puede ver más info sobre esto __[aquí](https://github.com/conventional-changelog/commitlint/#what-is-commitlint)__
__push:__ Cada push ejecutar `yarn run test` el cual ejecuta los test internos que tienen que cumplir con __95% de cobertura__.

View File

@@ -15,7 +15,7 @@
"lint:check": "eslint ./packages",
"lint:fix": "eslint --fix ./packages",
"build": "yarn run cli:rollup && yarn run bot:rollup && yarn run provider:rollup && yarn run database:rollup",
"link.dist": "cd packages/bot && npm link && cd ../provider && npm link && cd ../cli && npm link",
"link.dist": "cd packages/bot && npm link && cd ../provider && npm link && cd ../cli && npm link && cd ../database && npm link && cd ../provider && npm link",
"test.unit": "node ./node_modules/uvu/bin.js packages test",
"test.coverage": "node ./node_modules/c8/bin/c8.js npm run test.unit",
"test": "npm run test.coverage",
@@ -24,6 +24,7 @@
"dev": "node ./example-app/app.js",
"prepare": "npx husky install",
"preinstall": "npx only-allow yarn",
"postinstall": "npx prettier --write .",
"release": "standard-version"
},
"workspaces": [
@@ -65,6 +66,7 @@
"cz-conventional-changelog": "^3.3.0",
"eslint": "^8.26.0",
"eslint-config-prettier": "^8.5.0",
"fs-extra": "^11.1.0",
"git-cz": "^4.9.0",
"husky": "^8.0.2",
"only-allow": "^1.1.1",

View File

@@ -1,7 +1,7 @@
const CoreClass = require('./core/core.class')
const ProviderClass = require('./provider/provider.class')
const FlowClass = require('./io/flow.class')
const { addKeyword, addAnswer, toSerialize } = require('./io/methods')
const { addKeyword, addAnswer, addChild, toSerialize } = require('./io/methods')
/**
* Crear instancia de clase Bot
@@ -38,6 +38,7 @@ module.exports = {
createProvider,
addKeyword,
addAnswer,
addChild,
toSerialize,
ProviderClass,
CoreClass,

View File

@@ -10,6 +10,7 @@ const { toSerialize } = require('./toSerialize')
const addAnswer =
(inCtx) =>
(answer, options, cb = null, nested = []) => {
answer = Array.isArray(answer) ? answer.join('\n') : answer
/**
* Todas las opciones referentes a el mensaje en concreto options:{}
* @returns

View File

@@ -0,0 +1,15 @@
const { toSerialize } = require('./toSerialize')
/**
* @deprecate
* @param answer string
* @param options {media:string, buttons:[], capture:true default false}
* @returns
*/
const addChild = (flowIn = null) => {
if (!flowIn?.toJson) {
throw new Error('DEBE SER UN FLOW CON toJSON()')
}
return toSerialize(flowIn.toJson())
}
module.exports = { addChild }

View File

@@ -1,7 +1,8 @@
const { addAnswer } = require('./addAnswer')
const { addKeyword } = require('./addKeyword')
const { addChild } = require('./addChild')
const { toSerialize } = require('./toSerialize')
const { toCtx } = require('./toCtx')
const { toJson } = require('./toJson')
module.exports = { addAnswer, addKeyword, toCtx, toJson, toSerialize }
module.exports = { addAnswer, addKeyword, addChild, toCtx, toJson, toSerialize }

View File

@@ -22,6 +22,15 @@ test('Debere probar las propeidades array', () => {
assert.is(MAIN_CTX.ctx.keyword, ARRANGE.keyword)
})
test('Debere probar las propeidades array en answer', () => {
const ARRANGE = {
keyword: ['hola!', 'ole'],
}
const MAIN_CTX = addKeyword(ARRANGE.keyword).addAnswer(['hola', 'chao'])
assert.is(MAIN_CTX.ctx.keyword, ARRANGE.keyword)
})
test('Debere probar toSerialize', () => {
const ARRANGE = {
keyword: ['hola!', 'ole'],

View File

@@ -0,0 +1,21 @@
const fs = require('fs-extra')
/**
* Copy files
*/
const copyFiles = async (from, to) => {
try {
await fs.copy(from, to)
console.log('success!')
} catch (err) {
console.error(err)
}
}
const copyBaseApp = async () => {
const BASEP_APP_PATH_FROM = `${process.cwd()}/starters/apps/base`
const BASEP_APP_PATH_TO = `${process.cwd()}/example-app-base`
await copyFiles(BASEP_APP_PATH_FROM, BASEP_APP_PATH_TO)
}
module.exports = { copyBaseApp }

View File

@@ -2,6 +2,7 @@ const prompts = require('prompts')
const { yellow, red } = require('kleur')
const { installAll } = require('../install')
const { cleanSession } = require('../clean')
const { copyBaseApp } = require('../create-app')
const { checkNodeVersion, checkOs } = require('../check')
const { jsonConfig } = require('../configuration')
@@ -9,10 +10,15 @@ const startInteractive = async () => {
const questions = [
{
type: 'text',
name: 'dependencies',
message:
'Quieres actualizar las librerias "whatsapp-web.js"? (Y/n)',
name: 'exampeOpt',
message: 'Quieres crear una app de ejemplo "example-app"? (Y/n)',
},
// {
// type: 'text',
// name: 'dependencies',
// message:
// 'Quieres actualizar las librerias "whatsapp-web.js"? (Y/n)',
// },
{
type: 'text',
name: 'cleanTmp',
@@ -57,11 +63,12 @@ const startInteractive = async () => {
const {
dependencies = '',
cleanTmp = '',
exampeOpt = '',
providerDb = [],
providerWs = [],
} = response
/**
* Question #1
* Question
* @returns
*/
const installOrUdpateDep = async () => {
@@ -75,7 +82,7 @@ const startInteractive = async () => {
}
/**
* Question #2
* Question
* @returns
*/
const cleanAllSession = async () => {
@@ -88,6 +95,16 @@ const startInteractive = async () => {
}
}
const createApp = async () => {
const answer = exampeOpt.toLowerCase() || 'n'
if (answer.includes('n')) return true
if (answer.includes('y')) {
await copyBaseApp()
return true
}
}
const vendorProvider = async () => {
if (!providerWs.length) {
console.log(
@@ -117,6 +134,7 @@ const startInteractive = async () => {
}
}
await createApp()
await installOrUdpateDep()
await cleanAllSession()
await vendorProvider()

View File

@@ -25,6 +25,28 @@ const main = async () => {
}
```
#### CTX
```json
{
ref: 'ans_7d9981e5-5019-422c-a19a-565cbb021391',
keyword: 'ans_cfdad31b-ff6d-475f-873a-4ed6f8a79a43',
answer: 'Esperando respuesta...',
options: {
media: null,
buttons: [],
capture: true,
child: null,
nested: [Array],
keyword: {},
callback: true
},
refSerialize: '81f18f563fd26a6c6d12c62aed98095f',
from: 'NUMERO_PERSONA_QUE_ESCRIBE'
}
```
#### Video
> Video explicando como debes de agregar nuevos adaptadores

View File

@@ -1,15 +1,20 @@
/**
* Si necesitas saber que trae el "ctx"
* Puedes ver el README.md dentro packages/database
*/
class MockDatabase {
db
listHistory = []
constructor() {
/**
* Se debe cargar listHistory con historial de mensajes
* para que se pueda continuar el flow
*/
constructor() {}
getPrevByNumber = (from) => {
const history = this.listHistory.slice().reverse()
return history.find((a) => a.from === from)
}
save = (ctx) => {
console.log('Guardando DB...', ctx)
this.listHistory.push(ctx)
}
}

33
starters/apps/base/app.js Normal file
View File

@@ -0,0 +1,33 @@
const {
createBot,
createProvider,
createFlow,
addKeyword,
} = require('@bot-whatsapp/bot')
/**
* ATENCION: Si vas a usar el provider whatsapp-web.js
* recuerda ejecutar npm i whatsapp-web.js@latest
*/
const WebWhatsappProvider = require('@bot-whatsapp/provider/web-whatsapp')
const MockAdapter = require('@bot-whatsapp/database/mock')
const flowPrincipal = addKeyword(['hola', 'ole', 'HOLA'])
.addAnswer('Bienvenido a mi tienda')
.addAnswer('Como puedo ayudarte?')
.addAnswer(['Tengo:', 'Zapatos', 'Bolsos', 'etc..'])
const main = async () => {
const adapterDB = new MockAdapter()
const adapterFlow = createFlow([flowPrincipal])
const adapterProvider = createProvider(WebWhatsappProvider)
createBot({
flow: adapterFlow,
provider: adapterProvider,
database: adapterDB,
})
}
main()

View File

@@ -0,0 +1,15 @@
{
"name": "bot-whatsapp-base",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"keywords": [],
"dependencies": {
"whatsapp-web.js": "^1.18.3"
},
"author": "",
"license": "ISC"
}

View File

@@ -963,6 +963,7 @@ __metadata:
cz-conventional-changelog: ^3.3.0
eslint: ^8.26.0
eslint-config-prettier: ^8.5.0
fs-extra: ^11.1.0
git-cz: ^4.9.0
husky: ^8.0.2
only-allow: ^1.1.1
@@ -4379,6 +4380,17 @@ __metadata:
languageName: node
linkType: hard
"fs-extra@npm:^11.1.0":
version: 11.1.0
resolution: "fs-extra@npm:11.1.0"
dependencies:
graceful-fs: ^4.2.0
jsonfile: ^6.0.1
universalify: ^2.0.0
checksum: 5ca476103fa1f5ff4a9b3c4f331548f8a3c1881edaae323a4415d3153b5dc11dc6a981c8d1dd93eec8367ceee27b53f8bd27eecbbf66ffcdd04927510c171e7f
languageName: node
linkType: hard
"fs-extra@npm:^8.1.0":
version: 8.1.0
resolution: "fs-extra@npm:8.1.0"