js-dev-tool 1.0.1 → 1.0.3

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.
package/utils.js CHANGED
@@ -19,20 +19,17 @@
19
19
  */
20
20
  /// <reference types="./basic-types"/>
21
21
  // @ts-check
22
-
23
- // NOTE: fs-extra are bit slower.
24
22
  const fs = require("fs");
25
- // const util = require('util');
26
23
  const path = require("path");
27
-
28
24
  const lib = require("./common");
29
25
  const getExtraArgs = require("tin-args");
30
-
31
26
  const CI = !!process.env.CI;
27
+ /**
28
+ * Nothing is logged in a CI environment.
29
+ */
32
30
  const log = (() => {
33
31
  return CI ? () => ({}) : console.log;
34
32
  })();
35
-
36
33
  /**
37
34
  * get node version at runtime.
38
35
  *
@@ -49,26 +46,19 @@ const log = (() => {
49
46
  */
50
47
  function extractVersion(versionString = process.version) {
51
48
  const RE_VERSION = /v(\d+).(\d+).(\d+)/;
52
- // NOTE: pv is Array.isArray(pv), extend Array
53
49
  let pv = RE_VERSION.exec(versionString);
54
- const [major = 0, minor = 0, patch = 0] = pv
55
- ? pv
56
- .map((value, i) => {
57
- return (i > 0 && +value) || void 0;
58
- })
59
- .slice(1)
60
- : [];
50
+ const [major = 0, minor = 0, patch = 0] = pv ? pv.map((value, i) => {
51
+ return (i > 0 && +value) || void 0;
52
+ }).slice(1) : [];
61
53
  console.log("result:", major, minor, patch);
62
54
  return { major, minor, patch };
63
55
  }
64
-
65
56
  /**
66
57
  * use toLocaleString
67
58
  * @param {any} ymd use simple year month day formant? default `false`
68
59
  * + should be truthy/falsy value
69
60
  */
