iobroker.javascript 8.9.2 → 9.0.0

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 (119) hide show
  1. package/README.md +7 -3
  2. package/admin/assets/{createSvgIcon-BdRvDw53.js → createSvgIcon-BQT-7-GS.js} +1 -1
  3. package/admin/assets/{docs-6na4NFtj.js → docs-BrInh2Pn.js} +2 -2
  4. package/admin/assets/index-B0RKH_iG.js +1329 -0
  5. package/admin/assets/index-CfuHVX2B.js +193 -0
  6. package/admin/assets/index-CuCs5aLs.js +5 -0
  7. package/admin/assets/index-tExaxF69.js +930 -0
  8. package/admin/assets/inheritsLoose--KnFDOw1.js +36 -0
  9. package/admin/assets/{useTheme-Cl1QmYFL.js → useTheme-DF6qfrtI.js} +1 -1
  10. package/admin/custom/assets/{Components-ChpTW7sE.js → Components-D9kRsHNY.js} +1 -1
  11. package/admin/custom/assets/{DefaultPropsProvider-CHpMCMgA.js → DefaultPropsProvider-9qubdy-V.js} +2 -2
  12. package/admin/custom/assets/{FilledInput-CtcQVKyj.js → FilledInput-BpuM_GyB.js} +1 -1
  13. package/admin/custom/assets/Tabs-CvEv0KOT.js +138 -0
  14. package/admin/custom/assets/ThemeProvider-DZTpMR8n.js +29 -0
  15. package/admin/custom/assets/{createSvgIcon-C_vAELFU.js → createSvgIcon-BQThUM-f.js} +1 -1
  16. package/admin/custom/assets/hostInit-CrAs5YZS.js +1 -1
  17. package/admin/custom/assets/{index-DwsbskQy.js → index-DIWNdd4a.js} +1 -1
  18. package/admin/custom/assets/index-DZqbj5K4.js +55 -0
  19. package/admin/custom/assets/{index-D5apCzjJ.js → index-Dbe-II7_.js} +6 -6
  20. package/admin/custom/assets/index-az76fZMP.js +904 -0
  21. package/admin/custom/assets/index-sawv1cUe.js +1399 -0
  22. package/admin/custom/assets/{virtualExposes-BPncCdUy.js → virtualExposes-BMKIjWrE.js} +2 -2
  23. package/admin/custom/customComponents.js +2 -2
  24. package/admin/custom/i18n/de.json +29 -29
  25. package/admin/custom/i18n/es.json +29 -29
  26. package/admin/custom/i18n/fr.json +29 -29
  27. package/admin/custom/i18n/it.json +29 -29
  28. package/admin/custom/i18n/nl.json +29 -29
  29. package/admin/custom/i18n/pl.json +29 -29
  30. package/admin/custom/i18n/pt.json +29 -29
  31. package/admin/custom/i18n/ru.json +29 -29
  32. package/admin/custom/i18n/uk.json +29 -29
  33. package/admin/custom/i18n/zh-cn.json +29 -29
  34. package/admin/google-blockly/blockly_compressed.js +875 -887
  35. package/admin/google-blockly/blocks_compressed.js +38 -41
  36. package/admin/google-blockly/javascript_compressed.js +19 -54
  37. package/admin/google-blockly/media/delete-icon.svg +1 -0
  38. package/admin/google-blockly/media/foldout-icon.svg +1 -0
  39. package/admin/google-blockly/media/resize-handle.svg +3 -0
  40. package/admin/jsonConfig.json +2 -0
  41. package/admin/mf-manifest.json +1 -1
  42. package/admin/remoteEntry.js +2 -2
  43. package/admin/tab.html +4 -4
  44. package/admin/vsFont/README.md +1 -1
  45. package/admin/vsFont/createJson.js +1 -1
  46. package/build-backend/lib/consts.js +346 -0
  47. package/build-backend/lib/consts.js.map +1 -0
  48. package/build-backend/lib/convert.js +120 -0
  49. package/build-backend/lib/convert.js.map +1 -0
  50. package/build-backend/lib/debug.js +163 -0
  51. package/build-backend/lib/debug.js.map +1 -0
  52. package/{lib → build-backend/lib}/debugger.js +261 -232
  53. package/build-backend/lib/debugger.js.map +1 -0
  54. package/build-backend/lib/eventObj.js +177 -0
  55. package/build-backend/lib/eventObj.js.map +1 -0
  56. package/build-backend/lib/inspect.js +728 -0
  57. package/build-backend/lib/inspect.js.map +1 -0
  58. package/build-backend/lib/javascript.d.ts +1972 -0
  59. package/{lib → build-backend/lib}/mirror.js +185 -182
  60. package/build-backend/lib/mirror.js.map +1 -0
  61. package/build-backend/lib/nodeModulesManagement.js +25 -0
  62. package/build-backend/lib/nodeModulesManagement.js.map +1 -0
  63. package/build-backend/lib/patternCompareFunctions.js +321 -0
  64. package/build-backend/lib/patternCompareFunctions.js.map +1 -0
  65. package/build-backend/lib/protectFs.js +477 -0
  66. package/build-backend/lib/protectFs.js.map +1 -0
  67. package/build-backend/lib/request.js +89 -0
  68. package/build-backend/lib/request.js.map +1 -0
  69. package/{lib → build-backend/lib}/sandbox.js +2046 -1852
  70. package/build-backend/lib/sandbox.js.map +1 -0
  71. package/build-backend/lib/scheduler.js +553 -0
  72. package/build-backend/lib/scheduler.js.map +1 -0
  73. package/build-backend/lib/tools.js +183 -0
  74. package/build-backend/lib/tools.js.map +1 -0
  75. package/build-backend/lib/typescriptSettings.js +39 -0
  76. package/build-backend/lib/typescriptSettings.js.map +1 -0
  77. package/build-backend/lib/typescriptTools.js +435 -0
  78. package/build-backend/lib/typescriptTools.js.map +1 -0
  79. package/build-backend/lib/utils.js +66 -0
  80. package/build-backend/lib/utils.js.map +1 -0
  81. package/{lib → build-backend/lib}/words.js +23 -30
  82. package/build-backend/lib/words.js.map +1 -0
  83. package/build-backend/main.js +2671 -0
  84. package/build-backend/main.js.map +1 -0
  85. package/build-backend/types.d.ts +742 -0
  86. package/docs/de/README.md +1 -1
  87. package/docs/en/README.md +1 -1
  88. package/docs/en/javascript.md +10 -6
  89. package/docs/ru/README.md +1 -1
  90. package/install/installTypings.js +34 -47
  91. package/io-package.json +14 -14
  92. package/package.json +14 -14
  93. package/admin/assets/index-DCkkMRRa.js +0 -1335
  94. package/admin/assets/index-DJfSBoBB.js +0 -192
  95. package/admin/assets/index-DTiA4WdK.js +0 -930
  96. package/admin/assets/index-qABB1JVe.js +0 -5
  97. package/admin/assets/inheritsLoose-BW-3V39H.js +0 -36
  98. package/admin/custom/assets/Tabs-C1KOyWRi.js +0 -137
  99. package/admin/custom/assets/ThemeProvider-Buvx5nSd.js +0 -29
  100. package/admin/custom/assets/index-BGCRznKh.js +0 -904
  101. package/admin/custom/assets/index-DfBPYXqA.js +0 -55
  102. package/admin/custom/assets/index-jIr6kOLK.js +0 -1398
  103. package/lib/adapter-config.d.ts +0 -16
  104. package/lib/consts.js +0 -83
  105. package/lib/convert.js +0 -106
  106. package/lib/debug.js +0 -154
  107. package/lib/eventObj.js +0 -201
  108. package/lib/inspect.js +0 -688
  109. package/lib/javascript.d.ts +0 -1858
  110. package/lib/nodeModulesManagement.js +0 -26
  111. package/lib/patternCompareFunctions.js +0 -391
  112. package/lib/protectFs.js +0 -401
  113. package/lib/request.js +0 -72
  114. package/lib/scheduler.js +0 -447
  115. package/lib/tools.js +0 -192
  116. package/lib/typescriptSettings.js +0 -44
  117. package/lib/typescriptTools.js +0 -529
  118. package/lib/utils.js +0 -87
  119. package/main.js +0 -2653
