@appium/support 2.55.4 → 2.57.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 (96) hide show
  1. package/build/lib/env.d.ts +54 -0
  2. package/build/lib/env.d.ts.map +1 -0
  3. package/build/lib/env.js +102 -0
  4. package/build/lib/fs.d.ts +221 -0
  5. package/build/lib/fs.d.ts.map +1 -0
  6. package/build/lib/fs.js +74 -56
  7. package/build/lib/image-util.d.ts +56 -0
  8. package/build/lib/image-util.d.ts.map +1 -0
  9. package/build/lib/image-util.js +3 -6
  10. package/build/lib/index.d.ts +38 -0
  11. package/build/lib/index.d.ts.map +1 -0
  12. package/build/lib/index.js +36 -18
  13. package/build/lib/log-internal.d.ts +74 -0
  14. package/build/lib/log-internal.d.ts.map +1 -0
  15. package/build/lib/log-internal.js +11 -21
  16. package/build/lib/logger.d.ts +3 -0
  17. package/build/lib/logger.d.ts.map +1 -0
  18. package/build/lib/logger.js +2 -4
  19. package/build/lib/logging.d.ts +45 -0
  20. package/build/lib/logging.d.ts.map +1 -0
  21. package/build/lib/logging.js +12 -16
  22. package/build/lib/mjpeg.d.ts +65 -0
  23. package/build/lib/mjpeg.d.ts.map +1 -0
  24. package/build/lib/mjpeg.js +12 -7
  25. package/build/lib/mkdirp.d.ts +3 -0
  26. package/build/lib/mkdirp.d.ts.map +1 -0
  27. package/build/lib/mkdirp.js +7 -11
  28. package/build/lib/net.d.ts +95 -0
  29. package/build/lib/net.d.ts.map +1 -0
  30. package/build/lib/net.js +42 -26
  31. package/build/lib/node.d.ts +26 -0
  32. package/build/lib/node.d.ts.map +1 -0
  33. package/build/lib/node.js +102 -3
  34. package/build/lib/npm.d.ts +123 -0
  35. package/build/lib/npm.d.ts.map +1 -0
  36. package/build/lib/npm.js +217 -0
  37. package/build/lib/plist.d.ts +43 -0
  38. package/build/lib/plist.d.ts.map +1 -0
  39. package/build/lib/plist.js +2 -4
  40. package/build/lib/process.d.ts +3 -0
  41. package/build/lib/process.d.ts.map +1 -0
  42. package/build/lib/process.js +2 -4
  43. package/build/lib/system.d.ts +7 -0
  44. package/build/lib/system.d.ts.map +1 -0
  45. package/build/lib/system.js +2 -4
  46. package/build/lib/tempdir.d.ts +63 -0
  47. package/build/lib/tempdir.d.ts.map +1 -0
  48. package/build/lib/tempdir.js +4 -9
  49. package/build/lib/timing.d.ts +46 -0
  50. package/build/lib/timing.d.ts.map +1 -0
  51. package/build/lib/timing.js +2 -4
  52. package/build/lib/util.d.ts +183 -0
  53. package/build/lib/util.d.ts.map +1 -0
  54. package/build/lib/util.js +9 -15
  55. package/build/lib/zip.d.ts +180 -0
  56. package/build/lib/zip.d.ts.map +1 -0
  57. package/build/lib/zip.js +9 -9
  58. package/build/tsconfig.tsbuildinfo +1 -0
  59. package/lib/env.js +162 -0
  60. package/lib/fs.js +198 -69
  61. package/lib/image-util.js +23 -7
  62. package/lib/index.js +6 -6
  63. package/lib/log-internal.js +31 -38
  64. package/lib/logging.js +41 -17
  65. package/lib/mjpeg.js +14 -5
  66. package/lib/mkdirp.js +3 -6
  67. package/lib/net.js +116 -60
  68. package/lib/node.js +107 -4
  69. package/lib/npm.js +278 -0
  70. package/lib/plist.js +3 -1
  71. package/lib/tempdir.js +14 -13
  72. package/lib/util.js +36 -33
  73. package/lib/zip.js +31 -21
  74. package/package.json +31 -13
  75. package/build/test/assets/sample_binary.plist +0 -0
  76. package/build/test/assets/sample_text.plist +0 -28
  77. package/build/test/fs-specs.js +0 -264
  78. package/build/test/helpers.js +0 -35
  79. package/build/test/image-util-e2e-specs.js +0 -78
  80. package/build/test/index-specs.js +0 -49
  81. package/build/test/log-internals-specs.js +0 -97
  82. package/build/test/logger/helpers.js +0 -71
  83. package/build/test/logger/logger-force-specs.js +0 -41
  84. package/build/test/logger/logger-normal-specs.js +0 -113
  85. package/build/test/logger/logger-test-specs.js +0 -40
  86. package/build/test/mjpeg-e2e-specs.js +0 -96
  87. package/build/test/net-e2e-specs.js +0 -32
  88. package/build/test/node-e2e-specs.js +0 -22
  89. package/build/test/plist-specs.js +0 -54
  90. package/build/test/process-specs.js +0 -104
  91. package/build/test/system-specs.js +0 -136
  92. package/build/test/tempdir-specs.js +0 -86
  93. package/build/test/timing-specs.js +0 -125
  94. package/build/test/util-e2e-specs.js +0 -136
  95. package/build/test/util-specs.js +0 -537
  96. package/build/test/zip-e2e-specs.js +0 -233