70
61
  function dateStringForFile(ymd = false) {
71
- // return new Date().toLocaleString().replace(/\//g, "-").replace(/:/g, "_").replace(/ /g, "@");
72
62
  return new Date()
73
63
  .toLocaleString(void 0, {
74
64
  year: "2-digit",
@@ -77,7 +67,6 @@ function dateStringForFile(ymd = false) {
77
67
  hour: ymd ? void 0 : "2-digit",
78
68
  minute: ymd ? void 0 : "2-digit",
79
69
  second: ymd ? void 0 : "2-digit",
80
- // DEVNOTE: 191215 - "-" character appeared in node v13.3.0 (maybe
81
70
  })
82
71
  .replace(/(-|\/|:| )/g, (match, $1) => {
83
72
  switch ($1) {
@@ -90,16 +79,7 @@ function dateStringForFile(ymd = false) {
90
79
  }
91
80
  return match;
92
81
  });
93
- // return new Date().toLocaleString().replace(/(\/|:| )/g, (match, $1) => {
94
- // switch($1) {
95
- // case "/": return "-";
96
- // case ":": return "_";
97
- // case " ": return "@";
98
- // }
99
- // return match;
100
- // });
101
82
  }
102
-
103
83
  /**
104
84
  *
105
85
  * @param {string} path
@@ -108,7 +88,6 @@ function dateStringForFile(ymd = false) {
108
88
  function walkDirSync(path, handler) {
109
89
  fs.readdirSync(path, { withFileTypes: true }).forEach(handler);
110
90
  }
111
-
112
91
  /**
113
92
  * write text content to dest path.
114
93
  * when not exists parent directory, creat it.
@@ -118,50 +97,30 @@ function walkDirSync(path, handler) {
118
97
  * @param {() => void} [callback] the callback function
119
98
  */
120
99
  function writeTextUTF8(content, dest, callback) {
121
- // need dest parent dir check.
122
100
  lib.checkParentDirectory(dest);
123
-
124
- // actually, can write as binary
125
101
  const ws = fs.createWriteStream(dest);
126
102
  ws.on("error", function (err) {
127
103
  log("WriteStream.error evnet!", arguments);
128
104
  }).on("close", function (/*no args*/) {
129
- // DEVNOTE: this event never occurs when WriteStream.write returned `true`
130
- // log("[close] %s, stream closed", dest);
131
105
  callback && callback();
132
106
  });
133
-
134
107
  if (content instanceof Buffer) {
135
108
  content = content.toString();
136
109
  }
137
-
138
110
  if (typeof content === "string") {
139
- // chunk <string> | <Buffer> | <Uint8Array> | <any>
140
111
  const success = ws.write(content);
141
- // const success = ws.write(content, function (/*no args*/) {
142
- // // log(arguments);
143
- // log("callback of WriteStream.write");
144
- // });
145
- // log("writeTextUTF8: write: %s,", dest, success);
146
- // DEVNOTE: "drain" event callback -> WriteStream.write callback
147
- // -> WriteStream.end() => "close" event callback.
148
112
  if (!success) {
149
113
  ws.once("drain", function () {
150
- // log("[drain] file written: %s,", dest, ws.bytesWritten);
151
- ws.end(); // -> call close()
114
+ ws.end();
152
115
  });
153
116
  } else {
154
- // process.nextTick(callback);
155
117
  callback && callback();
156
118
  }
157
119
  }
158
- // NOTE: see https://nodejs.org/dist/latest-v6.x/docs/api/stream.html#stream_readable_pipe_destination_options
159
120
  else if ("readable" in content) {
160
- // Readable stream?
161
121
  content.pipe(ws);
162
122
  }
163
123
  }
164
-
165
124
  /**
166
125
  * @typedef {(err: any, data: string) => void} TFsCallback
167
126
  */
@@ -180,7 +139,6 @@ function readTextUTF8(from, callback) {
180
139
  }
181
140
  return /** @type {R} */ (undefined);
182
141
  }
183
-
184
142
  /**
185
143
  * @template T
186
144
  * @typedef {Record<string, T>} TypedRecord<T>
@@ -210,16 +168,6 @@ function readJson(path, callback) {
210
168
  }
211
169
  return /** @type {R} */ (undefined);
212
170
  }
213
- // // OK
214
- // /** @type {Record<string, {}>} */
215
- // const config = readJson("path");
216
- // // OK
217
- // readJson("path", (err, data) => err);
218
- // // OK
219
- // const config2 = readTextUTF8("path");
220
- // // OK
221
- // readTextUTF8("path", (err, data) => err);
222
-
223
171
  /**
224
172
  * use "rm-cstyle-cmts"
225
173
  *
@@ -231,7 +179,6 @@ function removeJsonComments(source) {
231
179
  }
232
180
  return require("rm-cstyle-cmts")(source);
233
181
  }
234
-
235
182
  /** @type {(options: any) => void} */
236
183
  let nodeReplace;
237
184
  /**
@@ -242,27 +189,19 @@ let nodeReplace;
242
189
  *
243
190
  * @date 2019-4-26
244
191
  */