package/lib/inspect.js DELETED
@@ -1,688 +0,0 @@
1
- /*
2
- * Copyright Node.js contributors. All rights reserved.
3
- *
4
- * Permission is hereby granted, free of charge, to any person obtaining a copy
5
- * of this software and associated documentation files (the "Software"), to
6
- * deal in the Software without restriction, including without limitation the
7
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
8
- * sell copies of the Software, and to permit persons to whom the Software is
9
- * furnished to do so, subject to the following conditions:
10
- *
11
- * The above copyright notice and this permission notice shall be included in
12
- * all copies or substantial portions of the Software.
13
- *
14
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
20
- * IN THE SOFTWARE.
21
- */
22
- 'use strict';
23
- const { spawn } = require('node:child_process');
24
- const { EventEmitter } = require('node:events');
25
- const net = require('node:net');
26
- const util = require('node:util');
27
- const path = require('node:path');
28
- const fs = require('node:fs');
29
-
30
- let breakOnStart;
31
- for (let i = 0; i < process.argv.length; i++) {
32
- if (process.argv[i] === '--breakOnStart') {
33
- breakOnStart = true;
34
- }
35
- }
36
-
37
- //const runAsStandalone = typeof __dirname !== 'undefined';
38
-
39
- const InspectClient = require('node-inspect/lib/internal/inspect_client');
40
- const createRepl = require('./debugger');
41
-
42
- const debuglog = util.debuglog('inspect');
43
-
44
- class StartupError extends Error {
45
- constructor(message) {
46
- super(message);
47
- this.name = 'StartupError';
48
- }
49
- }
50
-
51
- function portIsFree(host, port, timeout = 9999) {
52
- if (port === 0) {
53
- // Binding to a random port.
54
- return Promise.resolve();
55
- }
56
-
57
- const retryDelay = 150;
58
- let didTimeOut = false;
59
-
60
- return new Promise((resolve, reject) => {
61
- setTimeout(() => {
62
- didTimeOut = true;
63
- reject(new StartupError(
64
- `Timeout (${timeout}) waiting for ${host}:${port} to be free`));
65
- }, timeout);
66
-
67
- function pingPort() {
68
- if (didTimeOut) return;
69
-
70
- const socket = net.connect(port, host);
71
- let didRetry = false;
72
- function retry() {
73
- if (!didRetry && !didTimeOut) {
74
- didRetry = true;
75
- setTimeout(pingPort, retryDelay);
76
- }
77
- }
78
-
79
- socket.on('error', (error) => {
80
- if (error.code === 'ECONNREFUSED') {
81
- resolve();
82
- } else {
83
- retry();
84
- }
85
- });
86
- socket.on('connect', () => {
87
- socket.destroy();
88
- retry();
89
- });
90
- }
91
- pingPort();
92
- });
93
- }
94
-
95
- function runScript(script, scriptArgs, inspectHost, inspectPort, childPrint) {
96
- script = path.normalize(script);
97
- return portIsFree(inspectHost, inspectPort)
98
- .then(() => {
99
- return new Promise((resolve) => {
100
- const args = [breakOnStart ? `--inspect-brk=${inspectPort}` : `--inspect=${inspectPort}`].concat([script], scriptArgs);
101
- const child = spawn(process.execPath, args);
102
- child.stdout.setEncoding('utf8');
103
- child.stderr.setEncoding('utf8');
104
- child.stdout.on('data', childPrint);
105
- child.stderr.on('data', text => childPrint(text, true));
106
-
107
- let output = '';
108
- function waitForListenHint(text) {
109
- output += text;
110
- if (/Debugger listening on ws:\/\/\[?(.+?)]?:(\d+)\//.test(output)) {
111
- const host = RegExp.$1;
112
- const port = Number.parseInt(RegExp.$2);
113
- child.stderr.removeListener('data', waitForListenHint);
114
- resolve([child, port, host]);
115
- }
116
- }
117
-
118
- child.stderr.on('data', waitForListenHint);
119
- });
120
- });
121
- }
122
-
123
- function createAgentProxy(domain, client) {
124
- const agent = new EventEmitter();
125
- agent.then = (...args) => {
126
- // TODO: potentially fetch the protocol and pretty-print it here.
127
- const descriptor = {
128
- [util.inspect.custom](depth, { stylize }) {
129
- return stylize(`[Agent ${domain}]`, 'special');
130
- },
131
- };
132
- return Promise.resolve(descriptor).then(...args);
133
- };
134
-
135
- return new Proxy(agent, {
136
- get(target, name) {
137
- if (name in target) return target[name];
138
- return function callVirtualMethod(params) {
139
- return client.callMethod(`${domain}.${name}`, params);
140
- };
141
- },
142
- });
143
- }
144
-
145
- class NodeInspector {
146
- constructor(options, stdin, stdout) {
147
- this.options = options;
148
- this.stdin = stdin;
149
- this.stdout = stdout;
150
- this.scripts = {};
151
- this.deleyedContext = null;
152
-
153
- this.paused = true;
154
- this.child = null;
155
-
156
- if (options.script) {
157
- this._runScript = runScript.bind(null,
158
- options.script,
159
- options.scriptArgs,
160
- options.host,
161
- options.port,
162
- this.childPrint.bind(this),
163
- );
164
- } else {
165
- this._runScript =
166
- () => Promise.resolve([null, options.port, options.host]);
167
- }
168
-
169
- this.client = new InspectClient();
170
-
171
- this.domainNames = ['Debugger', 'HeapProfiler', 'Profiler', 'Runtime'];
172
-
173
- this.domainNames.forEach(domain =>
174
- this[domain] = createAgentProxy(domain, this.client));
175
-
176
- this.handleDebugEvent = (fullName, params) => {
177
- const [domain, name] = fullName.split('.');
178
-
179
- if (domain === 'Debugger' && name === 'scriptParsed') {
180
- // console.log(`Parsed: ${params.url}`);
181
- if ((scriptToDebug && params.url.includes(scriptToDebug)) || (instanceToDebug && params.url.includes(instanceToDebug))) {
182
- console.log(`My scriptID: ${params.scriptId}`);
183
- this.mainScriptId = params.scriptId;
184
- this.mainFile = params.url.replace('file:///', '');
185
- // load text of a script
186
- this.scripts[this.mainScriptId] = this.Debugger.getScriptSource({ scriptId: this.mainScriptId })
187
- .then(script => ({ script: script.scriptSource, scriptId: this.mainScriptId }));
188
-
189
- // sometimes the pause event comes before scriptParsed
190
- if (this.deleyedContext) {
191
- console.log('Send to debugger: readyToDebug');
192
- this.scripts[this.mainScriptId]
193
- .then(data => {
194
- // console.log('Send to debugger: readyToDebug ' + JSON.stringify(data));
195
- sendToHost({
196
- cmd: 'readyToDebug',
197
- scriptId: this.mainScriptId,
198
- script: data.script,
199
- context: this.deleyedContext,
200
- url: this.mainFile
201
- });
202
- this.deleyedContext = null;
203
- });
204
- }
205
- }
206
- return;
207
- } else if (domain === 'Debugger' && name === 'resumed') {
208
- this.Debugger.emit(name, params);
209
- sendToHost({ cmd: 'resumed', context: params });
210
- return;
211
- } else if (domain === 'Debugger' && name === 'paused') {
212
- console.log(`PAUSED!! ${alreadyPausedOnFirstLine}`);
213
- if (!alreadyPausedOnFirstLine && params.reason === 'exception') {
214
- // ignore all exceptions by start
215
- this.Debugger.resume();
216
- return;
217
- }
218
- //console.warn(fullName + ': => \n' + JSON.stringify(params, null, 2));
219
- this.Debugger.emit(name, params);
220
-
221
- if (!alreadyPausedOnFirstLine) {
222
- alreadyPausedOnFirstLine = true;
223
- // sometimes the pause event comes before scriptParsed
224
- if (this.mainScriptId && this.scripts[this.mainScriptId]) {
225
- this.scripts[this.mainScriptId]
226
- .then(data =>
227
- sendToHost({ cmd: 'readyToDebug', scriptId: data.scriptId, script: data.script, context: params, url: this.mainFile }));
228
- } else {
229
- // store context to send it later when script ID will be known
230
- this.deleyedContext = params;
231
- console.log('PAUSED, but no scriptId');
232
- }
233
- } else {
234
- // this.scripts[params.loca]
235
- // .then(data =>
236
- sendToHost({ cmd: 'paused', context: params });
237
- }
238
- return;
239
- }
240
-
241
- if (domain === 'Runtime') {
242
- //console.warn(fullName + ': => \n' + JSON.stringify(params, null, 2));
243
- }
244
- if (domain === 'Runtime' && name === 'consoleAPICalled') {
245
- const text = params.args[0].value;
246
- if (instanceToDebug) {
247
- sendToHost({ cmd: 'log', severity: params.type === 'warning' ? 'warn' : 'error', text, ts: Date.now() });
248
- } else if (text.includes(`$$${scriptToDebug}$$`)) {
249
- console.log(`${fullName} [${params.executionContextId}]: => ${text}`);
250
- const [severity, _text] = text.split(`$$${scriptToDebug}$$`);
251
- sendToHost({ cmd: 'log', severity, text: _text, ts: params.args[1] && params.args[1].value ? params.args[1].value : Date.now() });
252
- } else if (params.type === 'warning' || params.type === 'error') {
253
- sendToHost({
254
- cmd: 'log',
255
- severity: params.type === 'warning' ? 'warn' : 'error',
256
- text,
257
- ts: Date.now(),
258
- });
259
- }
260
- return;
261
- } else if (domain === 'Runtime' && (params.id === 2 || params.executionContextId === 2)) {
262
- if (name === 'executionContextCreated') {
263
- console.warn(`${fullName}: =>\n${JSON.stringify(params, null, 2)}`);
264
- } else if (name === 'executionContextDestroyed') {
265
- console.warn(`${fullName}: =>\n${JSON.stringify(params, null, 2)}`);
266
- sendToHost({ cmd: 'finished', context: params });
267
- }
268
- return;
269
- } else if (domain === 'Runtime' && name === 'executionContextDestroyed' && params.executionContextId === 1) {
270
- sendToHost({ cmd: 'finished', context: params });
271
- console.log('Exited!');
272
- setTimeout(() =>
273
- process.exit(125), 200);
274
- } else if (domain === 'Debugger' && name === 'scriptFailedToParse') {
275
- // ignore
276
- return;
277
- }
278
-
279
- console.warn(`${fullName}: =>\n${JSON.stringify(params, null, 2)}`);
280
-
281
- /*if (domain in this) {
282
- this[domain].emit(name, params);
283
- }*/
284
- };
285
- this.client.on('debugEvent', this.handleDebugEvent);
286
- const startRepl = createRepl(this);
287
-
288
- // Handle all possible exits
289
- process.on('exit', () => this.killChild());
290
- process.once('SIGTERM', process.exit.bind(process, 0));
291
- process.once('SIGHUP', process.exit.bind(process, 0));
292
-
293
- this.run()
294
- .then(() => startRepl())
295
- .then((repl) => {
296
- this.repl = repl;
297
- this.repl.on('exit', () =>
298
- process.exit(0));
299
- this.paused = false;
300
- })
301
- .then(null, (error) => process.nextTick(() => { throw error; }));
302
- }
303
-
304
- suspendReplWhile(fn) {
305
- if (this.repl) {
306
- this.repl.pause();
307
- }
308
- this.stdin.pause();
309
- this.paused = true;
310
-
311
- return new Promise(resolve => resolve(fn()))
312
- .then(() => {
313
- this.paused = false;
314
- if (this.repl) {
315
- this.repl.resume();
316
- this.repl.displayPrompt();
317
- }
318
- this.stdin.resume();
319
- })
320
- .then(null, error => process.nextTick(() => { throw error; }));
321
- }
322
-
323
- killChild() {
324
- this.client.reset();
325
- if (this.child) {
326
- this.child.kill();
327
- this.child = null;
328
- }
329
- }
330
-
331
- run() {
332
- this.killChild();
333
-
334
- return this._runScript().then(([child, port, host]) => {
335
- this.child = child;
336
-
337
- let connectionAttempts = 0;
338
- const attemptConnect = () => {
339
- ++connectionAttempts;
340
- debuglog('connection attempt #%d', connectionAttempts);
341
- this.stdout.write('.');
342
- return this.client.connect(port, host)
343
- .then(() => {
344
- debuglog('connection established');
345
- this.stdout.write(' ok');
346
- }, error => {
347
- debuglog('connect failed', error);
348
- // If it's failed to connect 10 times, then print a failed message
349
- if (connectionAttempts >= 10) {
350
- this.stdout.write(' failed to connect, please retry\n');
351
- process.exit(1);
352
- }
353
-
354
- return new Promise((resolve) => setTimeout(resolve, 500))
355
- .then(attemptConnect);
356
- });
357
- };
358
-
359
- this.print(`connecting to ${host}:${port} ..`, true);
360
- return attemptConnect();
361
- });
362
- }
363
-
364
- clearLine() {
365
- if (this.stdout.isTTY) {
366
- this.stdout.cursorTo(0);
367
- this.stdout.clearLine(1);
368
- } else {
369
- this.stdout.write('\b');
370
- }
371
- }
372
-
373
- print(text, oneline = false) {
374
- this.clearLine();
375
- this.stdout.write(oneline ? text : `${text}\n`);
376
- }
377
-
378
- childPrint(text, isError) {
379
- isError && this.print(
380
- text.toString()
381
- .split(/\r\n|\r|\n/g)
382
- .filter((chunk) => !!chunk)
383
- .map((chunk) => `< ${chunk}`)
384
- .join('\n')
385
- );
386
- if (!this.paused) {
387
- this.repl.displayPrompt(true);
388
- }
389
- if (/Waiting for the debugger to disconnect\.\.\.\n$/.test(text)) {
390
- this.killChild();
391
- sendToHost({ cmd: 'finished', text });
392
- }
393
- }
394
- }
395
-
396
- function parseArgv([target, ...args]) {
397
- let host = '127.0.0.1';
398
- let port = 9229;
399
- let isRemote = false;
400
- let script = target;
401
- let scriptArgs = args;
402
-
403
- const hostMatch = target.match(/^([^:]+):(\d+)$/);
404
- const portMatch = target.match(/^--port=(\d+)$/);
405
-
406
- if (hostMatch) {
407
- // Connecting to remote debugger
408
- // `node-inspect localhost:9229`
409
- host = hostMatch[1];
410
- port = parseInt(hostMatch[2], 10);
411
- isRemote = true;
412
- script = null;
413
- } else if (portMatch) {
414
- // start debugee on custom port
415
- // `node inspect --port=9230 script.js`
416
- port = parseInt(portMatch[1], 10);
417
- script = args[0];
418
- scriptArgs = args.slice(1);
419
- } else if (args.length === 1 && /^\d+$/.test(args[0]) && target === '-p') {
420
- // Start debugger against a given pid
421
- const pid = parseInt(args[0], 10);
422
- try {
423
- process._debugProcess(pid);
424
- } catch (e) {
425
- if (e.code === 'ESRCH') {
426
- /* eslint-disable no-console */
427
- console.error(`Target process: ${pid} doesn't exist.`);
428
- /* eslint-enable no-console */
429
- process.exit(1);
430
- }
431
- throw e;
432
- }
433
- script = null;
434
- isRemote = true;
435
- }
436
-
437
- return {
438
- host, port, isRemote, script, scriptArgs,
439
- };
440
- }
441
-
442
- function startInspect(argv = process.argv.slice(2), stdin = process.stdin, stdout = process.stdout) {
443
- /* eslint-disable no-console */
444
- /*if (argv.length < 1) {
445
- const invokedAs = runAsStandalone ?
446
- 'node-inspect' :
447
- `${process.argv0} ${process.argv[1]}`;
448
-
449
- console.error(`Usage: ${invokedAs} script.js`);
450
- console.error(` ${invokedAs} <host>:<port>`);
451
- console.error(` ${invokedAs} -p <pid>`);
452
- process.exit(1);
453
- }*/
454
-
455
- const options = parseArgv(argv);
456
- inspector = new NodeInspector(options, stdin, stdout);
457
-
458
- stdin.resume();
459
-
460
- function handleUnexpectedError(e) {
461
- if (!(e instanceof StartupError)) {
462
- console.error('There was an internal error in node-inspect. Please report this bug.');
463
- console.error(e.message);
464
- console.error(e.stack);
465
- } else {
466
- console.error(e.message);
467
- }
468
- if (inspector.child) inspector.child.kill();
469
- process.exit(1);
470
- }
471
-
472
- process.on('uncaughtException', handleUnexpectedError);
473
- /* eslint-enable no-console */
474
- }
475
-
476
- function extractErrorMessage(stack) {
477
- if (!stack) {
478
- return '<unknown>';
479
- }
480
- const m = stack.match(/^\w+: ([^\n]+)/);
481
- return m ? m[1] : stack;
482
- }
483
-
484
- function convertResultToError(result) {
485
- const { className, description } = result;
486
- const err = new Error(extractErrorMessage(description));
487
- err.stack = description;
488
- Object.defineProperty(err, 'name', { value: className });
489
- return err;
490
- }
491
-
492
- let inspector;
493
- let scriptToDebug;
494
- let instanceToDebug;
495
- let alreadyPausedOnFirstLine = false;
496
-
497
- process.on('message', message => {
498
- if (typeof message === 'string') {
499
- try {
500
- message = JSON.parse(message);
501
- } catch (e) {
502
- return console.error(`Cannot parse: ${message}`);
503
- }
504
- }
505
- processCommand(message);
506
- });
507
-
508
- sendToHost({ cmd: 'ready' });
509
-
510
- // possible commands
511
- // start - {cmd: 'start', scriptName: 'script.js.myName'} - start the debugging
512
- // end - {cmd: 'end'} - end the debugging and stop process
513
- // source - {cmd: 'source', scriptId} - read text of script by id
514
- // watch - {cmd: 'watch', expressions: ['i']} - add to watch the variable
515
- // unwatch - {cmd: 'unwatch', expressions: ['i']} - add to watch the variable
516
-
517
- // sb - {cmd: 'sb', breakpoints: [{scriptId: 50, lineNumber: 4, columnNumber: 0}]} - set breakpoint
518
- // cb - {cmd: 'cb', breakpoints: [{scriptId: 50, lineNumber: 4, columnNumber: 0}]} - clear breakpoint
519
-
520
- // pause - {cmd: 'pause'} - pause execution
521
- // cont - {cmd: 'cont'} - resume execution
522
- // next - {cmd: 'next'} - Continue to next line in current file
523
- // step - {cmd: 'step'} - Step into, potentially entering a function
524
- // out - {cmd: 'step'} - Step out, leaving the current function
525
-
526
- function processCommand(data) {
527
- if (data.cmd === 'start') {
528
- scriptToDebug = data.scriptName;
529
- instanceToDebug = data.adapterInstance;
530
- if (scriptToDebug) {
531
- startInspect([`${__dirname}/../main.js`, data.instance || 0, '--debug', '--debugScript', scriptToDebug]);
532
- } else {
533
- const [adapter, instance] = instanceToDebug.split('.');
534
- let file;
535
- try {
536
- file = require.resolve(`iobroker.${adapter}`);
537
- } catch (e) {
538
- // try to locate in the same dir
539
- const dir = path.normalize(path.join(__dirname, '..', 'iobroker.' + adapter));
540
- if (fs.existsSync(dir)) {
541
- const pack = require(path.join(dir, 'package.json'));
542
- if (fs.existsSync(path.join(dir, pack.main || `${adapter}.js`))) {
543
- file = path.join(dir, pack.main || `${adapter}.js`);
544
- }
545
- }
546
-
547
- if (!file) {
548
- sendToHost({cmd: 'error', error: `Cannot locate iobroker.${adapter}`, errorContext: e});
549
- return setTimeout(() => {
550
- sendToHost({cmd: 'finished', context: `Cannot locate iobroker.${adapter}`});
551
- setTimeout(() => process.exit(124), 500);
552
- }, 200);
553
- }
554
- }
555
- file = file.replace(/\\/g, '/');
556
- instanceToDebug = file;
557
- console.log(`Start ${file} ${instance} --debug`);
558
- startInspect([file, instance, '--debug']);
559
- }
560
- } else if (data.cmd === 'end') {
561
- process.exit();
562
- } else if (data.cmd === 'source') {
563
- inspector.Debugger.getScriptSource({ scriptId: data.scriptId })
564
- .then(script =>
565
- sendToHost({ cmd: 'script', scriptId: data.scriptId, text: script.scriptSource }));
566
- } else if (data.cmd === 'cont') {
567
- inspector.Debugger.resume()
568
- .catch(e => sendToHost({ cmd: 'error', error: e }));
569
- } else if (data.cmd === 'next') {
570
- inspector.Debugger.stepOver()
571
- .catch(e => sendToHost({ cmd: 'error', error: e }));
572
- } else if (data.cmd === 'pause') {
573
- inspector.Debugger.pause()
574
- .catch(e => sendToHost({ cmd: 'error', error: e }));
575
- } else if (data.cmd === 'step') {
576
- inspector.Debugger.stepInto()
577
- .catch(e => sendToHost({ cmd: 'error', error: e }));
578
- } else if (data.cmd === 'out') {
579
- inspector.Debugger.stepOut()
580
- .catch(e => sendToHost({ cmd: 'error', error: e }));
581
- } else if (data.cmd === 'sb') {
582
- console.log(JSON.stringify(data));
583
-
584
- Promise.all(data.breakpoints.map(bp =>
585
- inspector.Debugger.setBreakpoint({
586
- location: {
587
- scriptId: bp.scriptId,
588
- lineNumber: bp.lineNumber,
589
- columnNumber: bp.columnNumber
590
- }
591
- })
592
- .then(result =>
593
- ({ id: result.breakpointId, location: result.actualLocation}))
594
- .catch(e =>
595
- sendToHost({ cmd: 'error', error: `Cannot set breakpoint: ${e}`, errorContext: e, bp }))))
596
- .then(breakpoints =>
597
- sendToHost({cmd: 'sb', breakpoints}));
598
- } else if (data.cmd === 'cb') {
599
- Promise.all(data.breakpoints.map(breakpointId =>
600
- inspector.Debugger.removeBreakpoint({breakpointId})
601
- .then(() => breakpointId)
602
- .catch(e =>
603
- sendToHost({ cmd: 'error', error: `Cannot clear breakpoint: ${e}`, errorContext: e, id: breakpointId }))))
604
- .then(breakpoints =>
605
- sendToHost({ cmd: 'cb', breakpoints}));
606
- } else if (data.cmd === 'watch') {
607
- Promise.all(data.expressions.map(expr =>
608
- inspector.Debugger.watch(expr)
609
- .catch(e =>
610
- sendToHost({ cmd: 'error', error: `Cannot watch expr: ${e}`, errorContext: e, expr }))))
611
- .then(() => console.log('Watch done'));
612
- } else if (data.cmd === 'unwatch') {
613
- Promise.all(data.expressions.map(expr =>
614
- inspector.Debugger.unwatch(expr)
615
- .catch(e =>
616
- sendToHost({ cmd: 'error', error: `Cannot unwatch expr: ${e}`, errorContext: e, expr }))))
617
- .then(() => console.log('Watch done'));
618
- } else if (data.cmd === 'scope') {
619
- Promise.all(data.scopes.filter(scope => scope && scope.object && scope.object.objectId).map(scope =>
620
- inspector.Runtime.getProperties({
621
- objectId: scope.object.objectId,
622
- generatePreview: true,
623
- })
624
- .then(result => ({ type: scope.type, properties: result }))
625
- .catch(e =>
626
- sendToHost({ cmd: 'error', error: `Cannot get scopes expr: ${e}`, errorContext: e }))))
627
- .then(scopes =>
628
- sendToHost({ cmd: 'scope', scopes: scopes }));
629
- } else if (data.cmd === 'setValue') {
630
- inspector.Debugger.setVariableValue({
631
- variableName: data.variableName,
632
- scopeNumber: data.scopeNumber,
633
- newValue: data.newValue,
634
- callFrameId: data.callFrameId,
635
- })
636
- .catch(e =>
637
- sendToHost({cmd: 'setValue', variableName: `Cannot setValue: ${e}`, errorContext: e}))
638
- .then(() =>
639
- sendToHost(data));
640
- } else if (data.cmd === 'expressions') {
641
- Promise.all(data.expressions.map(item =>
642
- inspector.Debugger.evaluateOnCallFrame({
643
- callFrameId: data.callFrameId,
644
- expression: item.name,
645
- objectGroup: 'node-inspect',
646
- returnByValue: true,
647
- generatePreview: true,
648
- })
649
- .then(({ result, wasThrown }) => {
650
- if (wasThrown) {
651
- return {name: item.name, result: convertResultToError(result)};
652
- } else {
653
- return {name: item.name, result};
654
- }
655
- })
656
- .catch(e =>
657
- sendToHost({cmd: 'expressions', variableName: `Cannot setValue: ${e}`, errorContext: e}))))
658
- .then(expressions =>
659
- sendToHost({cmd: 'expressions', expressions}));
660
- } else if (data.cmd === 'stopOnException') {
661
- inspector.Debugger.setPauseOnExceptions({state: data.state ? 'all' : 'none'})
662
- .catch(e =>
663
- sendToHost({cmd: 'stopOnException', variableName: `Cannot stopOnException: ${e}`, errorContext: e}));
664
- } else if (data.cmd === 'getPossibleBreakpoints') {
665
- inspector.Debugger.getPossibleBreakpoints({start: data.start, end: data.end})
666
- .then(breakpoints =>
667
- sendToHost({cmd: 'getPossibleBreakpoints', breakpoints}))
668
- .catch(e =>
669
- sendToHost({cmd: 'getPossibleBreakpoints', variableName: `Cannot getPossibleBreakpoints: ${e}`, errorContext: e}));
670
- } else {
671
- console.error(`Unknown command: ${JSON.stringify(data)}`);
672
- }
673
- }
674
-
675
- function sendToHost(data) {
676
- if (data.cmd === 'error') {
677
- console.error(data.text);
678
- data.expr && console.error(`[EXPRESSION] ${data.expr}`);
679
- data.bp && console.error(`[BP] ${data.bp}`);
680
- }
681
-
682
- if (typeof data !== 'string') {
683
- data = JSON.stringify(data);
684
- }
685
-
686
- process.send && process.send(data);
687
- }
688
-