@naturalcycles/nodejs-lib 13.0.2 → 13.1.1

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 (77) hide show
  1. package/dist/bin/del.js +3 -2
  2. package/dist/bin/generate-build-info.js +8 -7
  3. package/dist/bin/json2env.js +3 -2
  4. package/dist/bin/kpy.js +3 -2
  5. package/dist/bin/secrets-decrypt.js +3 -2
  6. package/dist/bin/secrets-encrypt.js +3 -2
  7. package/dist/bin/secrets-gen-key.js +5 -4
  8. package/dist/bin/slack-this.js +3 -2
  9. package/dist/colors/colors.d.ts +1 -1
  10. package/dist/colors/colors.js +31 -30
  11. package/dist/fs/del.js +11 -10
  12. package/dist/fs/fs.util.d.ts +1 -1
  13. package/dist/fs/fs.util.js +42 -41
  14. package/dist/fs/json2env.js +6 -5
  15. package/dist/fs/kpy.js +8 -7
  16. package/dist/index.d.ts +4 -8
  17. package/dist/index.js +6 -11
  18. package/dist/infra/process.util.js +8 -7
  19. package/dist/jwt/jwt.service.d.ts +1 -1
  20. package/dist/jwt/jwt.service.js +6 -5
  21. package/dist/secret/secrets-decrypt.util.js +9 -8
  22. package/dist/secret/secrets-encrypt.util.js +8 -7
  23. package/dist/security/crypto.util.js +9 -8
  24. package/dist/security/hash.util.js +4 -3
  25. package/dist/security/id.util.js +4 -3
  26. package/dist/security/secret.util.js +7 -6
  27. package/dist/stream/ndjson/ndjsonStreamForEach.js +3 -2
  28. package/dist/stream/ndjson/pipelineFromNDJsonFile.js +4 -3
  29. package/dist/stream/ndjson/pipelineToNDJsonFile.js +4 -3
  30. package/dist/util/env.util.js +3 -2
  31. package/dist/util/exec.util.js +4 -3
  32. package/dist/util/git.util.js +9 -8
  33. package/dist/util/zip.util.js +6 -5
  34. package/dist/validation/ajv/getAjv.js +2 -1
  35. package/dist/validation/joi/joi.extensions.d.ts +1 -1
  36. package/dist/validation/joi/joi.extensions.js +3 -2
  37. package/dist/validation/joi/number.extensions.d.ts +1 -1
  38. package/dist/validation/joi/string.extensions.d.ts +1 -1
  39. package/package.json +1 -2
  40. package/src/bin/del.ts +1 -1
  41. package/src/bin/generate-build-info.ts +3 -3
  42. package/src/bin/json2env.ts +1 -1
  43. package/src/bin/kpy.ts +1 -1
  44. package/src/bin/secrets-decrypt.ts +1 -1
  45. package/src/bin/secrets-encrypt.ts +1 -1
  46. package/src/bin/secrets-gen-key.ts +2 -2
  47. package/src/bin/slack-this.ts +1 -1
  48. package/src/colors/colors.ts +2 -2
  49. package/src/fs/del.ts +2 -2
  50. package/src/fs/fs.util.ts +3 -3
  51. package/src/fs/json2env.ts +1 -1
  52. package/src/fs/kpy.ts +1 -1
  53. package/src/index.ts +3 -11
  54. package/src/infra/process.util.ts +1 -1
  55. package/src/jwt/jwt.service.ts +1 -1
  56. package/src/secret/secrets-decrypt.util.ts +2 -2
  57. package/src/secret/secrets-encrypt.util.ts +2 -2
  58. package/src/security/crypto.util.ts +1 -1
  59. package/src/security/hash.util.ts +1 -1
  60. package/src/security/id.util.ts +1 -1
  61. package/src/security/secret.util.ts +1 -1
  62. package/src/stream/ndjson/ndjsonStreamForEach.ts +1 -1
  63. package/src/stream/ndjson/pipelineFromNDJsonFile.ts +1 -1
  64. package/src/stream/ndjson/pipelineToNDJsonFile.ts +1 -1
  65. package/src/util/env.util.ts +1 -1
  66. package/src/util/exec.util.ts +1 -1
  67. package/src/util/git.util.ts +2 -2
  68. package/src/util/zip.util.ts +1 -1
  69. package/src/validation/joi/joi.extensions.ts +1 -1
  70. package/src/validation/joi/number.extensions.ts +1 -1
  71. package/src/validation/joi/string.extensions.ts +1 -1
  72. package/dist/got/getGot.d.ts +0 -13
  73. package/dist/got/getGot.js +0 -262
  74. package/dist/got/got.model.d.ts +0 -59
  75. package/dist/got/got.model.js +0 -2
  76. package/src/got/getGot.ts +0 -305
  77. package/src/got/got.model.ts +0 -71