245
- // DEVNOTE: 2020/9/20 - Added exception handling code
246
192
  function fireReplace(regex, replacement, paths, async = false) {
247
193
  // @ts-ignore "replace" is peerDependencies
248
194
  nodeReplace === void 0 && (nodeReplace = require("replace"));
249
- // replace init.tsx init.js ./lib/index.html && replace \\.\\/pkg\\.json ../package.json ./lib/app-properties.js
250
195
  if (Array.isArray(paths)) {
251
- // DEVNOTE: 2020/5/11 22:41:06 - exclude non exists files
252
196
  paths = paths.filter((path) => fs.existsSync(path));
253
197
  nodeReplace({
254
- regex, //: /init\.tsx/g,
255
- replacement, //: "init.js",
256
- paths, //: ["./lib/index.html"],
198
+ regex,
199
+ replacement,
200
+ paths,
257
201
  recursive: false,
258
202
  silent: false,
259
- // for test?
260
203
  preview: false,
261
- // replace function.
262
- // funcFile: "js source path",
263
- //
264
204
  async,
265
- // regexp flags, if "regex" are plain string then needed.
266
205
  ignoreCase: false,
267
206
  multiline: false,
268
207
  });
@@ -270,7 +209,6 @@ function fireReplace(regex, replacement, paths, async = false) {
270
209
  throw new Error(`invalid paths parameter: paths=[${paths}]`);
271
210
  }
272
211
  }
273
-
274
212
  /**
275
213
  * create sourceName zip. (using zip.min.js
276
214
  *
@@ -280,33 +218,25 @@ function fireReplace(regex, replacement, paths, async = false) {
280
218
  function compressScript(scriptPath, comment = "") {
281
219
  // @ts-ignore
282
220
  const zlibZip = require("./lib/zip.min").Zlib.Zip;
283
- // const zlibZip = require("zlibjs/bin/zip.min").Zlib.Zip;
284
221
  const zip = new zlibZip();
285
-
286
222
  const scriptBin = fs.readFileSync(scriptPath);
287
- // plainData1
288
223
  zip.addFile(scriptBin, {
289
- // filename: stringToByteArray("webpack.js"),
290
224
  filename: stringToByteArray(path.basename(scriptPath)),
291
225
  comment: stringToByteArray(comment),
292
- // STORE or DEFLATE, default: DEFLATE...?
293
226
  compressionMethod: zlibZip.CompressionMethod.DEFLATE,
294
227
  os: zlibZip.OperatingSystem.MSDOS,
295
228
  });
296
-
297
229
  console.log(`added ${scriptPath} to zip`);
298
230
  console.log("start compress...");
299
231
  console.time("zip:compress");
300
232
  const compressed = zip.compress();
301
233
  console.timeEnd("zip:compress");
302
234
  console.log("compress done.\n");
303
-
304
235
  const pp = path.parse(scriptPath);
305
236
  const output = `${pp.dir ? pp.dir + "/" : ""}${pp.name}.zip`;
306
237
  fs.writeFile(output, compressed, (err) => {
307
238
  console.log(`\nzip file created, error: ${err}\n => ${output}`);
308
239
  });
309
-
310
240
  /**
311
241
  * @param {string} str
312
242
  */
@@ -318,7 +248,6 @@ function compressScript(scriptPath, comment = "") {
318
248
  return array;
319
249
  }
320
250
  }
321
-
322
251
  /**
323
252
  * DEVNOTE: 10/21/2018, 9:15:00 PM - using "archiver" package, this is too fast!.
324
253
  *
@@ -326,11 +255,9 @@ function compressScript(scriptPath, comment = "") {
326
255
  * @param {string} comment
327
256
  */