package/lib/fs.js CHANGED
@@ -1,76 +1,162 @@
1
- // jshint ignore: start
2
- import _ from 'lodash';
3
- import path from 'path';
4
- import _fs from 'fs';
5
- import rimraf from 'rimraf';
6
- import ncp from 'ncp';
1
+ // @ts-check
2
+
7
3
  import B from 'bluebird';
8
- import mv from 'mv';
9
- import which from 'which';
10
- import glob from 'glob';
11
4
  import crypto from 'crypto';
5
+ import { close, constants, createReadStream, createWriteStream, promises as fsPromises, read, write, open } from 'fs';
6
+ import glob from 'glob';
12
7
  import klaw from 'klaw';
8
+ import _ from 'lodash';
9
+ import mv from 'mv';
10
+ import ncp from 'ncp';
11
+ import path from 'path';
12
+ import pkgDir from 'pkg-dir';
13
+ import readPkg from 'read-pkg';
14
+ import rimrafIdx from 'rimraf';
13
15
  import sanitize from 'sanitize-filename';
14
- import findRoot from 'find-root';
15
- import { pluralize } from './util';
16
+ import which from 'which';
16
17
  import log from './logger';
17
18
  import Timer from './timing';
19
+ import { pluralize } from './util';
18
20
 
19
- const mkdirAsync = B.promisify(_fs.mkdir);
20
- const ncpAsync = B.promisify(ncp);
21
- const findRootCached = _.memoize(findRoot);
21
+ const ncpAsync = /** @type {(source: string, dest: string, opts: ncp.Options|undefined) => B<void>} */(B.promisify(ncp));
22
+ const findRootCached = _.memoize(pkgDir.sync);
22
23
 
