8 |
9 |
10 |
11 | ## Summary
12 |
13 | - [Summary](#summary)
14 | - [🤖 Computer-vision based UI Automation](#-computer-vision-based-ui-automation)
15 | - [🚀 Getting Started](#-getting-started)
16 | - [📦 Prerequisites](#-prerequisites)
17 | - [💫 Installing](#-installing)
18 | - [📚 Documentation](#-documentation)
19 | - [💻 Developers Portal](#-developers-portal)
20 | - [💬 Forum](#-forum)
21 | - [🌎 BotCity Automation Platform](#-botcity-automation-platform)
22 | - [1️⃣ All in One Platform](#1️⃣--all-in-one-platform)
23 | - [2️⃣ Deploy with a Single Line](#2️⃣--deploy-with-a-single-line)
24 | - [3️⃣ Manage your Task Queue](#3️⃣--manage-your-task-queue)
25 | - [4️⃣ Manage your Runtime Environments](#4️⃣--manage-your-runtime-environments)
26 | - [5️⃣ Create Alerts and Reports from the Automation Execution](#5️⃣--create-alerts-and-reports-from-the-automation-execution)
27 | - [6️⃣ Create Google Data Studio Dashboards](#6️⃣--create-google-data-studio-dashboards)
28 | - [7️⃣ Create your Community Account](#7️⃣--create-your-community-account)
29 | - [🤝 Contributing to BotCity Framework](#-contributing-to-botcity-framework)
30 | - [⛑ Support](#-support)
31 | - [🐛 Bug reports and 💎 Feature requests](#-bug-reports-and--feature-requests)
32 | - [📢 Contact us](#-contact-us)
33 |
34 |
35 | ## 🤖 Computer-vision based UI Automation
36 |
37 | Recognize and interact with UI elements using state-of-art computer vision module.
38 |
39 | Operate any UI interface independent of the technology or platform (desktop, web, terminal).
40 |
41 |
42 | ## 🚀 Getting Started
43 |
44 | ### 📦 Prerequisites
45 | * Node 16+
46 |
47 | ### 💫 Installing
48 |
49 | Install by Npm:
50 | ```
51 | npm i @botcity/botcity-maestro-sdk
52 | ```
53 |
54 | Install a local:
55 | ```bash
56 | npm install
57 | ```
58 |
59 |
60 | ## 📚 Documentation
61 |
62 | Documentation is available at https://documentation.botcity.dev/maestro/maestro-sdk/
63 |
64 | ## 💻 Developers Portal
65 |
66 | [](https://documentation.botcity.dev)
67 |
68 | ## 💬 Forum
69 |
70 | [](https://community.botcity.dev/)
71 |
72 | ## 🌎 BotCity Automation Platform
73 | BotCity is a platform to develop, deploy, manage and maintain automations. Automations can be developed in Python or Java using open-source libraries that are market standard.
74 |
75 | ### 1️⃣ All in One Platform
76 | Develop, deploy, manage and scale your Automation Ops using All in One platform that provides task queue, runtime environment management, reports, alerts, logs and much more.
77 |
78 | [](https://botcity.atlassian.net/l/c/WWGswYRX)
79 |
80 | ### 2️⃣ Deploy with a Single Line
81 |
82 | Use BotCity command-line interface (CLI) to deploy your bot into a runtime environment with a single line:
83 |
84 | [](https://botcity.atlassian.net/l/c/hJHE1ZFv)
85 |
86 | ### 3️⃣ Manage your Task Queue
87 |
88 | [](https://botcity.atlassian.net/l/c/gR3AAd2a)
89 |
90 | ### 4️⃣ Manage your Runtime Environments
91 |
92 | [](https://botcity.atlassian.net/l/c/uDB087nK)
93 |
94 | ### 5️⃣ Create Alerts and Reports from the Automation Execution
95 |
96 | [](https://botcity.atlassian.net/l/c/McH09qYw)
97 |
98 | ### 6️⃣ Create Google Data Studio Dashboards
99 |
100 | [](https://botcity.atlassian.net/l/c/Z1uMY1vX)
101 |
102 | ### 7️⃣ Create your Community Account
103 |
104 | We have a community account for hobbyists and students. Just signup and start automating.
105 |
106 | [](https://botcity.dev/app/signup)
107 |
108 |
109 | ## 🤝 Contributing to BotCity Framework
110 |
111 | - [Guidelines](https://github.com/botcity-dev/botcity-maestro-sdk-js/blob/main/.github/CONTRIBUTING.md)
112 | - [Documentation](https://documentation.botcity.dev/maestro/maestro-sdk/)
113 |
114 | ## ⛑ Support
115 |
116 | ### 🐛 Bug reports and 💎 Feature requests
117 |
118 | If you spot a problem, please let us know by following the template in
119 | here: [Report a bug](https://github.com/botcity-dev/botcity-maestro-sdk-js/issues/new?template=bug-report.md).
120 |
121 | Ideas or suggestions for enhancements are more than welcome. Please use the following
122 | template in here: [Request feature](https://github.com/botcity-dev/botcity-maestro-sdk-js/issues/new?template=feature-request.md&labels=request).
123 |
124 | ### 📢 Contact us
125 |
126 | If you have questions or comments in general about the framework, we want to know.
127 |
128 | You can choose between the channels the one that best fit you:
129 |
130 | - [BotCity Community]() (Public)
131 |
132 | or you can [file a bug](https://github.com/botcity-dev/botcity-maestro-sdk-js/issues/new?template=bug-report.md) and let us know where our documentation could be improved.
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/src/botcity/maestro/sdk.ts:
--------------------------------------------------------------------------------
1 | import axios, { AxiosResponse } from 'axios'
2 | import {
3 | ensureAccessToken,
4 | catchError,
5 | getMessageInError,
6 | getStackInError,
7 | getTypeInError,
8 | getDefaultTags,
9 | createNpmList,
10 | verifyUrlServer
11 | } from './utils'
12 | import { Alert, DataLog, Log, Logs, Task, Artifact, Artifacts } from './interfaces'
13 | import fs from 'fs'
14 | import https from 'https'
15 | import FormData from 'form-data'
16 | import { Column } from './columns'
17 | import { basename } from 'path'
18 |
19 | export class BotMaestroSdk {
20 | private _server: string
21 | private _login: string
22 | private _key: string
23 | private _accessToken: string
24 | private _verifySSLCert: boolean
25 |
26 | constructor (server: string, login: string, key: string, verifySSLCert: boolean = true) {
27 | this._server = verifyUrlServer(server)
28 | this._login = login
29 | this._key = key
30 | this._accessToken = ''
31 | this._verifySSLCert = verifySSLCert
32 | }
33 |
34 | get server (): string {
35 | return this._server
36 | }
37 |
38 | set server (server: string) {
39 | this._server = verifyUrlServer(server)
40 | }
41 |
42 | private get headers (): Object {
43 | return {
44 | headers: { token: this.accessToken, organization: this._login },
45 | httpsAgent: this._getHttpsAgent()
46 | }
47 | }
48 |
49 | get accessToken (): string {
50 | return this._accessToken
51 | }
52 |
53 | set accessToken (accessToken: string) {
54 | this._accessToken = accessToken
55 | }
56 |
57 | get verify (): string {
58 | return this._accessToken
59 | }
60 |
61 | set verifySSLCert (verifySSLCert: boolean) {
62 | this._verifySSLCert = verifySSLCert
63 | }
64 |
65 | get verifySSLCert (): boolean {
66 | return this._verifySSLCert
67 | }
68 |
69 | get isOnline (): boolean {
70 | return this.accessToken !== ''
71 | }
72 |
73 | private _getHttpsAgent (): https.Agent {
74 | return new https.Agent({
75 | rejectUnauthorized: this.verifySSLCert
76 | })
77 | }
78 |
79 | private _validateItems (
80 | totalItems: number | null,
81 | processedItems: number | null,
82 | failedItems: number | null
83 | ): any[] {
84 | if (totalItems === null && processedItems === null && failedItems === null) {
85 | console.warn(
86 | `Attention: this task is not reporting items. Please inform the total, processed and failed items.
87 | Reporting items is a crucial step to calculate the ROI, success rate and other metrics for your automation
88 | via BotCity Insights.`
89 | )
90 | return [null, null, null]
91 | }
92 |
93 | if (totalItems === null && processedItems !== null && failedItems !== null) {
94 | totalItems = processedItems + failedItems
95 | }
96 |
97 | if (totalItems !== null && processedItems !== null && failedItems === null) {
98 | failedItems = totalItems - processedItems
99 | }
100 |
101 | if (totalItems !== null && processedItems === null && failedItems !== null) {
102 | processedItems = totalItems - failedItems
103 | }
104 |
105 | if (totalItems === null || processedItems === null || failedItems === null) {
106 | throw new Error(
107 | 'You must inform at least two of the following parameters: totalItems, processedItems, failedItems.'
108 | )
109 | }
110 |
111 | totalItems = Math.max(0, totalItems)
112 | processedItems = Math.max(0, processedItems)
113 | failedItems = Math.max(0, failedItems)
114 |
115 | if (totalItems !== null && processedItems !== null && failedItems !== null) {
116 | if (totalItems !== processedItems + failedItems) {
117 | throw new Error('Total items is not equal to the sum of processed and failed items.')
118 | }
119 | }
120 | return [totalItems, processedItems, failedItems]
121 | }
122 |
123 | async login (server: string = '', login: string = '', key: string = ''): Promise {
124 | try {
125 | if (server !== '') {
126 | this.server = verifyUrlServer(server)
127 | }
128 |
129 | this._login = login !== '' ? login : this._login
130 | this._key = key !== '' ? key : this._key
131 |
132 | if (this.server === '') {
133 | throw new Error('Server is required.')
134 | }
135 |
136 | if (this._login === '') {
137 | throw new Error('Login is required.')
138 | }
139 |
140 | if (this._key === '') {
141 | throw new Error('Key is required.')
142 | }
143 |
144 | const url = `${this.server}/api/v2/workspace/login`
145 | const data = { login: this._login, key: this._key }
146 | const response: AxiosResponse = await axios.post(url, data, {
147 | httpsAgent: this._getHttpsAgent()
148 | })
149 | this.accessToken = response.data.accessToken
150 | } catch (error) {
151 | console.error(error)
152 | throw error
153 | }
154 | }
155 |
156 | async logoff (): Promise {
157 | this.accessToken = ''
158 | }
159 |
160 | @ensureAccessToken
161 | @catchError
162 | async createTask (
163 | activityLabel: string,
164 | parameters: Object,
165 | test: boolean = false,
166 | priority: number = 0,
167 | minExecutionDate: Date | null = null
168 | ): Promise {
169 | const url = `${this.server}/api/v2/task`
170 | const data = {
171 | activityLabel,
172 | test,
173 | parameters,
174 | priority,
175 | minExecutionDate: minExecutionDate instanceof Date ? minExecutionDate.toISOString() : null
176 | }
177 | const response: AxiosResponse = await axios
178 | .post(url, data, this.headers)
179 | .catch((error: any) => {
180 | console.log(error)
181 | throw new Error(error.response.data.message)
182 | })
183 | return response.data
184 | }
185 |
186 | @ensureAccessToken
187 | @catchError
188 | async finishTask (
189 | taskId: string | number,
190 | finishStatus: Object,
191 | finishMessage: string = '',
192 | totalItems: number | null = null,
193 | processedItems: number | null = null,
194 | failedItems: number | null = null
195 | ): Promise {
196 | const url = `${this.server}/api/v2/task/${taskId}`
197 | const [validTotalItems, validProcessedItems, validFailedItems] = this._validateItems(
198 | totalItems,
199 | processedItems,
200 | failedItems
201 | )
202 | const data = {
203 | state: 'FINISHED',
204 | finishStatus,
205 | finishMessage,
206 | totalItems: validTotalItems,
207 | processedItems: validProcessedItems,
208 | failedItems: validFailedItems
209 | }
210 | const response: AxiosResponse = await axios
211 | .post(url, data, this.headers)
212 | .catch((error: any) => {
213 | throw new Error(error.response.data.message)
214 | })
215 | return response.data
216 | }
217 |
218 | @ensureAccessToken
219 | @catchError
220 | async getTask (taskId: string | number): Promise {
221 | const url = `${this.server}/api/v2/task/${taskId}`
222 | const response: AxiosResponse = await axios.get(url, this.headers).catch((error: any) => {
223 | throw new Error(error.response.data.message)
224 | })
225 | return response.data
226 | }
227 |
228 | @ensureAccessToken
229 | @catchError
230 | async restartTask (taskId: string | number): Promise {
231 | const url = `${this.server}/api/v2/task/${taskId}`
232 | const data = { state: 'START' }
233 | const response: AxiosResponse = await axios
234 | .post(url, data, this.headers)
235 | .catch((error: any) => {
236 | throw new Error(error.response.data.message)
237 | })
238 | return response.data
239 | }
240 |
241 | @ensureAccessToken
242 | @catchError
243 | async interruptTask (taskId: string | number): Promise {
244 | const url = `${this.server}/api/v2/task/${taskId}`
245 | const data = { interrupted: true }
246 | const response: AxiosResponse = await axios
247 | .post(url, data, this.headers)
248 | .catch((error: any) => {
249 | throw new Error(error.response.data.message)
250 | })
251 | return response.data
252 | }
253 |
254 | @ensureAccessToken
255 | @catchError
256 | async createLog (activityLabel: string, columns: Column[]): Promise {
257 | const url = `${this.server}/api/v2/log`
258 | const data = { activityLabel, columns, organizationLabel: this._login }
259 | const response: AxiosResponse = await axios
260 | .post(url, data, this.headers)
261 | .catch((error: any) => {
262 | throw new Error(error.response.data.message)
263 | })
264 | return response.data
265 | }
266 |
267 | @ensureAccessToken
268 | @catchError
269 | async getLogs (): Promise {
270 | const url = `${this.server}/api/v2/log`
271 | const response: AxiosResponse = await axios.get(url, this.headers).catch((error: any) => {
272 | throw new Error(error.response.data.message)
273 | })
274 | return response.data
275 | }
276 |
277 | @ensureAccessToken
278 | @catchError
279 | async getLog (idLog: string): Promise {
280 | const url = `${this.server}/api/v2/log/${idLog}`
281 | const response: AxiosResponse = await axios.get(url, this.headers).catch((error: any) => {
282 | console.log(error)
283 | throw new Error(error.response.data.message)
284 | })
285 | return response.data
286 | }
287 |
288 | // TODO: Implement others queries params
289 | @ensureAccessToken
290 | @catchError
291 | async fetchDataLog (idLog: string, days: number = 7): Promise {
292 | const url = `${this.server}/api/v2/log/${idLog}/entry-list?days=${days}`
293 | const response: AxiosResponse = await axios.get(url, this.headers).catch((error: any) => {
294 | throw new Error(error.response.data.message)
295 | })
296 | return response.data
297 | }
298 |
299 | @ensureAccessToken
300 | @catchError
301 | async downloadCsvLog (idLog: string, filepath: string, days: number = 7): Promise {
302 | const url = `${this.server}/api/v2/log/${idLog}/export?days=${days}&format=csv`
303 | const response: AxiosResponse = await axios
304 | .get(url, { ...this.headers, responseType: 'arraybuffer' })
305 | .catch((error: any) => {
306 | throw new Error(error.response.data.message)
307 | })
308 | await fs.promises.writeFile(filepath, response.data)
309 | return response.data
310 | }
311 |
312 | @ensureAccessToken
313 | @catchError
314 | async deleteLog (idLog: string): Promise {
315 | const url = `${this.server}/api/v2/log/${idLog}`
316 | await axios.delete(url, this.headers).catch((error: any) => {
317 | throw new Error(error.response.data.message)
318 | })
319 | }
320 |
321 | @ensureAccessToken
322 | @catchError
323 | async logEntry (idLog: string, content: Object): Promise {
324 | const url = `${this.server}/api/v2/log/${idLog}/entry`
325 | await axios.post(url, content, this.headers).catch((error: any) => {
326 | throw new Error(error.response.data.message)
327 | })
328 | }
329 |
330 | @ensureAccessToken
331 | @catchError
332 | async createAlert (
333 | taskId: string | number,
334 | title: string,
335 | message: string,
336 | type: string
337 | ): Promise {
338 | const url = `${this.server}/api/v2/alerts`
339 | const data = { taskId, title, message, type }
340 | const response: AxiosResponse = await axios
341 | .post(url, data, this.headers)
342 | .catch((error: any) => {
343 | throw new Error(error.response.data.message)
344 | })
345 | return response.data
346 | }
347 |
348 | @ensureAccessToken
349 | @catchError
350 | async createMessage (
351 | emails: String[],
352 | logins: String[] = [],
353 | subject: string,
354 | body: string,
355 | type: string
356 | ): Promise {
357 | const url = `${this.server}/api/v2/message`
358 | const data = { emails, logins, subject, body, type }
359 | await axios.post(url, data, this.headers).catch((error: any) => {
360 | throw new Error(error.response.data.message)
361 | })
362 | }
363 |
364 | @ensureAccessToken
365 | @catchError
366 | async createArtifact (taskId: string | number, name: string, filename: string): Promise {
367 | const url = `${this.server}/api/v2/artifact`
368 | const data = { taskId, name, filename }
369 | const response: AxiosResponse = await axios
370 | .post(url, data, this.headers)
371 | .catch((error: any) => {
372 | throw new Error(error.response.data.message)
373 | })
374 | return response.data
375 | }
376 |
377 | @ensureAccessToken
378 | @catchError
379 | async uploadFile (artifactId: string, filepath: string): Promise {
380 | const formData = new FormData()
381 | const file = fs.createReadStream(filepath)
382 | formData.append('file', file)
383 | const url = `${this.server}/api/v2/artifact/log/${artifactId}`
384 | const contentType = `multipart/form-data; boundary=${formData.getBoundary()}`
385 | const headers: object = {
386 | ...this.headers,
387 | 'Content-Type': contentType
388 | }
389 | await axios.post(url, formData, headers).catch((error: any) => {
390 | throw new Error(error.response.data.message)
391 | })
392 | }
393 |
394 | @ensureAccessToken
395 | @catchError
396 | async uploadArtifact (
397 | taskId: string | number,
398 | name: string,
399 | filename: string,
400 | filepath: string
401 | ): Promise {
402 | const artifact = await this.createArtifact(taskId, name, filename)
403 | await this.uploadFile(`${artifact.id}`, filepath)
404 | return artifact
405 | }
406 |
407 | // Todo: Ajust pageable
408 | @ensureAccessToken
409 | @catchError
410 | async getArtifacts (
411 | size: string,
412 | page: string,
413 | sort: String[] = ['dateCreation'],
414 | days: string = '7'
415 | ): Promise {
416 | const url = `${this.server}/api/v2/artifact?size=${size}&page=${page}&sort=${sort.join(
417 | ','
418 | )}&days=${days}`
419 | // TODO: Implement not pageable
420 | const response: AxiosResponse = await axios.get(url, this.headers).catch((error: any) => {
421 | throw new Error(error.response.data.message)
422 | })
423 | return response.data
424 | }
425 |
426 | @ensureAccessToken
427 | @catchError
428 | async downloadArtifact (artifactId: string, filepath: string): Promise {
429 | const url = `${this.server}/api/v2/artifact/${artifactId}/file`
430 | const response: AxiosResponse = await axios
431 | .get(url, { ...this.headers, responseType: 'arraybuffer' })
432 | .catch((error: any) => {
433 | throw new Error(error.response.data.message)
434 | })
435 | await fs.promises.writeFile(filepath, response.data)
436 | return response.data
437 | }
438 |
439 | @ensureAccessToken
440 | @catchError
441 | async createError (
442 | taskId: string | number,
443 | error: Error,
444 | tags: object = {},
445 | screenshot: string = '',
446 | attachments: string[] = []
447 | ): Promise {
448 | const message: string = getMessageInError(error)
449 | const type: string = getTypeInError(error)
450 | const stackTrace: string = getStackInError(error)
451 | const language: string = 'javascript'.toUpperCase()
452 | const url = `${this.server}/api/v2/error`
453 | tags = await getDefaultTags(tags)
454 | const data = { taskId, type, message, stackTrace, language, tags }
455 | const response: AxiosResponse = await axios
456 | .post(url, data, this.headers)
457 | .catch((error: any) => {
458 | throw new Error(error.response.data.message)
459 | })
460 | if (screenshot !== '') {
461 | await this.createScreenshot(response.data.id, screenshot)
462 | }
463 |
464 | const npmListPath = await createNpmList()
465 |
466 | attachments.push(npmListPath)
467 |
468 | try {
469 | if (attachments.length > 0) {
470 | await this.createAttachments(response.data.id, attachments)
471 | }
472 | } finally {
473 | fs.unlinkSync(npmListPath)
474 | }
475 | }
476 |
477 | async getCredential (label: string, key: string): Promise {
478 | const url = `${this.server}/api/v2/credential/${label}/key/${key}`
479 | const response: AxiosResponse = await axios.get(url, this.headers).catch((error: any) => {
480 | throw new Error(error.response.data.message)
481 | })
482 | return response.data
483 | }
484 |
485 | @ensureAccessToken
486 | @catchError
487 | private async createScreenshot (errorId: string, filepath: string): Promise {
488 | const formData = new FormData()
489 | const file = fs.createReadStream(filepath)
490 | try {
491 | formData.append('file', file)
492 | const url = `${this.server}/api/v2/error/${errorId}/screenshot`
493 | const contentType = `multipart/form-data; boundary=${formData.getBoundary()}`
494 | const headers: object = {
495 | ...this.headers,
496 | 'Content-Type': contentType
497 | }
498 | await axios.post(url, formData, headers).catch((error: any) => {
499 | throw new Error(error.response.data.message)
500 | })
501 | } finally {
502 | file.destroy()
503 | }
504 | }
505 |
506 | async getCredentialByLabel (label: string): Promise {
507 | const url = `${this.server}/api/v2/credential/${label}`
508 | try {
509 | const response: AxiosResponse = await axios.get(url, this.headers)
510 | return response.data
511 | } catch {
512 | return null
513 | }
514 | }
515 |
516 | @ensureAccessToken
517 | @catchError
518 | private async createAttachments (errorId: string, attachments: string[]): Promise {
519 | const url = `${this.server}/api/v2/error/${errorId}/attachments`
520 | for (const attachment of attachments) {
521 | const formData = new FormData()
522 | const file = fs.createReadStream(attachment)
523 | try {
524 | formData.append('file', file, { filename: basename(attachment) })
525 | const contentType = `multipart/form-data; boundary=${formData.getBoundary()}`
526 | const headers: object = {
527 | ...this.headers,
528 | 'Content-Type': contentType
529 | }
530 | await axios.post(url, formData, headers).catch((error: any) => {
531 | throw new Error(error.response.data.message)
532 | })
533 | } finally {
534 | file.destroy()
535 | }
536 | }
537 | }
538 |
539 | async createCredentialByLabel (label: string, key: string, value: any): Promise {
540 | const data = {
541 | label,
542 | secrets: [{ key, value, valid: true }]
543 | }
544 | const url = `${this.server}/api/v2/credential`
545 | const credential = await axios.post(url, data, this.headers).catch((error: any) => {
546 | throw new Error(error.response.data.message)
547 | })
548 | return credential
549 | }
550 |
551 | @ensureAccessToken
552 | @catchError
553 | async createCredential (label: string, key: string, value: any): Promise {
554 | let credential = await this.getCredentialByLabel(label)
555 | if (credential == null) {
556 | credential = await this.createCredentialByLabel(label, key, value)
557 | return credential.data
558 | }
559 | const url = `${this.server}/api/v2/credential/${label}/key`
560 | const data = { key, value }
561 | credential = await axios.post(url, data, this.headers).catch((error: any) => {
562 | throw new Error(error.response.data.message)
563 | })
564 | return credential.data
565 | }
566 | }
567 |
--------------------------------------------------------------------------------