328
257
  function compressScript2(scriptPath, comment = "") {
329
- // DEVNOTE: if want use "archiver" then install to npm global
330
258
  const archiver = require("archiver");
331
259
  const archive = archiver("zip", {
332
- // comment, deplicated, unzip.min will fail decompress...
333
- zlib: { level: 9 }, // Sets the compression level.
260
+ zlib: { level: 9 },
334
261
  });
335
262
  const pp = path.parse(scriptPath);
336
263
  const output = fs.createWriteStream(`${pp.dir}/${pp.name}.zip`);
@@ -343,21 +270,17 @@ function compressScript2(scriptPath, comment = "") {
343
270
  output.on("end", function () {
344
271
  console.log("Data has been drained");
345
272
  });
346
- // TODO: write code.
347
273
  archive.on("progress", (progress) => {
348
274
  console.log(progress.entries.processed);
349
275
  });
350
276
  archive.pipe(output);
351
- // option name は必ず指定 (entry name となるため
352
277
  archive.file(scriptPath, {
353
278
  name: path.basename(scriptPath),
354
- // DEVNOTE: "comment" are not entry at @types. however, it is entered in zip-stream.
355
279
  // @ts-ignore ignore mistake of type definition
356
280
  comment,
357
281
  });
358
282
  archive.finalize();
359
283
  }
360
-
361
284
  /**
362
285
  * it is bundled in webpack.js, other code becomes unnecessary.(at webpack
363
286
  *
@@ -369,7 +292,6 @@ function compressScript2(scriptPath, comment = "") {
369
292
  * @param {(result: string) => void} doneCallbackWithArgs gulp callback function.
370
293
  */
371
294
  function execWithOutputResult(command, doneCallbackWithArgs, cwd) {
372
- // const process = require("child_process");
373
295
  console.log();
374
296
  const { exec } = require("child_process");
375
297
  return exec(command, { cwd }, (err, stdout /* , stderr */) => {
@@ -380,130 +302,6 @@ function execWithOutputResult(command, doneCallbackWithArgs, cwd) {
380
302
  }
381
303
  });
382
304
  }
383
-
384
- /**
385
- *
386
- * @param {string} list
387
- */
388
- const NPM_INSTALL_SCRIPT = (list) => `
389
- @echo off
390
- rem REVISION LOG ENTRY
391
- rem
392
- rem File name : npm-upg.cmd
393
- rem Revision By: Copyright 2020 Hiroyuki Tominaga, All Rights Reserved.
394
- rem
395
- rem 9:26 2018/06/27 When executed in batch - npm ERR! Maximum call stack size exceeded
396
- rem
397
-
398
- set opt=
399
- if not "%1" == "" (
400
- set opt=%1
401
- ) else (
402
- set opt=i
403
- )
404
-
405
- rem workbox-cli@4 is too large
406
- rem \`node-sass\` will complete more smoothly if installed separately
407
- rem \`windows-build-tools\` - It is better to start PowerShell with administrator privileges and install
408
-
409
- REM TODO: automation script by nodejs
410
- REM + child_process("npm -g outdated") -> get output
411
- REM + extract outdated packages by regex
412
- REM + output install script
413
-
414
- set LIST=${list}
415
-
416
- echo packages="%LIST%"
417
- npm %opt% -g %LIST%
418
- `;
419
- /**
420
- * ### generate npm global package update script (windows command)
421
- *
422
- * ```js
423
- * const utils = require("./utils");
424
- * // ...
425
- * // execute normally
426
- * utils.genGlobalNpmUpdateScript("electron", "workbox-cli");
427
- * // debug
428
- * utils.genGlobalNpmUpdateScript("--debug", "electron", "workbox-cli");
429
- * ```
430
- *
431
- * @param {string[]} excludes
432
- */
433
- function genGlobalNpmUpdateScript(...excludes) {
434
- let debug = false;
435
- if (excludes.length && excludes[0] === "--debug") {
436
- debug = true;
437
- excludes.shift();
438
- }
439
-
440
- console.log("run `npm -g outdated`");
441
- // const progress = createProgressObject(aa, aa, aa);
442
- // progress.run();
443
- execWithOutputResult("npm -g outdated", (output) => {
444
- console.log("done `npm -g outdated`");
445
- /** @type {RegExpExecArray | null} */
446
- let m;
447
- /** @type {string[]} */
448
- const packages = [];
449
- const re = /^([\w-]+)/gm; // DEVNOTE: must use multi line flag
450
- while ((m = re.exec(output))) {
451
- const name = m[1];
452
- if (name !== "Package" && !excludes.includes(name)) {
453
- packages.push(name);
454
- }
455
- }
456
- const packageList = packages.join("^\n ");
457
- const source = NPM_INSTALL_SCRIPT(packageList);
458
- if (!debug) {
459
- writeTextUTF8(source, "./tmp/npm-upg.cmd");
460
- } else {
461
- console.log(source);
462
- }
463
- });
464
- }
465
- /* [simple test of `globalNpmUpdate`]
466
- const dummy = (output: string) => {
467
- let m: RegExpExecArray | null;
468
- const packages: string[] = [];
469
- const re = /^([\w-]+)/gm;
470
- while (m = re.exec(output)) {
471
- const name = m[1];
472
- if (name !== "Package" && !excludes.includes(name)) {
473
- packages.push(name);
474
- }
475
- }
476
- const packageList = packages.join("^\n ");
477
- const source = NPM_INSTALL_SCRIPT(packageList);
478
- // if (!debug) {
479
- // writeTextUTF8(source, "./tmp/npm-upg.cmd");
480
- // } else {
481
- // console.log(source);
482
- // }
483
- console.log(source);
484
- };
485
-
486
- //
487
- // for TEST code
488
- //
489
- const excludes = [
490
- "electron", "workbox-cli"
491
- ];
492
- const outdatedResult = `Package Current Wanted Latest Location
493
- create-react-app 3.4.0 3.4.1 3.4.1 global
494
- electron 8.0.1 8.2.0 8.2.0 global
495
- firebase 7.12.0 7.13.1 7.13.1 global
496
- firebase-tools 7.15.1 7.16.1 7.16.1 global
497
- npm-check-updates 4.0.4 4.1.0 4.1.0 global
498
- ts-node 8.7.0 8.8.1 8.8.1 global
499
- typedoc 0.17.1 0.17.3 0.17.3 global
500
- webpack 4.42.0 4.42.1 4.42.1 global
501
- workbox-cli 4.3.1 4.3.1 5.1.2 global
502
- `;
503
- // run test
504
- dummy(outdatedResult);
505
- */
506
-
507
305
  /**
508
306
  * ### command:
509
307
  *
@@ -534,32 +332,12 @@ function copyText(content, message = "text copied!", chcp65001 = true) {
534
332
  if (error) {
535
333
  console.error(error);
536
334
  }
537
- // DEVNOTE: do noting...
538
- // util.inspect("content_for_the_clipboard");
539
335
  // @ts-ignore
540
336
  childProc.stdin.end();
541
337
  });
542
338
  };
543
-
544
339
  clipTask();
545
- // if (os.platform() === "win32") {
546
- // // clipTask();
547
- // cp.exec("chcp", (err, stdout) => {
548
- // if (err) {
549
- // console.error(err);
550
- // } else {
551
- // if (!stdout.includes("65001")) {
552
- // console.log("OKKKK");
553
- // clipTask();
554
- // }
555
- // }
556
- // }
557
- // );
558
- // } else {
559
- // clipTask();
560
- // }
561
340
  }
562
-
563
341
  /**
564
342
  * use for gulp.dest(...)
565
343
  *
@@ -581,17 +359,10 @@ function copyText(content, message = "text copied!", chcp65001 = true) {
581
359
  * @param {string} dest default is "." -> node launched directory. (cwd?)
582
360
  */
583
361
  function convertRelativeDir(vinyl, dest = ".") {
584
- // NOTE: vinyl is https://github.com/gulpjs/vinyl
585
- // if (false) {
586
- // console.log("convertRelativeDir::debug log");
587
- // console.log(vinyl.cwd);
588
- // console.log(vinyl.base);
589
- // }
590
362
  let x = vinyl.cwd.length + 1;
591
363
  let relative_dir = vinyl.base.substring(x);
592
364
  return `${dest}/${relative_dir}`;
593
365
  }
594
-
595
366
  /**
596
367
  * prepend `content` to the beginning of each element of `str_array`
597
368
  *
@@ -613,10 +384,8 @@ function prependStringTo(str_array, content, suffix = "") {
613
384
  str_array[i++] = `${content}${suffix}${target}`;
614
385
  }
615
386
  }
616
-
617
387
  module.exports = {
618
388
  prependStringTo,
619
-
620
389
  extractVersion,
621
390
  dateStringForFile,
622
391
  getExtraArgs,
@@ -625,11 +394,9 @@ module.exports = {
625
394
  readTextUTF8,
626
395
  readJson,
627
396
  walkDirSync,
628
-
629
397
  compressScript,
630
398
  compressScript2,
631
399
  execWithOutputResult,
632
- genGlobalNpmUpdateScript,
633
400
  convertRelativeDir,
634
401
  /**
635
402
  *
@@ -640,4 +407,4 @@ module.exports = {
640
407
  fireReplace,
641
408
  CI,
642
409
  log,
643
- };
410
+ };