@@ -1,59 +0,0 @@
1
- import { AnyObject, CommonLogger } from '@naturalcycles/js-lib';
2
- import type { Options } from 'got';
3
- export interface GetGotOptions extends Options {
4
- /**
5
- * Set to `true` to enable all possible debug logging.
6
- * Not safe in prod (as it logs Responses), but great to use during development.
7
- */
8
- debug?: boolean;
9
- /**
10
- * @default false
11
- */
12
- logStart?: boolean;
13
- /**
14
- * Log when request is finished.
15
- *
16
- * @default false
17
- */
18
- logFinished?: boolean;
19
- /**
20
- * Log request object.
21
- *
22
- * @default false
23
- */
24
- logRequest?: boolean;
25
- /**
26
- * Log actual response object.
27
- *
28
- * @default false
29
- */
30
- logResponse?: boolean;
31
- /**
32
- * @default true
33
- * Set to false to exclude `prefixUrl` from logs (both success and error)
34
- */
35
- logWithPrefixUrl?: boolean;
36
- /**
37
- * @default true
38
- * Set to false to strip searchParams from url when logging (both success and error)
39
- */
40
- logWithSearchParams?: boolean;
41
- /**
42
- * Defaults to `console`
43
- */
44
- logger?: CommonLogger;
45
- /**
46
- * Max length of response object before it's truncated.
47
- *
48
- * @default 10_000
49
- */
50
- maxResponseLength?: number;
51
- }
52
- export interface GotRequestContext extends AnyObject {
53
- /**
54
- * Millisecond-timestamp of when the request was started. To be able to count "time spent".
55
- */
56
- started: number;
57
- err?: Error;
58
- retryCount?: number;
59
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/src/got/getGot.ts DELETED
@@ -1,305 +0,0 @@
1
- import { URL } from 'node:url'
2
- import { _since } from '@naturalcycles/js-lib'
3
- import got, {
4
- AfterResponseHook,
5
- BeforeErrorHook,
6
- BeforeRequestHook,
7
- BeforeRetryHook,
8
- Got,
9
- } from 'got'
10
- import { inspectAny } from '..'
11
- import { GetGotOptions, GotRequestContext } from './got.model'
12
-
13
- /**
14
- * Returns instance of Got with "reasonable defaults":
15
- *
16
- * 1. Error handler hook that prints helpful errors.
17
- * 2. Hooks that log start/end of request (optional, false by default).
18
- * 3. Reasonable defaults(tm), e.g non-infinite Timeout
19
- * 4. Preserves error stack traces (!) (experimental!)
20
- *
21
- * @deprecated `getGot` (together with `getKy`) is deprecated in favor of `getFetcher` of js-lib
22
- */
23
- export function getGot(opt: GetGotOptions = {}): Got {
24
- opt.logger ||= console
25
-
26
- if (opt.debug) {
27
- opt.logStart = opt.logFinished = opt.logResponse = opt.logRequest = true
28
- }
29
-
30
- return got.extend({
31
- // Most-important is to set to anything non-empty (so, requests don't "hang" by default).
32
- // Should be long enough to handle for slow responses from scaled cloud APIs in times of spikes
33
- // Ideally should be LESS than default Request timeout in backend-lib (so, it has a chance to error
34
- // before server times out with 503).
35
- //
36
- // UPD 2021-11-27
37
- // There are 2 types/strategies for requests:
38
- // 1. Optimized to get result no matter what. E.g in Cron jobs, where otherwise there'll be a job failure
39
- // 2. Part of the Backend request, where we better retry quickly and fail on timeout before Backend aborts it with "503 Request timeout"
40
- //
41
- // Here it's hard to set the default timeout right for both use-cases.
42
- // So, if it's important, you should override it according to your use-cases:
43
- // - set it longer for Type 1 (e.g 120 seconds)
44
- // - set it shorter for Type 2 (e.g 10/20 seconds)
45
- // Please beware of default Retry strategy of Got:
46
- // by default it will retry 2 times (after first try)
47
- // First delay between tries will be ~1 second, then ~2 seconds
48
- // Each retry it'll wait up to `timeout` (so, up to 60 seconds by default).
49
- // So, for 3 tries it multiplies your timeout by 3 (+3 seconds between the tries).
50
- // So, e.g 60 seconds timeout with 2 retries becomes up to 183 seconds.
51
- // Which definitely doesn't fit into default "RequestTimeout"
52
- timeout: 60_000,
53
- ...opt,
54
- handlers: [
55
- (options, next) => {
56
- options.context = {
57
- ...options.context,
58
- started: Date.now(),
59
- // This is to preserve original stack trace
60
- // https://github.com/sindresorhus/got/blob/main/documentation/async-stack-traces.md
61
- err: new Error('RequestError'),
62
- } as GotRequestContext
63
-
64
- return next(options)
65
- },
66
- ],
67
- hooks: {
68
- ...opt.hooks,
69
- beforeError: [
70
- ...(opt.hooks?.beforeError || []),
71
- // User hooks go BEFORE
72
- gotErrorHook(opt),
73
- ],
74
- beforeRequest: [
75
- gotBeforeRequestHook(opt),
76
- // User hooks go AFTER
77
- ...(opt.hooks?.beforeRequest || []),
78
- ],
79
- beforeRetry: [
80
- gotBeforeRetryHook(opt),
81
- // User hooks go AFTER
82
- ...(opt.hooks?.beforeRetry || []),
83
- ],
84
- afterResponse: [
85
- ...(opt.hooks?.afterResponse || []),
86
- // User hooks go BEFORE
87
- gotAfterResponseHook(opt),
88
- ],
89
- },
90
- })
91
- }
92
-
93
- /**
94
- * Without this hook (default behaviour):
95
- *
96
- * HTTPError: Response code 422 (Unprocessable Entity)
97
- * at EventEmitter.<anonymous> (.../node_modules/got/dist/source/as-promise.js:118:31)
98
- * at processTicksAndRejections (internal/process/task_queues.js:97:5) {
99
- * name: 'HTTPError'
100
- *
101
- *
102
- * With this hook:
103
- *
104
- * HTTPError 422 GET http://a.com/err?q=1 in 8 ms
105
- * {
106
- * message: 'Reference already exists',
107
- * documentation_url: 'https://developer.github.com/v3/git/refs/#create-a-reference'
108
- * }
109
- *
110
- * Features:
111
- * 1. Includes original method and URL (including e.g searchParams) in the error message.
112
- * 2. Includes response.body in the error message (limited length).
113
- * 3. Auto-detects and parses JSON response body (limited length).
114
- * 4. Includes time spent (gotBeforeRequestHook must also be enabled).
115
- * UPD: excluded now to allow automatic Sentry error grouping
116
- */
117
- function gotErrorHook(opt: GetGotOptions = {}): BeforeErrorHook {
118
- const { maxResponseLength = 10_000 } = opt
119
-
120
- return err => {
121
- const statusCode = err.response?.statusCode || 0
122
- const { method, url, prefixUrl } = err.options
123
- const shortUrl = getShortUrl(opt, url, prefixUrl)
124
- const { started, retryCount } = (err.request?.options.context || {}) as GotRequestContext
125
-
126
- const body = err.response?.body
127
- ? inspectAny(err.response.body, {
128
- maxLen: maxResponseLength,
129
- colors: false,
130
- })
131
- : err.message
132
-
133
- // We don't include Response/Body/Message in the log, because it's included in the Error thrown from here
134
- opt.logger!.log(
135
- [
136
- ' <<',
137
- statusCode,
138
- method,
139
- shortUrl,
140
- retryCount && `(retry ${retryCount})`,
141
- 'error',
142
- started && 'in ' + _since(started),
143
- ]
144
- .filter(Boolean)
145
- .join(' '),
146
- )
147
-
148
- // timings are not part of err.message to allow automatic error grouping in Sentry
149
- // Colors are not used, because there's high chance that this Error will be propagated all the way to the Frontend
150
- err.message = [[statusCode, method, shortUrl].filter(Boolean).join(' '), body]
151
- .filter(Boolean)
152
- .join('\n')
153
-
154
- const stack = (err.options.context as GotRequestContext)?.err?.stack
155
- if (stack) {
156
- const originalStack = err.stack.split('\n')
157
- let originalStackIndex = originalStack.findIndex(line => line.includes(' at '))
158
- if (originalStackIndex === -1) originalStackIndex = originalStack.length - 1
159
-
160
- // Skipping first line as it has RequestError: ...
161
- // Skipping second line as it's known to be from e.g at got_1.default.extend.handlers
162
- const syntheticStack = stack.split('\n').slice(2)
163
- let firstNonNodeModulesIndex = syntheticStack.findIndex(
164
- line => !line.includes('node_modules'),
165
- )
166
- if (firstNonNodeModulesIndex === -1) firstNonNodeModulesIndex = 0
167
-
168
- err.stack = [
169
- // First lines of original error
170
- ...originalStack.slice(0, originalStackIndex),
171
- // Other lines from "Synthetic error"
172
- ...syntheticStack.slice(firstNonNodeModulesIndex),
173
- ].join('\n')
174
- // err.stack += '\n --' + stack.replace('Error: RequestError', '')
175
- }
176
-
177
- return err
178
- }
179
- }
180
-
181
- function gotBeforeRequestHook(opt: GetGotOptions): BeforeRequestHook {
182
- return options => {
183
- if (opt.logStart) {
184
- const { retryCount } = options.context as GotRequestContext
185
- const shortUrl = getShortUrl(opt, options.url, options.prefixUrl)
186
- opt.logger!.log(
187
- [' >>', options.method, shortUrl, retryCount && `(retry ${retryCount})`].join(' '),
188
- )
189
- }
190
-
191
- if (opt.logRequest) {
192
- const body = options.json || options.body
193
-
194
- if (body) {
195
- opt.logger!.log(body)
196
- }
197
- }
198
- }
199
- }
200
-
201
- // Here we log always, because it's similar to ErrorHook - we always log errors
202
- // Because Retries are always result of some Error
203
- function gotBeforeRetryHook(opt: GetGotOptions): BeforeRetryHook {
204
- const { maxResponseLength = 10_000 } = opt
205
-
206
- return (options, err, retryCount) => {
207
- // opt.logger!.log('beforeRetry', retryCount)
208
- const statusCode = err?.response?.statusCode || 0
209
-
210
- if (statusCode && statusCode < 300) {
211
- // todo: possibly remove the log message completely in the future
212
- // opt.logger!.log(
213
- // `skipping got.beforeRetry hook as statusCode is ${statusCode}, err.msg is ${err?.message}`,
214
- // )
215
- return
216
- }
217
-
218
- const { method, url, prefixUrl } = options
219
- const shortUrl = getShortUrl(opt, url, prefixUrl)
220
- const { started } = options.context as GotRequestContext
221
- Object.assign(options.context, { retryCount })
222
-
223
- const body = err?.response?.body
224
- ? inspectAny(err.response.body, {
225
- maxLen: maxResponseLength,
226
- colors: false,
227
- })
228
- : err?.message
229
-
230
- // We don't include Response/Body/Message in the log, because it's included in the Error thrown from here
231
- opt.logger!.warn(
232
- [
233
- [
234
- ' <<',
235
- statusCode,
236
- method,
237
- shortUrl,
238
- retryCount && retryCount > 1 ? `(retry ${retryCount - 1})` : '(first try)',
239
- 'error',
240
- started && 'in ' + _since(started),
241
- ]
242
- .filter(Boolean)
243
- .join(' '),
244
- body,
245
- ]
246
- .filter(Boolean)
247
- .join('\n'),
248
- )
249
- }
250
- }
251
-
252
- // AfterResponseHook is never called on Error
253
- // So, coloredHttpCode(resp.statusCode) is probably useless
254
- function gotAfterResponseHook(opt: GetGotOptions = {}): AfterResponseHook {
255
- return resp => {
256
- const success = resp.statusCode >= 200 && resp.statusCode < 400
257
-
258
- // Errors are not logged here, as they're logged by gotErrorHook
259
- if (opt.logFinished && success) {
260
- const { started, retryCount } = resp.request.options.context as GotRequestContext
261
- const { url, prefixUrl, method } = resp.request.options
262
- const shortUrl = getShortUrl(opt, url, prefixUrl)
263
-
264
- opt.logger!.log(
265
- [
266
- ' <<',
267
- resp.statusCode,
268
- method,
269
- shortUrl,
270
- retryCount && `(retry ${retryCount - 1})`,
271
- started && 'in ' + _since(started),
272
- ]
273
- .filter(Boolean)
274
- .join(' '),
275
- )
276
- // console.log(`afterResp! ${resp.request.options.method} ${resp.url}`, { context: resp.request.options.context })
277
- }
278
-
279
- // Error responses are not logged, cause they're included in Error message already
280
- if (opt.logResponse && success) {
281
- opt.logger!.log(inspectAny(resp.body, { maxLen: opt.maxResponseLength }))
282
- }
283
-
284
- return resp
285
- }
286
- }
287
-
288
- function getShortUrl(opt: GetGotOptions, url: URL, prefixUrl?: string): string {
289
- if (url.password) {
290
- url = new URL(url.toString()) // prevent original url mutation
291
- url.password = '[redacted]'
292
- }
293
-
294
- let shortUrl = url.toString()
295
-
296
- if (opt.logWithSearchParams === false) {
297
- shortUrl = shortUrl.split('?')[0]!
298
- }
299
-
300
- if (opt.logWithPrefixUrl === false && prefixUrl && shortUrl.startsWith(prefixUrl)) {
301
- shortUrl = shortUrl.slice(prefixUrl.length)
302
- }
303
-
304
- return shortUrl
305
- }
@@ -1,71 +0,0 @@
1
- import { AnyObject, CommonLogger } from '@naturalcycles/js-lib'
2
- import type { Options } from 'got'
3
-
4
- export interface GetGotOptions extends Options {
5
- /**
6
- * Set to `true` to enable all possible debug logging.
7
- * Not safe in prod (as it logs Responses), but great to use during development.
8
- */
9
- debug?: boolean
10
-
11
- /**
12
- * @default false
13
- */
14
- logStart?: boolean
15
-
16
- /**
17
- * Log when request is finished.
18
- *
19
- * @default false
20
- */
21
- logFinished?: boolean
22
-
23
- /**
24
- * Log request object.
25
- *
26
- * @default false
27
- */
28
- logRequest?: boolean
29
-
30
- /**
31
- * Log actual response object.
32
- *
33
- * @default false
34
- */
35
- logResponse?: boolean
36
-
37
- /**
38
- * @default true
39
- * Set to false to exclude `prefixUrl` from logs (both success and error)
40
- */
41
- logWithPrefixUrl?: boolean
42
-
43
- /**
44
- * @default true
45
- * Set to false to strip searchParams from url when logging (both success and error)
46
- */
47
- logWithSearchParams?: boolean
48
-
49
- /**
50
- * Defaults to `console`
51
- */
52
- logger?: CommonLogger
53
-
54
- /**
55
- * Max length of response object before it's truncated.
56
- *
57
- * @default 10_000
58
- */
59
- maxResponseLength?: number
60
- }
61
-
62
- export interface GotRequestContext extends AnyObject {
63
- /**
64
- * Millisecond-timestamp of when the request was started. To be able to count "time spent".
65
- */
66
- started: number
67
-
68
- err?: Error
69
-
70
- retryCount?: number
71
- }