@open-wa/wa-automate 4.76.0 → 5.0.0-alpha.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 (125) hide show
  1. package/README.md +14 -165
  2. package/dist/cli-runtime-B7_3MM0c.cjs +798 -0
  3. package/dist/cli-runtime-B7_3MM0c.cjs.map +1 -0
  4. package/dist/cli-runtime-CmpYxFCk.d.cts +31 -0
  5. package/dist/cli-runtime-CmpYxFCk.d.cts.map +1 -0
  6. package/dist/cli.cjs +17 -0
  7. package/dist/cli.cjs.map +1 -0
  8. package/dist/cli.d.cts +2 -0
  9. package/dist/index.cjs +224 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.cts +81 -0
  12. package/dist/index.d.cts.map +1 -0
  13. package/package.json +34 -177
  14. package/CNAME +0 -1
  15. package/_tsconfig.docs.json +0 -140
  16. package/bin/config-schema.json +0 -1
  17. package/bin/oas-type-schemas.json +0 -1
  18. package/bin/server.js +0 -45
  19. package/build/build-config-json-for-bin.ts +0 -56
  20. package/build/generate-oas-types.ts +0 -31
  21. package/dist/api/Client.d.ts +0 -2255
  22. package/dist/api/Client.js +0 -4358
  23. package/dist/api/functions/exposed.enum.d.ts +0 -7
  24. package/dist/api/functions/exposed.enum.js +0 -11
  25. package/dist/api/model/aliases.d.ts +0 -110
  26. package/dist/api/model/aliases.js +0 -3
  27. package/dist/api/model/button.d.ts +0 -24
  28. package/dist/api/model/button.js +0 -2
  29. package/dist/api/model/call.d.ts +0 -51
  30. package/dist/api/model/call.js +0 -18
  31. package/dist/api/model/chat.d.ts +0 -221
  32. package/dist/api/model/chat.js +0 -52
  33. package/dist/api/model/config.d.ts +0 -836
  34. package/dist/api/model/config.js +0 -111
  35. package/dist/api/model/contact.d.ts +0 -143
  36. package/dist/api/model/contact.js +0 -2
  37. package/dist/api/model/errors.d.ts +0 -90
  38. package/dist/api/model/errors.js +0 -117
  39. package/dist/api/model/events.d.ts +0 -120
  40. package/dist/api/model/events.js +0 -127
  41. package/dist/api/model/group-metadata.d.ts +0 -124
  42. package/dist/api/model/group-metadata.js +0 -25
  43. package/dist/api/model/id.d.ts +0 -5
  44. package/dist/api/model/id.js +0 -2
  45. package/dist/api/model/index.d.ts +0 -110
  46. package/dist/api/model/index.js +0 -128
  47. package/dist/api/model/label.d.ts +0 -24
  48. package/dist/api/model/label.js +0 -2
  49. package/dist/api/model/media.d.ts +0 -93
  50. package/dist/api/model/media.js +0 -12
  51. package/dist/api/model/message.d.ts +0 -422
  52. package/dist/api/model/message.js +0 -40
  53. package/dist/api/model/product.d.ts +0 -141
  54. package/dist/api/model/product.js +0 -2
  55. package/dist/api/model/reactions.d.ts +0 -76
  56. package/dist/api/model/reactions.js +0 -2
  57. package/dist/api/model/sessionInfo.d.ts +0 -77
  58. package/dist/api/model/sessionInfo.js +0 -2
  59. package/dist/build/build-postman.d.ts +0 -1
  60. package/dist/build/build-postman.js +0 -262
  61. package/dist/cli/cli-options.d.ts +0 -9
  62. package/dist/cli/cli-options.js +0 -289
  63. package/dist/cli/collections.d.ts +0 -2
  64. package/dist/cli/collections.js +0 -251
  65. package/dist/cli/file-utils.d.ts +0 -1
  66. package/dist/cli/file-utils.js +0 -71
  67. package/dist/cli/index.d.ts +0 -1
  68. package/dist/cli/index.js +0 -231
  69. package/dist/cli/integrations/chatwoot.d.ts +0 -49
  70. package/dist/cli/integrations/chatwoot.js +0 -672
  71. package/dist/cli/integrations/cloudflare.d.ts +0 -6
  72. package/dist/cli/integrations/cloudflare.js +0 -76
  73. package/dist/cli/logo.d.ts +0 -1
  74. package/dist/cli/logo.js +0 -49
  75. package/dist/cli/server.d.ts +0 -24
  76. package/dist/cli/server.js +0 -540
  77. package/dist/cli/setup.d.ts +0 -30
  78. package/dist/cli/setup.js +0 -308
  79. package/dist/config/puppeteer.config.d.ts +0 -11
  80. package/dist/config/puppeteer.config.js +0 -65
  81. package/dist/controllers/auth.d.ts +0 -36
  82. package/dist/controllers/auth.js +0 -322
  83. package/dist/controllers/browser.d.ts +0 -17
  84. package/dist/controllers/browser.js +0 -603
  85. package/dist/controllers/events.d.ts +0 -82
  86. package/dist/controllers/events.js +0 -173
  87. package/dist/controllers/init_patch.d.ts +0 -13
  88. package/dist/controllers/init_patch.js +0 -42
  89. package/dist/controllers/initializer.d.ts +0 -22
  90. package/dist/controllers/initializer.js +0 -511
  91. package/dist/controllers/launch_checks.d.ts +0 -8
  92. package/dist/controllers/launch_checks.js +0 -130
  93. package/dist/controllers/patch_manager.d.ts +0 -37
  94. package/dist/controllers/patch_manager.js +0 -231
  95. package/dist/controllers/popup/index.d.ts +0 -3
  96. package/dist/controllers/popup/index.html +0 -168
  97. package/dist/controllers/popup/index.js +0 -148
  98. package/dist/controllers/script_preloader.d.ts +0 -17
  99. package/dist/controllers/script_preloader.js +0 -88
  100. package/dist/index.d.ts +0 -13
  101. package/dist/index.js +0 -36
  102. package/dist/lib/README.md +0 -5
  103. package/dist/lib/base64.js +0 -1
  104. package/dist/lib/hash.js +0 -1
  105. package/dist/lib/jsSha.min.js +0 -1
  106. package/dist/lib/launch.js +0 -1
  107. package/dist/lib/qr.min.js +0 -1
  108. package/dist/lib/wapi.js +0 -2163
  109. package/dist/logging/custom_transport.d.ts +0 -9
  110. package/dist/logging/custom_transport.js +0 -35
  111. package/dist/logging/logging.d.ts +0 -50
  112. package/dist/logging/logging.js +0 -196
  113. package/dist/structures/Collector.d.ts +0 -202
  114. package/dist/structures/Collector.js +0 -391
  115. package/dist/structures/Dialog.d.ts +0 -55
  116. package/dist/structures/Dialog.js +0 -21
  117. package/dist/structures/MessageCollector.d.ts +0 -78
  118. package/dist/structures/MessageCollector.js +0 -145
  119. package/dist/structures/preProcessors.d.ts +0 -58
  120. package/dist/structures/preProcessors.js +0 -181
  121. package/dist/utils/pid_utils.d.ts +0 -1
  122. package/dist/utils/pid_utils.js +0 -26
  123. package/dist/utils/tools.d.ts +0 -152
  124. package/dist/utils/tools.js +0 -494
  125. package/tos.md +0 -77