23
24
  const fs = {
25
+ /**
26
+ * Resolves `true` if `path` is _readable_, which differs from Node.js' default behavior of "can we see it?"
27
+ * @param {import('fs').PathLike} path
28
+ * @returns {Promise<boolean>}
29
+ */
24
30
  async hasAccess (path) {
25
31
  try {
26
- await this.access(path, _fs.R_OK);
32
+ await fsPromises.access(path, constants.R_OK);
27
33
  } catch (err) {
28
34
  return false;
29
35
  }
30
36
  return true;
31
37
  },
32
- exists (path) { return this.hasAccess(path); },
33
- rimraf: B.promisify(rimraf),
34
- rimrafSync: rimraf.sync.bind(rimraf),
35
- async mkdir (...args) {
38
+
39
+ /**
40
+ * Alias for {@linkcode fs.hasAccess}
41
+ * @param {import('fs').PathLike} path
42
+ */
43
+ async exists (path) {
44
+ return await fs.hasAccess(path);
45
+ },
46
+
47
+ /**
48
+ * Remove a directory and all its contents, recursively
49
+ * @todo Replace with `rm()` from `fs.promises` when Node.js v12 support is dropped.
50
+ */
51
+ rimraf: /** @type {(dirpath: string, opts?: import('rimraf').Options) => Promise<void>} */(B.promisify(rimrafIdx)),
52
+
53
+ /**
54
+ * Alias of {@linkcode rimrafIdx.sync}
55
+ * @todo Replace with `rmSync()` from `fs` when Node.js v12 support is dropped.
56
+ */
57
+ rimrafSync: rimrafIdx.sync,
58
+
59
+ /**
60
+ * Like Node.js' `fsPromises.mkdir()`, but will _not_ reject if the directory already exists.
61
+ *
62
+ * @param {string|Buffer|URL} filepath
63
+ * @param {import('fs').MakeDirectoryOptions} [opts]
64
+ * @returns {Promise<string|undefined>}
65
+ * @see https://nodejs.org/api/fs.html#fspromisesmkdirpath-options
66
+ */
67
+ async mkdir (filepath, opts = {}) {
36
68
  try {
37
- return await mkdirAsync(...args);
69
+ return await fsPromises.mkdir(filepath, opts);
38
70
  } catch (err) {
39
- if (err && err.code !== 'EEXIST') {
71
+ if (err?.code !== 'EEXIST') {
40
72
  throw err;
41
73
  }
42
74
  }
43
75
  },
44
- async copyFile (source, destination, ...otherArgs) {
45
- if (!await this.hasAccess(source)) {
76
+ /**
77
+ * Copies files _and entire directories_
78
+ * @param {string} source - Source to copy
79
+ * @param {string} destination - Destination to copy to
80
+ * @param {ncp.Options} [opts] - Additional arguments to pass to `ncp`
81
+ * @see https://npm.im/ncp
82
+ * @returns {Promise<void>}
83
+ */
84
+ async copyFile (source, destination, opts = {}) {
85
+ if (!await fs.hasAccess(source)) {
46
86
  throw new Error(`The file at '${source}' does not exist or is not accessible`);
47
87
  }
48
- return await ncpAsync(source, destination, ...otherArgs);
88
+ return await ncpAsync(source, destination, opts);
49
89
  },
90
+
91
+ /**
92
+ * Create an MD5 hash of a file.
93
+ * @param {import('fs').PathLike} filePath
94
+ * @returns {Promise<string>}
95
+ */
50
96
  async md5 (filePath) {
51
- return await this.hash(filePath, 'md5');
97
+ return await fs.hash(filePath, 'md5');
52
98
  },
53
- mv: B.promisify(mv),
54
- which: B.promisify(which),
55
- glob: B.promisify(glob),
99
+
100
+ /**
101
+ * Move a file
102
+ */
103
+ mv: /** @type {(from: string, to: string, opts?: mv.Options) => B<void>} */(B.promisify(mv)),
104
+
105
+ /**
106
+ * Find path to an executable in system `PATH`
107
+ * @see https://github.com/npm/node-which
108
+ */
109
+ which,
110
+
111
+ /**
112
+ * Given a glob pattern, resolve with list of files matching that pattern
113
+ * @see https://github.com/isaacs/node-glob
114
+ */
115
+ glob: /** @type {(pattern: string, opts?: glob.IOptions) => B<string[]>} */(B.promisify(glob)),
116
+
117
+ /**
118
+ * Sanitize a filename
119
+ * @see https://github.com/parshap/node-sanitize-filename
120
+ */
56
121
  sanitizeName: sanitize,
122
+
123
+ /**
124
+ * Create a hex digest of some file at `filePath`
125
+ * @param {import('fs').PathLike} filePath
126
+ * @param {string} [algorithm]
127
+ * @returns {Promise<string>}
128
+ */
57
129
  async hash (filePath, algorithm = 'sha1') {
58
130
  return await new B((resolve, reject) => {
59
131
  const fileHash = crypto.createHash(algorithm);
60
- const readStream = _fs.createReadStream(filePath);
132
+ const readStream = createReadStream(filePath);
61
133
  readStream.on('error', (e) => reject(
62
134
  new Error(`Cannot calculate ${algorithm} hash for '${filePath}'. Original error: ${e.message}`)));
63
135
  readStream.on('data', (chunk) => fileHash.update(chunk));
64
136
  readStream.on('end', () => resolve(fileHash.digest('hex')));
65
137
  });
66
138
  },
67
- /** The callback function which will be called during the directory walking
68
- * @name WalkDirCallback
69
- * @function
70
- * @param {string} itemPath The path of the file or folder
71
- * @param {boolean} isDirectory Shows if it is a directory or a file
72
- * @return {boolean} return true if you want to stop walking
73
- */
139
+
140
+ /**
141
+ * Returns an `Walker` instance, which is a readable stream (and thusly an async iterator).
142
+ *
143
+ * @param {string} dir - Dir to start walking at
144
+ * @param {import('klaw').Options} [opts]
145
+ * @returns {import('klaw').Walker}
146
+ * @see https://www.npmjs.com/package/klaw
147
+ */
148
+ walk (dir, opts) {
149
+ return klaw(dir, opts);
150
+ },
151
+
152
+ /**
153
+ * Recursively create a directory.
154
+ * @param {import('fs').PathLike} dir
155
+ * @returns {Promise<string|undefined>}
156
+ */
157
+ async mkdirp (dir) {
158
+ return await fs.mkdir(dir, {recursive: true});
159
+ },
74
160
 
75
161
  /**
76
162
  * Walks a directory given according to the parameters given. The callback will be invoked with a path joined with the dir parameter
@@ -78,7 +164,7 @@ const fs = {
78
164
  * @param {boolean} recursive Set it to true if you want to continue walking sub directories
79
165
  * @param {WalkDirCallback} callback The callback to be called when a new path is found
80
166
  * @throws {Error} If the `dir` parameter contains a path to an invalid folder
81
- * @return {?string} returns the found path or null if the item was not found
167
+ * @returns {Promise<string?>} returns the found path or null if the item was not found
82
168
  */
83
169
  async walkDir (dir, recursive, callback) { //eslint-disable-line promise/prefer-await-to-callbacks
84
170
  let isValidRoot = false;
@@ -131,7 +217,9 @@ const fs = {
131
217
  })
132
218
  .on('end', function () {
133
219
  lastFileProcessed
134
- .then(resolve)
220
+ .then((file) => {
221
+ resolve(/** @type {string|undefined} */(file) ?? null);
222
+ })
135
223
  .catch(function (err) {
136
224
  log.warn(`Unexpected error: ${err.message}`);
137
225
  reject(err);
@@ -149,14 +237,14 @@ const fs = {
149
237
  /**
150
238
  * Reads the closest `package.json` file from absolute path `dir`.
151
239
  * @param {string} dir - Directory to search from
152
- * @throws {TypeError} If `dir` is not a nonempty string or relative path
240
+ * @param {import('read-pkg').Options} [opts] - Additional options for `read-pkg`
153
241
  * @throws {Error} If there were problems finding or reading a `package.json` file
154
242
  * @returns {object} A parsed `package.json`
155
243
  */
156
- readPackageJsonFrom (dir) {
157
- const root = fs.findRoot(dir);
244
+ readPackageJsonFrom (dir, opts = {}) {
245
+ const cwd = fs.findRoot(dir);
158
246
  try {
159
- return JSON.parse(_fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
247
+ return readPkg.sync({...opts, cwd});
160
248
  } catch (err) {
161
249
  err.message = `Failed to read a \`package.json\` from dir \`${dir}\`:\n\n${err.message}`;
162
250
  throw err;
@@ -178,34 +266,75 @@ const fs = {
178
266
  throw new Error(`\`findRoot()\` could not find \`package.json\` from ${dir}`);
179
267
  }
180
268
  return result;
181
- }
182
- };
269
+ },
270
+
271
+ // add the supported `fs` functions
272
+ access: fsPromises.access,
273
+ appendFile: fsPromises.appendFile,
274
+ chmod: fsPromises.chmod,
275
+ close: B.promisify(close),
276
+ constants,
277
+ createWriteStream,
278
+ createReadStream,
279
+ lstat: fsPromises.lstat,
280
+ /**
281
+ * Warning: this is a promisified {@linkcode open fs.open}.
282
+ * It resolves w/a file descriptor instead of a {@linkcode fsPromises.FileHandle FileHandle} object, as {@linkcode fsPromises.open} does. Use {@linkcode fs.openFile} if you want a `FileHandle`.
283
+ * @type {(path: import('fs').PathLike, flags: import('fs').OpenMode, mode?: import('fs').Mode) => Promise<number>}
284
+ */
285
+ open: B.promisify(open),
286
+ openFile: fsPromises.open,
287
+ readdir: fsPromises.readdir,
288
+ read: B.promisify(read),
289
+ readFile: fsPromises.readFile,
290
+ readlink: fsPromises.readlink,
291
+ realpath: fsPromises.realpath,
292
+ rename: fsPromises.rename,
293
+ stat: fsPromises.stat,
294
+ symlink: fsPromises.symlink,
295
+ unlink: fsPromises.unlink,
296
+ write: B.promisify(write),
297
+ writeFile: fsPromises.writeFile,
298
+
299
+ // deprecated props
300
+
301
+ /**
302
+ * Use `constants.F_OK` instead.
303
+ * @deprecated
304
+ */
305
+ F_OK: constants.F_OK,
306
+
307
+ /**
308
+ * Use `constants.R_OK` instead.
309
+ * @deprecated
310
+ */
311
+ R_OK: constants.R_OK,
312
+
313
+ /**
314
+ * Use `constants.W_OK` instead.
315
+ * @deprecated
316
+ */
317
+ W_OK: constants.W_OK,
183
318
 
184
- // add the supported `fs` functions
185
- const simples = [
186
- 'open', 'close', 'access', 'readFile', 'writeFile', 'write', 'read',
187
- 'readlink', 'chmod', 'unlink', 'readdir', 'stat', 'rename', 'lstat',
188
- 'appendFile', 'realpath', 'symlink',
189
- ];
190
- for (const s of simples) {
191
- fs[s] = B.promisify(_fs[s]);
192
- }
193
-
194
- const syncFunctions = [
195
- 'createReadStream',
196
- 'createWriteStream',
197
- ];
198
- for (const s of syncFunctions) {
199
- fs[s] = _fs[s];
200
- }
201
-
202
- // add the constants from `fs`
203
- const constants = [
204
- 'F_OK', 'R_OK', 'W_OK', 'X_OK', 'constants',
205
- ];
206
- for (const c of constants) {
207
- fs[c] = _fs[c];
208
- }
319
+ /**
320
+ * Use `constants.X_OK` instead.
321
+ * @deprecated
322
+ */
323
+ X_OK: constants.X_OK
324
+ };
209
325
 
210
326
  export { fs };
211
327
  export default fs;
328
+
329
+ /**
330
+ * The callback function which will be called during the directory walking
331
+ * @callback WalkDirCallback
332
+ * @param {string} itemPath The path of the file or folder
333
+ * @param {boolean} isDirectory Shows if it is a directory or a file
334
+ * @return {boolean} return true if you want to stop walking
335
+ */
336
+
337
+ /**
338
+ * @typedef {import('glob')} glob
339
+ * @typedef {import('mv')} mv
340
+ */
package/lib/image-util.js CHANGED
@@ -15,7 +15,7 @@ const { MIME_JPEG, MIME_PNG, MIME_BMP } = Jimp;
15
15
  *
16
16
  * @param {Buffer|string} data - binary image buffer or base64-encoded image
17
17
  * string
18
- * @returns {Jimp} - the jimp image object
18
+ * @returns {Promise<AppiumJimp>} - the jimp image object
19
19
  */
20
20
  async function getJimpImage (data) {
21
21
  return await new B((resolve, reject) => {
@@ -26,15 +26,19 @@ async function getJimpImage (data) {
26
26
  if (_.isString(data)) {
27
27
  data = Buffer.from(data, 'base64');
28
28
  }
29
- new Jimp(data, (err, imgObj) => {
29
+ new Jimp(data,
30
+ /**
31
+ * @param {Error?} err
32
+ * @param {AppiumJimp} imgObj
33
+ */
34
+ (err, imgObj) => {
30
35
  if (err) {
31
36
  return reject(err);
32
37
  }
33
38
  if (!imgObj) {
34
39
  return reject(new Error('Could not create jimp image from that data'));
35
40
  }
36
- imgObj._getBuffer = imgObj.getBuffer.bind(imgObj);
37
- imgObj.getBuffer = B.promisify(imgObj._getBuffer, {context: imgObj});
41
+ imgObj.getBuffer = B.promisify(imgObj.getBuffer.bind(imgObj), {context: imgObj});
38
42
  resolve(imgObj);
39
43
  });
40
44
  });
@@ -45,7 +49,7 @@ async function getJimpImage (data) {
45
49
  *
46
50
  * @param {string} base64Image The string with base64 encoded image
47
51
  * @param {Region} rect The selected region of image
48
- * @return {string} base64 encoded string of cropped image
52
+ * @return {Promise<string>} base64 encoded string of cropped image
49
53
  */
50
54
  async function cropBase64Image (base64Image, rect) {
51
55
  const image = await base64ToImage(base64Image);
@@ -57,7 +61,7 @@ async function cropBase64Image (base64Image, rect) {
57
61
  * Create a pngjs image from given base64 image
58
62
  *
59
63
  * @param {string} base64Image The string with base64 encoded image
60
- * @return {PNG} The image object
64
+ * @return {Promise<PNG>} The image object
61
65
  */
62
66
  async function base64ToImage (base64Image) {
63
67
  const imageBuffer = Buffer.from(base64Image, 'base64');
@@ -76,7 +80,7 @@ async function base64ToImage (base64Image) {
76
80
  * Create a base64 string for given image object
77
81
  *
78
82
  * @param {PNG} image The image object
79
- * @return {string} The string with base64 encoded image
83
+ * @return {Promise<string>} The string with base64 encoded image
80
84
  */
81
85
  async function imageToBase64 (image) {
82
86
  return await new B((resolve, reject) => {
@@ -138,3 +142,15 @@ export {
138
142
  cropBase64Image, base64ToImage, imageToBase64, cropImage,
139
143
  getJimpImage, MIME_JPEG, MIME_PNG, MIME_BMP
140
144
  };
145
+
146
+ /**
147
+ * @typedef {Omit<Jimp,'getBuffer'> & {getBuffer: Jimp['getBufferAsync']}} AppiumJimp
148
+ */
149
+
150
+ /**
151
+ * @typedef Region
152
+ * @property {number} left
153
+ * @property {number} top
154
+ * @property {number} width
155
+ * @property {number} height
156
+ */
package/lib/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import * as tempDir from './tempdir';
2
2
  import * as system from './system';
3
3
  import * as util from './util';
4
- import * as fsIndex from './fs';
4
+ import { fs } from './fs';
5
5
  import * as net from './net';
6
6
  import * as plist from './plist';
7
- import * as mkdirpIndex from './mkdirp';
7
+ import { mkdirp } from './mkdirp';
8
8
  import * as logger from './logging';
9
9
  import * as process from './process';
10
10
  import * as zip from './zip';
@@ -12,17 +12,17 @@ import * as imageUtil from './image-util';
12
12
  import * as mjpeg from './mjpeg';
13
13
  import * as node from './node';
14
14
  import * as timing from './timing';
15
+ import * as env from './env';
15
16
 
17
+ export { npm } from './npm';
16
18
 
17
- const { fs } = fsIndex;
18
19
  const { cancellableDelay } = util;
19
- const { mkdirp } = mkdirpIndex;
20
20
 
21
21
  export {
22
22
  tempDir, system, util, fs, cancellableDelay, plist, mkdirp, logger, process,
23
- zip, imageUtil, net, mjpeg, node, timing,
23
+ zip, imageUtil, net, mjpeg, node, timing, env
24
24
  };
25
25
  export default {
26
26
  tempDir, system, util, fs, cancellableDelay, plist, mkdirp, logger, process,
27
- zip, imageUtil, net, mjpeg, node, timing,
27
+ zip, imageUtil, net, mjpeg, node, timing, env
28
28
  };
@@ -3,12 +3,6 @@ import _ from 'lodash';
3
3
 
4
4
  const DEFAULT_REPLACER = '**SECURE**';
5
5
 
6
- /**
7
- * @typedef {Object} SecureValuePreprocessingRule
8
- * @property {RegExp} pattern The parsed pattern which is going to be used for replacement
9
- * @property {string} replacer [DEFAULT_SECURE_REPLACER] The replacer value to use. By default
10
- * equals to `DEFAULT_SECURE_REPLACER`
11
- */
12
6
 
13
7
  class SecureValuesPreprocessor {
14
8
  constructor () {
@@ -23,19 +17,6 @@ class SecureValuesPreprocessor {
23
17
  return this._rules;
24
18
  }
25
19
 
26
- /**
27
- * @typedef {Object} Rule
28
- * @property {string} pattern A valid RegExp pattern to be replaced
29
- * @property {string} text A text match to replace. Either this property or the
30
- * above one must be provided. `pattern` has priority over `text` if both are provided.
31
- * @property {string} flags ['g'] Regular expression flags for the given pattern.
32
- * Supported flag are the same as for the standard JavaScript RegExp constructor:
33
- * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags_2
34
- * The 'g' (global matching) is always enabled though.
35
- * @property {string} replacer [DEFAULT_SECURE_REPLACER] The replacer value to use. By default
36
- * equals to `DEFAULT_SECURE_REPLACER`
37
- */
38
-
39
20
  /**
40
21
  * Parses single rule from the given JSON file
41
22
  *
@@ -45,32 +26,28 @@ class SecureValuesPreprocessor {
45
26
  * @returns {SecureValuePreprocessingRule} The parsed rule
46
27
  */
47
28
  parseRule (rule) {
48
- const raiseError = (msg) => {
49
- throw new Error(`${JSON.stringify(rule)} -> ${msg}`);
50
- };
51
-
52
29
  let pattern;
53
30
  let replacer = DEFAULT_REPLACER;
54
31
  let flags = ['g'];
55
32
  if (_.isString(rule)) {
56
33
  if (rule.length === 0) {
57
- raiseError('The value must not be empty');
34
+ throw new Error(`${JSON.stringify(rule)} -> The value must not be empty`);
58
35
  }
59
36
  pattern = `\\b${_.escapeRegExp(rule)}\\b`;
60
37
  } else if (_.isPlainObject(rule)) {
61
38
  if (_.has(rule, 'pattern')) {
62
39
  if (!_.isString(rule.pattern) || rule.pattern.length === 0) {
63
- raiseError(`The value of 'pattern' must be a valid non-empty string`);
40
+ throw new Error(`${JSON.stringify(rule)} -> The value of 'pattern' must be a valid non-empty string`);
64
41
  }
65
42
  pattern = rule.pattern;
66
43
  } else if (_.has(rule, 'text')) {
67
44
  if (!_.isString(rule.text) || rule.text.length === 0) {
68
- raiseError(`The value of 'text' must be a valid non-empty string`);
45
+ throw new Error(`${JSON.stringify(rule)} -> The value of 'text' must be a valid non-empty string`);
69
46
  }
70
47
  pattern = `\\b${_.escapeRegExp(rule.text)}\\b`;
71
48
  }
72
49
  if (!pattern) {
73
- raiseError(`Must either have a field named 'pattern' or 'text'`);
50
+ throw new Error(`${JSON.stringify(rule)} -> Must either have a field named 'pattern' or 'text'`);
74
51
  }
75
52
 
76
53
  if (_.has(rule, 'flags')) {
@@ -87,27 +64,23 @@ class SecureValuesPreprocessor {
87
64
  replacer = rule.replacer;
88
65
  }
89
66
  } else {
90
- raiseError('Must either be a string or an object');
67
+ throw new Error(`${JSON.stringify(rule)} -> Must either be a string or an object`);
91
68
  }
92
69
 
93
- try {
94
- return {
95
- pattern: new RegExp(pattern, flags.join('')),
96
- replacer,
97
- };
98
- } catch (e) {
99
- raiseError(e.message);
100
- }
70
+ return {
71
+ pattern: new RegExp(pattern, flags.join('')),
72
+ replacer,
73
+ };
101
74
  }
102
75
 
103
76
  /**
104
77
  * Loads rules from the given JSON file
105
78
  *
106
- * @param {string|string[]|Rule[]>} source The full path to the JSON file containing secure
79
+ * @param {string|string[]|Rule[]} source The full path to the JSON file containing secure
107
80
  * values replacement rules or the rules themselves represented as an array
108
81
  * @throws {Error} If the format of the source file is invalid or
109
82
  * it does not exist
110
- * @returns {Array<string>} The list of issues found while parsing each rule.
83
+ * @returns {Promise<string[]>} The list of issues found while parsing each rule.
111
84
  * An empty list is returned if no rule parsing issues were found
112
85
  */
113
86
  async loadRules (source) {
@@ -165,3 +138,23 @@ const SECURE_VALUES_PREPROCESSOR = new SecureValuesPreprocessor();
165
138
 
166
139
  export { SECURE_VALUES_PREPROCESSOR, SecureValuesPreprocessor };
167
140
  export default SECURE_VALUES_PREPROCESSOR;
141
+
142
+ /**
143
+ * @typedef Rule
144
+ * @property {string} pattern A valid RegExp pattern to be replaced
145
+ * @property {string} text A text match to replace. Either this property or the
146
+ * above one must be provided. `pattern` has priority over `text` if both are provided.
147
+ * @property {string} [flags] Regular expression flags for the given pattern.
148
+ * Supported flag are the same as for the standard JavaScript RegExp constructor:
149
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags_2
150
+ * The 'g' (global matching) is always enabled though.
151
+ * @property {string} [replacer] The replacer value to use. By default
152
+ * equals to `DEFAULT_SECURE_REPLACER`
153
+ */
154
+
155
+ /**
156
+ * @typedef SecureValuePreprocessingRule
157
+ * @property {RegExp} pattern The parsed pattern which is going to be used for replacement
158
+ * @property {string} [replacer] The replacer value to use. By default
159
+ * equals to `DEFAULT_SECURE_REPLACER`
160
+ */