@@ -1,511 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.create = exports.screenshot = exports.timeout = exports.configWithCases = exports.pkg = void 0;
39
- const fs = __importStar(require("fs"));
40
- const boxen_1 = __importDefault(require("boxen"));
41
- const os_name_1 = __importDefault(require("os-name"));
42
- const update_notifier_1 = __importDefault(require("update-notifier"));
43
- const Client_1 = require("../api/Client");
44
- const index_1 = require("../api/model/index");
45
- const path = __importStar(require("path"));
46
- const os = __importStar(require("os"));
47
- const auth_1 = require("./auth");
48
- const browser_1 = require("./browser");
49
- const events_1 = require("./events");
50
- const launch_checks_1 = require("./launch_checks");
51
- const cfonts_1 = __importDefault(require("cfonts"));
52
- const tools_1 = require("../utils/tools");
53
- const crypto_1 = require("crypto");
54
- const fs_extra_1 = require("fs-extra");
55
- const pico_s3_1 = require("pico-s3");
56
- const init_patch_1 = require("./init_patch");
57
- const patch_manager_1 = require("./patch_manager");
58
- const logging_1 = require("../logging/logging");
59
- const timeout = (ms) => {
60
- return new Promise(resolve => setTimeout(resolve, ms, 'timeout'));
61
- };
62
- exports.pkg = (0, fs_extra_1.readJsonSync)(path.join(__dirname, '../../package.json')), exports.configWithCases = (0, fs_extra_1.readJsonSync)(path.join(__dirname, '../../bin/config-schema.json')), exports.timeout = timeout;
63
- /**
64
- * Used to initialize the client session.
65
- *
66
- * *Note* It is required to set all config variables as [ConfigObject](https://open-wa.github.io/wa-automate-nodejs/interfaces/configobject.html) that includes both [sessionId](https://open-wa.github.io/wa-automate-nodejs/interfaces/configobject.html#sessionId). Setting the session id as the first variable is no longer valid
67
- *
68
- * e.g
69
- *
70
- * ```javascript
71
- * create({
72
- * sessionId: 'main',
73
- * customUserAgent: ' 'WhatsApp/2.16.352 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15',
74
- * blockCrashLogs true,
75
- * ...
76
- * })....
77
- * ```
78
- * @param config AdvancedConfig The extended custom configuration
79
- */
80
- //@ts-ignore
81
- function create(config = {}) {
82
- var _a, _b, _c, _d;
83
- return __awaiter(this, void 0, void 0, function* () {
84
- const START_TIME = Date.now();
85
- if (config.logging) {
86
- if (Array.isArray(config === null || config === void 0 ? void 0 : config.logging))
87
- config.logging = (0, logging_1.setupLogging)(config === null || config === void 0 ? void 0 : config.logging, `owa-${(config === null || config === void 0 ? void 0 : config.sessionId) || 'session'}`);
88
- }
89
- let waPage = undefined;
90
- let notifier;
91
- let sessionId = '';
92
- let customUserAgent;
93
- if (!config || (config === null || config === void 0 ? void 0 : config.eventMode) !== false) {
94
- config.eventMode = true;
95
- }
96
- if ((config === null || config === void 0 ? void 0 : config.waitForRipeSession) !== false)
97
- config.waitForRipeSession = true;
98
- if ((config === null || config === void 0 ? void 0 : config.multiDevice) !== false)
99
- config.multiDevice = true;
100
- if ((config === null || config === void 0 ? void 0 : config.deleteSessionDataOnLogout) !== false)
101
- config.deleteSessionDataOnLogout = true;
102
- if (!(config === null || config === void 0 ? void 0 : config.skipUpdateCheck) || (config === null || config === void 0 ? void 0 : config.keepUpdated)) {
103
- notifier = yield (0, update_notifier_1.default)({
104
- pkg: exports.pkg,
105
- updateCheckInterval: 0
106
- });
107
- notifier.notify();
108
- if ((notifier === null || notifier === void 0 ? void 0 : notifier.update) && (config === null || config === void 0 ? void 0 : config.keepUpdated) && (notifier === null || notifier === void 0 ? void 0 : notifier.update.latest) !== exports.pkg.version) {
109
- console.log('UPDATING @OPEN-WA');
110
- logging_1.log.info('UPDATING @OPEN-WA');
111
- const crossSpawn = yield Promise.resolve().then(() => __importStar(require('cross-spawn')));
112
- const result = crossSpawn.sync('npm', ['i', '@open-wa/wa-automate'], { stdio: 'inherit' });
113
- if (!result.stderr) {
114
- console.log('UPDATED SUCCESSFULLY');
115
- logging_1.log.info('UPDATED SUCCESSFULLY');
116
- }
117
- console.log('RESTARTING PROCESS');
118
- logging_1.log.info('RESTARTING PROCESS');
119
- process.on("exit", function () {
120
- crossSpawn.spawn(process.argv.shift(), process.argv, {
121
- cwd: process.cwd(),
122
- detached: true,
123
- stdio: "inherit"
124
- });
125
- });
126
- process.exit();
127
- }
128
- }
129
- if (config === null || config === void 0 ? void 0 : config.inDocker) {
130
- //try to infer config variables from process.env
131
- config = Object.assign(Object.assign({}, config), (0, tools_1.getConfigFromProcessEnv)(exports.configWithCases));
132
- config.chromiumArgs = (config === null || config === void 0 ? void 0 : config.chromiumArgs) || [];
133
- customUserAgent = config.customUserAgent;
134
- }
135
- if (sessionId === '' || (config === null || config === void 0 ? void 0 : config.sessionId))
136
- sessionId = (config === null || config === void 0 ? void 0 : config.sessionId) || 'session';
137
- const prettyFont = cfonts_1.default.render(('@OPEN-WA|WHATSAPP|AUTOMATOR'), {
138
- font: '3d',
139
- color: 'candy',
140
- align: 'center',
141
- gradient: ["red", "#f80"],
142
- lineHeight: 3
143
- });
144
- console.log((config === null || config === void 0 ? void 0 : config.disableSpins) ? (0, boxen_1.default)([
145
- `@open-wa/wa-automate `,
146
- `${exports.pkg.description}`,
147
- `Version: ${exports.pkg.version} `,
148
- `Check out the latest changes: https://github.com/open-wa/wa-automate-nodejs#latest-changes `,
149
- ].join('\n'), { padding: 1, borderColor: 'yellow', borderStyle: 'bold' }) : prettyFont.string);
150
- if (config === null || config === void 0 ? void 0 : config.popup) {
151
- const { popup } = yield Promise.resolve().then(() => __importStar(require('./popup')));
152
- const popupaddr = yield popup(config);
153
- console.log(`You can also authenticate the session at: ${popupaddr}`);
154
- logging_1.log.info(`You can also authenticate the session at: ${popupaddr}`);
155
- }
156
- if (!sessionId)
157
- sessionId = 'session';
158
- const spinner = new events_1.Spin(sessionId, 'STARTUP', config === null || config === void 0 ? void 0 : config.disableSpins);
159
- const qrManager = new auth_1.QRManager(config);
160
- const RAM_INFO = `Total: ${parseFloat(`${os.totalmem() / 1000000000}`).toFixed(2)} GB | Free: ${parseFloat(`${os.freemem() / 1000000000}`).toFixed(2)} GB`;
161
- logging_1.log.info("RAM INFO", RAM_INFO);
162
- const PPTR_VERSION = ((_a = (0, fs_extra_1.readJsonSync)(require.resolve("puppeteer/package.json"), { throws: false })) === null || _a === void 0 ? void 0 : _a.version) || "UNKNOWN";
163
- logging_1.log.info("PPTR VERSION INFO", PPTR_VERSION);
164
- try {
165
- if (typeof config === 'string')
166
- console.error("AS OF VERSION 3+ YOU CAN NO LONGER SET THE SESSION ID AS THE FIRST PARAMETER OF CREATE. CREATE CAN ONLY TAKE A CONFIG OBJECT. IF YOU STILL HAVE CONFIGS AS A SECOND PARAMETER, THEY WILL HAVE NO EFFECT! PLEASE SEE DOCS.");
167
- spinner.start('Starting');
168
- spinner.succeed(`Version: ${exports.pkg.version}`);
169
- spinner.info(`Initializing WA`);
170
- /**
171
- * Check if the IGNORE folder exists, therefore, assume that the session is MD.
172
- */
173
- const mdDir = config["userDataDir"] || `${(config === null || config === void 0 ? void 0 : config.sessionDataPath) || ((config === null || config === void 0 ? void 0 : config.inDocker) ? '/sessions' : (config === null || config === void 0 ? void 0 : config.sessionDataPath) || '.')}/_IGNORE_${(config === null || config === void 0 ? void 0 : config.sessionId) || 'session'}`;
174
- if (process.env.AUTO_MD && fs.existsSync(mdDir) && !(config === null || config === void 0 ? void 0 : config.multiDevice)) {
175
- spinner.info(`Multi-Device directory detected. multiDevice set to true.`);
176
- config.multiDevice = true;
177
- }
178
- if ((config === null || config === void 0 ? void 0 : config.multiDevice) && (config === null || config === void 0 ? void 0 : config.chromiumArgs))
179
- spinner.info(`Using custom chromium args with multi device will cause issues! Please remove them: ${config === null || config === void 0 ? void 0 : config.chromiumArgs}`);
180
- if ((config === null || config === void 0 ? void 0 : config.multiDevice) && !(config === null || config === void 0 ? void 0 : config.useChrome))
181
- spinner.info(`It is recommended to set useChrome: true or use the --use-chrome flag if you are experiencing issues with Multi device support`);
182
- waPage = yield (0, browser_1.initPage)(sessionId, config, qrManager, customUserAgent, spinner);
183
- spinner.succeed('Page loaded');
184
- const browserLaunchedTs = (0, tools_1.now)();
185
- const throwOnError = config && config.throwErrorOnTosBlock == true;
186
- const PAGE_UA = yield waPage.evaluate('navigator.userAgent');
187
- const BROWSER_VERSION = yield waPage.browser().version();
188
- const OS = (0, os_name_1.default)();
189
- const START_TS = Date.now();
190
- const screenshotPath = `./logs/${config.sessionId || 'session'}/${START_TS}`;
191
- exports.screenshot = (page) => __awaiter(this, void 0, void 0, function* () {
192
- yield page.screenshot({
193
- path: `${screenshotPath}/${Date.now()}.jpg`
194
- }).catch(() => {
195
- fs.mkdirSync(screenshotPath, { recursive: true });
196
- return (0, exports.screenshot)(page);
197
- });
198
- console.log('Screenshot taken. path:', `${screenshotPath}`);
199
- });
200
- if (config === null || config === void 0 ? void 0 : config.screenshotOnInitializationBrowserError)
201
- waPage.on('console', (msg) => __awaiter(this, void 0, void 0, function* () {
202
- for (let i = 0; i < msg.args().length; ++i)
203
- console.log(`${i}: ${msg.args()[i]}`);
204
- if (msg.type() === 'error' && !msg.text().includes('apify') && !msg.text().includes('crashlogs'))
205
- yield (0, exports.screenshot)(waPage);
206
- }));
207
- const WA_AUTOMATE_VERSION = `${exports.pkg.version}${(notifier === null || notifier === void 0 ? void 0 : notifier.update) && ((notifier === null || notifier === void 0 ? void 0 : notifier.update.latest) !== exports.pkg.version) ? ` UPDATE AVAILABLE: ${notifier === null || notifier === void 0 ? void 0 : notifier.update.latest}` : ''}`;
208
- yield waPage.waitForFunction('window.Debug!=undefined && window.Debug.VERSION!=undefined && require');
209
- //@ts-ignore
210
- const WA_VERSION = yield waPage.evaluate(() => window.Debug ? window.Debug.VERSION : 'I think you have been TOS_BLOCKed');
211
- const canInjectEarly = yield (0, patch_manager_1.earlyInjectionCheck)(waPage);
212
- const attemptingReauth = yield waPage.evaluate(`!!(localStorage['WAToken2'] || localStorage['last-wid-md'])`);
213
- let debugInfo = {
214
- WA_VERSION,
215
- PAGE_UA,
216
- WA_AUTOMATE_VERSION,
217
- BROWSER_VERSION,
218
- OS,
219
- START_TS,
220
- RAM_INFO,
221
- PPTR_VERSION
222
- };
223
- if ((config === null || config === void 0 ? void 0 : config.logDebugInfoAsObject) || (config === null || config === void 0 ? void 0 : config.disableSpins))
224
- spinner.succeed(`Debug info: ${JSON.stringify(debugInfo, null, 2)}`);
225
- else {
226
- console.table(debugInfo);
227
- logging_1.log.info('Debug info:', debugInfo);
228
- }
229
- debugInfo.LATEST_VERSION = !((notifier === null || notifier === void 0 ? void 0 : notifier.update) && ((notifier === null || notifier === void 0 ? void 0 : notifier.update.latest) !== exports.pkg.version));
230
- debugInfo.CLI = process.env.OWA_CLI && true || false;
231
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
232
- spinner.succeed('Use this easy pre-filled link to report an issue: ' + (0, tools_1.generateGHIssueLink)(config, debugInfo));
233
- spinner.info(`Time to injection: ${((0, tools_1.now)() - browserLaunchedTs).toFixed(0)}ms`);
234
- /**
235
- * Atempt to avoid invariant violations
236
- */
237
- const invariantAviodanceTs = (0, tools_1.now)();
238
- yield Promise.race([
239
- waPage.waitForFunction(`(()=>{return require && require("__debug").modulesMap["WAWebCollections"] ? true : false})()`, { timeout: 10000 }).catch(() => { }),
240
- waPage.waitForFunction(`[...document.getElementsByTagName('div')].filter(x=>x.dataset && x.dataset.testid)[0]?.dataset?.testid === 'qrcode'`, { timeout: 10000 }).catch(() => { }),
241
- waPage.waitForFunction(`document.getElementsByTagName('circle').length===1`, { timeout: 10000 }).catch(() => { }) //qr spinner is present
242
- ]);
243
- spinner.info(`Invariant Violation Avoidance: ${((0, tools_1.now)() - invariantAviodanceTs).toFixed(0)}ms`);
244
- if (canInjectEarly) {
245
- if (attemptingReauth)
246
- yield waPage.evaluate(`window.Store = {"Msg": true}`);
247
- spinner.start('Injecting api');
248
- waPage = yield (0, browser_1.injectApi)(waPage, spinner);
249
- spinner.start('WAPI injected');
250
- }
251
- else {
252
- spinner.remove();
253
- if (throwOnError)
254
- throw Error('TOSBLOCK');
255
- }
256
- spinner.start('Authenticating');
257
- const authRace = [];
258
- authRace.push((0, auth_1.isAuthenticated)(waPage).catch(() => { }));
259
- if ((config === null || config === void 0 ? void 0 : config.authTimeout) !== 0) {
260
- authRace.push((0, exports.timeout)((config.authTimeout || config.multiDevice ? 120 : 60) * 1000));
261
- }
262
- const authenticated = yield Promise.race(authRace);
263
- if (authenticated === 'NUKE' && !(config === null || config === void 0 ? void 0 : config.ignoreNuke)) {
264
- //kill the browser
265
- spinner.fail("Session data most likely expired due to manual host account logout. Please re-authenticate this session.");
266
- yield (0, browser_1.kill)(waPage);
267
- if (config === null || config === void 0 ? void 0 : config.deleteSessionDataOnLogout)
268
- yield (0, browser_1.deleteSessionData)(config);
269
- if (config === null || config === void 0 ? void 0 : config.throwOnExpiredSessionData) {
270
- throw new index_1.SessionExpiredError();
271
- }
272
- else
273
- //restart the process with no session data
274
- return create(Object.assign(Object.assign({}, config), { sessionData: authenticated }));
275
- }
276
- /**
277
- * Attempt to preload the license
278
- */
279
- const earlyWid = yield waPage.evaluate(`(localStorage["last-wid"] || '').replace(/"/g,"")`);
280
- const licensePromise = (0, patch_manager_1.getLicense)(config, {
281
- _serialized: earlyWid
282
- }, debugInfo, spinner);
283
- if (authenticated == 'timeout') {
284
- const oorProms = [(0, auth_1.phoneIsOutOfReach)(waPage)];
285
- if ((config === null || config === void 0 ? void 0 : config.oorTimeout) !== 0)
286
- oorProms.push((0, exports.timeout)(((config === null || config === void 0 ? void 0 : config.oorTimeout) || 60) * 1000));
287
- const outOfReach = yield Promise.race(oorProms);
288
- spinner.emit(outOfReach && outOfReach !== 'timeout' ? 'appOffline' : 'authTimeout');
289
- spinner.fail(outOfReach && outOfReach !== 'timeout' ? 'Authentication timed out. Please open the app on the phone. Shutting down' : 'Authentication timed out. Shutting down. Consider increasing authTimeout config variable: https://open-wa.github.io/wa-automate-nodejs/interfaces/configobject.html#authtimeout');
290
- yield (0, browser_1.kill)(waPage);
291
- if (config === null || config === void 0 ? void 0 : config.killProcessOnTimeout)
292
- process.exit();
293
- throw new Error(outOfReach ? 'App Offline' : 'Auth Timeout. Consider increasing authTimeout config variable: https://open-wa.github.io/wa-automate-nodejs/interfaces/configobject.html#authtimeout');
294
- }
295
- if (authenticated) {
296
- spinner.succeed('Authenticated');
297
- }
298
- else {
299
- spinner.info('Authenticate to continue');
300
- const race = [];
301
- if (config === null || config === void 0 ? void 0 : config.linkCode) {
302
- race.push(qrManager.linkCode(waPage, config, spinner));
303
- }
304
- else
305
- race.push(qrManager.smartQr(waPage, config, spinner));
306
- if ((config === null || config === void 0 ? void 0 : config.qrTimeout) !== 0) {
307
- let to = ((config === null || config === void 0 ? void 0 : config.qrTimeout) || 60) * 1000;
308
- if (config === null || config === void 0 ? void 0 : config.multiDevice)
309
- to = to * 2;
310
- race.push((0, exports.timeout)(to));
311
- }
312
- const result = yield Promise.race(race);
313
- if (result === "MULTI_DEVICE_DETECTED" && !(config === null || config === void 0 ? void 0 : config.multiDevice)) {
314
- yield (0, browser_1.kill)(waPage);
315
- return create(Object.assign(Object.assign({}, config), { multiDevice: true }));
316
- }
317
- if (result == 'timeout') {
318
- spinner.emit('qrTimeout');
319
- spinner.fail('QR scan took too long. Session Timed Out. Shutting down. Consider increasing qrTimeout config variable: https://open-wa.github.io/wa-automate-nodejs/interfaces/configobject.html#qrtimeout');
320
- yield (0, browser_1.kill)(waPage);
321
- if (config === null || config === void 0 ? void 0 : config.killProcessOnTimeout)
322
- process.exit();
323
- throw new Error('QR Timeout');
324
- }
325
- spinner.emit('successfulScan');
326
- spinner.succeed();
327
- }
328
- if (config.logInternalEvents)
329
- yield waPage.evaluate("debugEvents=true");
330
- yield waPage.evaluate("window.critlis=true");
331
- const tI = yield (0, tools_1.timePromise)(() => (0, init_patch_1.injectInternalEventHandler)(waPage));
332
- logging_1.log.info(`Injected internal event handler: ${tI} ms`);
333
- if (attemptingReauth) {
334
- yield waPage.evaluate("window.Store = undefined");
335
- if (config === null || config === void 0 ? void 0 : config.waitForRipeSession) {
336
- spinner.start("Waiting for ripe session....");
337
- if (yield (0, auth_1.waitForRipeSession)(waPage, config === null || config === void 0 ? void 0 : config.waitForRipeSessionTimeout))
338
- spinner.succeed("Session ready for injection");
339
- else
340
- spinner.fail("You may experience issues in headless mode. Continuing...");
341
- }
342
- }
343
- const pre = canInjectEarly ? 'Rei' : 'I';
344
- spinner.start(`${pre}njecting api`);
345
- waPage = yield (0, browser_1.injectApi)(waPage, spinner, true);
346
- spinner.succeed(`WAPI ${pre}njected`);
347
- if (canInjectEarly) {
348
- //check if page is valid after 5 seconds
349
- spinner.start('Checking if session is valid');
350
- if (config === null || config === void 0 ? void 0 : config.safeMode) {
351
- yield (0, exports.timeout)(5000);
352
- yield (0, browser_1.injectApi)(waPage, spinner, true);
353
- }
354
- }
355
- //@ts-ignore
356
- const VALID_SESSION = yield waPage.waitForFunction(`window.Store && window.Store.Msg ? true : false`, { timeout: 9000, polling: 200 }).catch((e) => __awaiter(this, void 0, void 0, function* () {
357
- logging_1.log.error("Valid session check failed", e);
358
- return false;
359
- }));
360
- if (VALID_SESSION) {
361
- /**
362
- * Session is valid, attempt to preload patches
363
- */
364
- const patchPromise = (0, patch_manager_1.getPatch)(config, spinner, debugInfo);
365
- spinner.succeed('Client is ready');
366
- const localStorage = JSON.parse(yield waPage.evaluate(() => {
367
- return JSON.stringify(window.localStorage);
368
- }));
369
- const stdSessionJsonPath = ((config === null || config === void 0 ? void 0 : config.sessionDataPath) && (config === null || config === void 0 ? void 0 : config.sessionDataPath.includes('.data.json'))) ? path.join(path.resolve(process.cwd(), (config === null || config === void 0 ? void 0 : config.sessionDataPath) || '')) : path.join(path.resolve(process.cwd(), (config === null || config === void 0 ? void 0 : config.sessionDataPath) || ''), `${sessionId || 'session'}.data.json`);
370
- const altMainModulePath = ((_b = require === null || require === void 0 ? void 0 : require.main) === null || _b === void 0 ? void 0 : _b.path) || ((_c = process === null || process === void 0 ? void 0 : process.mainModule) === null || _c === void 0 ? void 0 : _c.path);
371
- const altSessionJsonPath = !altMainModulePath ? null : ((config === null || config === void 0 ? void 0 : config.sessionDataPath) && (config === null || config === void 0 ? void 0 : config.sessionDataPath.includes('.data.json'))) ? path.join(path.resolve(altMainModulePath, (config === null || config === void 0 ? void 0 : config.sessionDataPath) || '')) : path.join(path.resolve(altMainModulePath, (config === null || config === void 0 ? void 0 : config.sessionDataPath) || ''), `${sessionId || 'session'}.data.json`);
372
- const sessionjsonpath = altSessionJsonPath && fs.existsSync(altSessionJsonPath) ? altSessionJsonPath : stdSessionJsonPath;
373
- const sessionData = {
374
- WABrowserId: localStorage.WABrowserId,
375
- WASecretBundle: localStorage.WASecretBundle,
376
- WAToken1: localStorage.WAToken1,
377
- WAToken2: localStorage.WAToken2
378
- };
379
- if (config.multiDevice) {
380
- delete sessionData.WABrowserId;
381
- logging_1.log.info("Multi-device detected. Removing Browser ID from session data to prevent session reauth corruption");
382
- }
383
- const sdB64 = Buffer.from(JSON.stringify(sessionData)).toString('base64');
384
- spinner.emit(sessionData, "sessionData");
385
- spinner.emit(sdB64, "sessionDataBase64");
386
- if (!(config === null || config === void 0 ? void 0 : config.skipSessionSave))
387
- fs.writeFile(sessionjsonpath, sdB64, (err) => {
388
- if (err) {
389
- console.error(err);
390
- return;
391
- }
392
- });
393
- if (config === null || config === void 0 ? void 0 : config.sessionDataBucketAuth) {
394
- try {
395
- spinner === null || spinner === void 0 ? void 0 : spinner.info('Uploading new session data to cloud storage..');
396
- yield (0, pico_s3_1.upload)(Object.assign(Object.assign({ directory: '_sessionData' }, JSON.parse(Buffer.from(config.sessionDataBucketAuth, 'base64').toString('ascii'))), { filename: `${config.sessionId || 'session'}.data.json`, file: `data:text/plain;base64,${Buffer.from(sdB64).toString('base64')}` }));
397
- spinner === null || spinner === void 0 ? void 0 : spinner.succeed('Successfully uploaded session data file to cloud storage!');
398
- }
399
- catch (error) {
400
- spinner === null || spinner === void 0 ? void 0 : spinner.fail(`Something went wrong while uploading new session data to cloud storage bucket. Continuing...`);
401
- }
402
- }
403
- /**
404
- * Set page-level logging
405
- */
406
- waPage.on('console', msg => {
407
- if (config === null || config === void 0 ? void 0 : config.logConsole)
408
- console.log(msg);
409
- logging_1.log.info('Page Console:', msg.text());
410
- });
411
- waPage.on('error', error => {
412
- if (config === null || config === void 0 ? void 0 : config.logConsoleErrors)
413
- console.error(error);
414
- logging_1.log.error('Page Console Error:', error.message || (error === null || error === void 0 ? void 0 : error.text()));
415
- });
416
- if (config === null || config === void 0 ? void 0 : config.restartOnCrash)
417
- waPage.on('error', (error) => __awaiter(this, void 0, void 0, function* () {
418
- console.error('Page Crashed! Restarting...', error);
419
- yield (0, browser_1.kill)(waPage);
420
- yield create(config).then(config.restartOnCrash);
421
- }));
422
- const pureWAPI = yield (0, launch_checks_1.checkWAPIHash)();
423
- if (!pureWAPI) {
424
- config.skipBrokenMethodsCheck = true;
425
- // config.skipPatches = true;
426
- }
427
- if (config === null || config === void 0 ? void 0 : config.hostNotificationLang) {
428
- yield waPage.evaluate(`window.hostlang="${config.hostNotificationLang}"`);
429
- }
430
- //patch issues with wapi.js
431
- if (!(config === null || config === void 0 ? void 0 : config.skipPatches)) {
432
- yield (0, patch_manager_1.getAndInjectLivePatch)(waPage, spinner, yield patchPromise, config, debugInfo);
433
- debugInfo.OW_KEY = yield waPage.evaluate(`window.o()`);
434
- }
435
- const NUM = ((yield waPage.evaluate(`(window.moi() || "").replace('@c.us','').replace(/"/g,"")`)) || "");
436
- debugInfo.NUM = NUM.slice(-4);
437
- debugInfo.NUM_HASH = (0, crypto_1.createHash)('md5').update(NUM, 'utf8').digest('hex');
438
- if ((config === null || config === void 0 ? void 0 : config.skipBrokenMethodsCheck) !== true)
439
- yield (0, launch_checks_1.integrityCheck)(waPage, notifier, spinner, debugInfo);
440
- const LAUNCH_TIME_MS = Date.now() - START_TIME;
441
- debugInfo = Object.assign(Object.assign({}, debugInfo), { LAUNCH_TIME_MS });
442
- spinner.emit(debugInfo, "DebugInfo");
443
- //@ts-ignore
444
- const metrics = yield waPage.evaluate(({ config }) => WAPI.launchMetrics(config), { config });
445
- const purgedMessage = (metrics === null || metrics === void 0 ? void 0 : metrics.purged) ? Object.entries(metrics.purged).filter(([, e]) => Number(e) > 0).map(([k, e]) => `${e} ${k}`).join(" and ") : "";
446
- if (metrics.isMd && !(config === null || config === void 0 ? void 0 : config.multiDevice))
447
- spinner.info("!!!Please set multiDevice: true in the config or use the --mutli-Device flag!!!");
448
- spinner.succeed(`Client loaded for ${metrics.isBiz ? "business" : "normal"} account ${metrics.isMd && "[MD] " || ''}with ${metrics.contacts} contacts, ${metrics.chats} chats & ${metrics.messages} messages ${purgedMessage ? `+ purged ${purgedMessage} ` : ``}in ${LAUNCH_TIME_MS / 1000}s`);
449
- debugInfo.ACC_TYPE = metrics.isBiz ? "BUSINESS" : "PERSONAL";
450
- if ((config === null || config === void 0 ? void 0 : config.deleteSessionDataOnLogout) || (config === null || config === void 0 ? void 0 : config.killClientOnLogout))
451
- config.eventMode = true;
452
- const client = new Client_1.Client(waPage, config, Object.assign(Object.assign({}, debugInfo), metrics));
453
- const { me } = yield client.getMe();
454
- const licIndex = process.argv.findIndex(arg => arg === "--license-key" || arg === "-l");
455
- config.licenseKey = config.licenseKey || licIndex !== -1 && process.argv[licIndex + 1];
456
- if ((config === null || config === void 0 ? void 0 : config.licenseKey) || me._serialized !== earlyWid) {
457
- yield (0, patch_manager_1.getAndInjectLicense)(waPage, config, me, debugInfo, spinner, me._serialized !== earlyWid ? false : yield licensePromise);
458
- }
459
- spinner.info("Finalizing web session...");
460
- yield (0, init_patch_1.injectInitPatch)(waPage);
461
- spinner.info("Finalizing client...");
462
- yield client.loaded();
463
- if (config.ensureHeadfulIntegrity && !attemptingReauth) {
464
- spinner.info("QR scanned for the first time. Refreshing...");
465
- yield client.refresh();
466
- spinner.info("Session refreshed.");
467
- }
468
- const issueLink = yield client.getIssueLink();
469
- console.log((0, boxen_1.default)("Use the link below to easily report issues:👇👇👇", { padding: 1, borderColor: 'red' }));
470
- spinner.succeed(issueLink);
471
- spinner.succeed(`🚀 @OPEN-WA ready for account: ${me.user.slice(-4)}`);
472
- if (!debugInfo.CLI && !config.licenseKey)
473
- spinner.succeed(`Use this link to get a license: ${yield client.getLicenseLink()}`);
474
- spinner.emit('SUCCESS');
475
- spinner.remove();
476
- return client;
477
- }
478
- else {
479
- const storeKeys = yield waPage.evaluate(`Object.keys(window.Store || {})`);
480
- logging_1.log.info("Store keys", storeKeys);
481
- spinner.fail('The session is invalid. Retrying');
482
- yield (0, browser_1.kill)(waPage);
483
- return yield create(config);
484
- }
485
- }
486
- catch (error) {
487
- spinner.emit(error.message);
488
- logging_1.log.error(error.message);
489
- if (error.stack) {
490
- logging_1.log.error(error.stack);
491
- console.error(error.stack);
492
- }
493
- yield (0, browser_1.kill)(waPage);
494
- if (error.name === "ProtocolError" && ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes("Target closed"))) {
495
- spinner.fail(error.message);
496
- process.exit();
497
- }
498
- if (error.name === "TimeoutError" && (config === null || config === void 0 ? void 0 : config.multiDevice)) {
499
- spinner.fail(`Please delete the ${config === null || config === void 0 ? void 0 : config.userDataDir} folder and any related data.json files and try again. It is highly suggested to set useChrome: true also.`);
500
- }
501
- if (error.name === "TimeoutError" && (config === null || config === void 0 ? void 0 : config.killProcessOnTimeout)) {
502
- process.exit();
503
- }
504
- else {
505
- spinner.remove();
506
- throw error;
507
- }
508
- }
509
- });
510
- }
511
- exports.create = create;
@@ -1,8 +0,0 @@
1
- import { JsonObject } from 'type-fest';
2
- import { Page } from 'puppeteer';
3
- import { Spin } from './events';
4
- import { SessionInfo } from '../api/model/sessionInfo';
5
- export declare function checkWAPIHash(): Promise<boolean>;
6
- export declare function integrityCheck(waPage: Page, notifier: {
7
- update: JsonObject;
8
- }, spinner: Spin, debugInfo: SessionInfo): Promise<boolean>;
@@ -1,130 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __importDefault = (this && this.__importDefault) || function (mod) {
35
- return (mod && mod.__esModule) ? mod : { "default": mod };
36
- };
37
- Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.integrityCheck = exports.checkWAPIHash = void 0;
39
- const path = __importStar(require("path"));
40
- const hasha_1 = __importDefault(require("hasha"));
41
- const lodash_uniq_1 = __importDefault(require("lodash.uniq"));
42
- const fs_extra_1 = require("fs-extra");
43
- const fs = __importStar(require("fs"));
44
- const pkg = (0, fs_extra_1.readJsonSync)(path.join(__dirname, '../../package.json'));
45
- const currentHash = '8d3a09fe3156605ac2cf55ce920bbbab';
46
- function checkWAPIHash() {
47
- return __awaiter(this, void 0, void 0, function* () {
48
- const h = yield hasha_1.default.fromFile(path.join(__dirname, '../lib', 'wapi.js'), { algorithm: 'md5' });
49
- return h == currentHash;
50
- });
51
- }
52
- exports.checkWAPIHash = checkWAPIHash;
53
- function integrityCheck(waPage, notifier, spinner, debugInfo) {
54
- return __awaiter(this, void 0, void 0, function* () {
55
- const waitForIdle = catchRequests(waPage);
56
- spinner.start('Checking client integrity');
57
- yield waitForIdle();
58
- const wapi = fs.readFileSync(path.join(__dirname, '../lib', 'wapi.js'), 'utf8');
59
- const methods = (0, lodash_uniq_1.default)(wapi.match(/(Store[.\w]*)\(/g).map((x) => x.replace("(", "")));
60
- const check = () => __awaiter(this, void 0, void 0, function* () {
61
- return yield waPage.evaluate((checkList) => {
62
- return checkList.filter(check => {
63
- try {
64
- return eval(check) ? false : true;
65
- }
66
- catch (error) {
67
- return true;
68
- }
69
- });
70
- }, methods);
71
- });
72
- let BROKEN_METHODS = yield check();
73
- if (BROKEN_METHODS.length > 0) {
74
- spinner.info('Broken methods detected. Attempting repair.');
75
- yield new Promise(resolve => setTimeout(resolve, 2500));
76
- //attempting repair
77
- const unconditionalInject = wapi.replace('!window.Store||!window.Store.Msg', 'true');
78
- yield waPage.evaluate(s => eval(s), unconditionalInject);
79
- yield waitForIdle();
80
- //check again
81
- BROKEN_METHODS = yield check();
82
- if (BROKEN_METHODS.length > 0) {
83
- spinner.info('Unable to repair. Reporting broken methods.');
84
- //report broken methods:
85
- if (notifier === null || notifier === void 0 ? void 0 : notifier.update) {
86
- //needs an updated
87
- spinner.fail("!!!BROKEN METHODS DETECTED!!!\n\n Please update to the latest version: " + notifier.update.latest);
88
- }
89
- else {
90
- //hmm latest version
91
- const axios = (yield Promise.resolve().then(() => __importStar(require('axios')))).default;
92
- const report = yield axios.post(pkg.brokenMethodReportUrl, Object.assign(Object.assign({}, debugInfo), { BROKEN_METHODS })).catch(() => false);
93
- if (report === null || report === void 0 ? void 0 : report.data) {
94
- spinner.fail(`Unable to repair broken methods. Sometimes this happens the first time after a new WA version, please try again. An issue has been created, add more detail if required: ${report === null || report === void 0 ? void 0 : report.data}`);
95
- }
96
- else
97
- spinner.fail(`Unable to repair broken methods. Sometimes this happens the first time after a new WA version, please try again. Please check the issues in the repo for updates: https://github.com/open-wa/wa-automate-nodejs/issues`);
98
- }
99
- }
100
- else
101
- spinner.info('Session repaired.');
102
- }
103
- else
104
- spinner.info('Passed Integrity Test');
105
- return true;
106
- });
107
- }
108
- exports.integrityCheck = integrityCheck;
109
- function catchRequests(page, reqs = 0) {
110
- const started = () => (reqs = reqs + 1);
111
- const ended = () => (reqs = reqs - 1);
112
- page.on('request', started);
113
- page.on('requestfailed', ended);
114
- page.on('requestfinished', ended);
115
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
116
- return (timeout = 5000, success = false) => __awaiter(this, void 0, void 0, function* () {
117
- // eslint-disable-next-line no-constant-condition
118
- while (true) {
119
- if (reqs < 1)
120
- break;
121
- yield new Promise((yay) => setTimeout(yay, 100));
122
- if ((timeout = timeout - 100) < 0) {
123
- throw new Error('Timeout');
124
- }
125
- }
126
- page.off('request', started);
127
- page.off('requestfailed', ended);
128
- page.off('requestfinished', ended);
129
- });
130
- }