@ix-xs/node-comfort 1.1.31 → 2.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 (77) hide show
  1. package/CHANGELOG.md +190 -0
  2. package/LICENSE +21 -0
  3. package/README.md +210 -748
  4. package/index.js +84 -13
  5. package/package.json +201 -21
  6. package/src/Arr.js +901 -0
  7. package/src/Async.js +585 -0
  8. package/src/Cache.js +329 -0
  9. package/src/Checker.js +979 -188
  10. package/src/Cli.js +1034 -0
  11. package/src/Color.js +415 -0
  12. package/src/Crypto.js +707 -0
  13. package/src/Emitter.js +289 -0
  14. package/src/Env.js +555 -0
  15. package/src/FS.js +1483 -768
  16. package/src/Func.js +692 -0
  17. package/src/Http.js +538 -0
  18. package/src/Id.js +418 -0
  19. package/src/Logger.js +739 -307
  20. package/src/Num.js +849 -0
  21. package/src/Obj.js +904 -0
  22. package/src/SQLite.js +1308 -994
  23. package/src/Schema.js +1586 -0
  24. package/src/Str.js +999 -0
  25. package/src/Sys.js +511 -0
  26. package/src/Time.js +1323 -0
  27. package/src/Utils.js +321 -325
  28. package/src/errors.js +292 -0
  29. package/types/index.d.ts +693 -120
  30. package/types/src/Arr.d.ts +562 -0
  31. package/types/src/Arr.d.ts.map +1 -0
  32. package/types/src/Async.d.ts +321 -0
  33. package/types/src/Async.d.ts.map +1 -0
  34. package/types/src/Cache.d.ts +195 -0
  35. package/types/src/Cache.d.ts.map +1 -0
  36. package/types/src/Checker.d.ts +609 -81
  37. package/types/src/Checker.d.ts.map +1 -1
  38. package/types/src/Cli.d.ts +582 -0
  39. package/types/src/Cli.d.ts.map +1 -0
  40. package/types/src/Color.d.ts +294 -0
  41. package/types/src/Color.d.ts.map +1 -0
  42. package/types/src/Crypto.d.ts +534 -0
  43. package/types/src/Crypto.d.ts.map +1 -0
  44. package/types/src/Emitter.d.ts +170 -0
  45. package/types/src/Emitter.d.ts.map +1 -0
  46. package/types/src/Env.d.ts +382 -0
  47. package/types/src/Env.d.ts.map +1 -0
  48. package/types/src/FS.d.ts +709 -201
  49. package/types/src/FS.d.ts.map +1 -1
  50. package/types/src/Func.d.ts +455 -0
  51. package/types/src/Func.d.ts.map +1 -0
  52. package/types/src/Http.d.ts +374 -0
  53. package/types/src/Http.d.ts.map +1 -0
  54. package/types/src/Id.d.ts +200 -0
  55. package/types/src/Id.d.ts.map +1 -0
  56. package/types/src/Logger.d.ts +374 -24
  57. package/types/src/Logger.d.ts.map +1 -1
  58. package/types/src/Num.d.ts +578 -0
  59. package/types/src/Num.d.ts.map +1 -0
  60. package/types/src/Obj.d.ts +475 -0
  61. package/types/src/Obj.d.ts.map +1 -0
  62. package/types/src/SQLite.d.ts +647 -305
  63. package/types/src/SQLite.d.ts.map +1 -1
  64. package/types/src/Schema.d.ts +940 -0
  65. package/types/src/Schema.d.ts.map +1 -0
  66. package/types/src/Str.d.ts +696 -0
  67. package/types/src/Str.d.ts.map +1 -0
  68. package/types/src/Sys.d.ts +269 -0
  69. package/types/src/Sys.d.ts.map +1 -0
  70. package/types/src/Time.d.ts +664 -0
  71. package/types/src/Time.d.ts.map +1 -0
  72. package/types/src/Utils.d.ts +154 -102
  73. package/types/src/Utils.d.ts.map +1 -1
  74. package/types/src/errors.d.ts +292 -0
  75. package/types/src/errors.d.ts.map +1 -0
  76. package/tsconfig.json +0 -18
  77. package/types/index.d.ts.map +0 -1
package/src/errors.js ADDED
@@ -0,0 +1,292 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * The errors node-comfort throws. They all extend `NodeComfortError` (itself
5
+ * a regular `Error`) and carry a stable `code`, so you can branch on the
6
+ * kind of failure without parsing messages.
7
+ *
8
+ * @example
9
+ * try {
10
+ * await nc.http.get("https://api.example.com/users/42");
11
+ * } catch (error) {
12
+ * if (error instanceof nc.errors.HttpError && error.status === 404) return null;
13
+ * throw error;
14
+ * }
15
+ */
16
+
17
+ /**
18
+ * Options shared by every error constructor.
19
+ * @typedef {object} NodeComfortErrorOptions
20
+ * @property {string} [code] Machine-readable code, like `"ETIMEDOUT"`.
21
+ * @property {unknown} [cause] The error that caused this one, kept as `error.cause`.
22
+ */
23
+
24
+ /**
25
+ * Base class of every node-comfort error. `name` is the class name and
26
+ * `code` a stable identifier.
27
+ *
28
+ * @example
29
+ * if (error instanceof nc.errors.NodeComfortError) logger.warn(error.code);
30
+ */
31
+ class NodeComfortError extends Error {
32
+ /**
33
+ * @param {string} message
34
+ * @param {NodeComfortErrorOptions} [options]
35
+ */
36
+ constructor(message, options = {}) {
37
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
38
+ /** The class name, like `"TimeoutError"`. */
39
+ this.name = new.target.name;
40
+ /** Stable, machine-readable code. */
41
+ this.code = options.code ?? "ERR_NODE_COMFORT";
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Thrown by `nc.assert()` and `nc.assertType()`.
47
+ *
48
+ * @example
49
+ * nc.assert(user, "User is required");
50
+ */
51
+ class AssertionError extends NodeComfortError {
52
+ /**
53
+ * @param {string} [message="Assertion failed"]
54
+ * @param {NodeComfortErrorOptions} [options]
55
+ */
56
+ constructor(message = "Assertion failed", options = {}) {
57
+ super(message, { code: "ERR_ASSERTION", ...options });
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Thrown when something takes too long: `func.timeout`, `async.poll`, HTTP
63
+ * requests, `emitter.waitFor`...
64
+ *
65
+ * @example
66
+ * try {
67
+ * await nc.func.timeout(slowTask(), 1000);
68
+ * } catch (error) {
69
+ * if (error instanceof nc.errors.TimeoutError) console.log(`Gave up after ${error.timeout}ms`);
70
+ * }
71
+ */
72
+ class TimeoutError extends NodeComfortError {
73
+ /**
74
+ * @param {string} [message="Operation timed out"]
75
+ * @param {NodeComfortErrorOptions & { timeout?: number }} [options] Can include the time limit in milliseconds.
76
+ */
77
+ constructor(message = "Operation timed out", options = {}) {
78
+ super(message, { code: "ETIMEDOUT", ...options });
79
+ /** The time limit in milliseconds, when known. */
80
+ this.timeout = options.timeout;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Thrown when an operation is cancelled with an `AbortSignal`. Its name is
86
+ * `"AbortError"`, like native abort errors, so existing checks keep working.
87
+ */
88
+ class AbortError extends NodeComfortError {
89
+ /**
90
+ * @param {string} [message="The operation was aborted"]
91
+ * @param {NodeComfortErrorOptions} [options] Usually `{ cause: signal.reason }`.
92
+ */
93
+ constructor(message = "The operation was aborted", options = {}) {
94
+ super(message, { code: "ABORT_ERR", ...options });
95
+ }
96
+ }
97
+
98
+ /**
99
+ * One problem found while validating data.
100
+ * @typedef {object} ValidationIssue
101
+ * @property {Array<string|number>} path Where the problem is, like `["user", "emails", 0]`. Empty for the root value.
102
+ * @property {string} code What went wrong: `"invalid_type"`, `"too_small"`, `"invalid_string"`, `"custom"`...
103
+ * @property {string} message A message you can show to users.
104
+ * @property {string} [expected] The expected type, for type errors.
105
+ * @property {string} [received] The received type, for type errors.
106
+ */
107
+
108
+ /**
109
+ * Thrown when data doesn't match a schema or when environment variables are
110
+ * invalid. `issues` lists every problem, not just the first one.
111
+ *
112
+ * @example
113
+ * try {
114
+ * User.parse(body);
115
+ * } catch (error) {
116
+ * if (error instanceof nc.errors.ValidationError) return res.status(400).json(error.flatten());
117
+ * throw error;
118
+ * }
119
+ */
120
+ class ValidationError extends NodeComfortError {
121
+ /**
122
+ * @param {ValidationIssue[]} issues
123
+ * @param {NodeComfortErrorOptions & { message?: string }} [options]
124
+ */
125
+ constructor(issues, options = {}) {
126
+ super(options.message ?? ValidationError.format(issues), { code: "ERR_VALIDATION", ...options });
127
+ /** Every problem found, in order. */
128
+ this.issues = issues;
129
+ }
130
+
131
+ /**
132
+ * Turns issues into a readable message, one line per issue.
133
+ *
134
+ * @param {ValidationIssue[]} issues
135
+ * @returns {string}
136
+ */
137
+ static format(issues) {
138
+ if (!issues.length) return "Validation failed";
139
+ const lines = issues.map((issue) => {
140
+ const where = issue.path.length ? issue.path.join(".") : "(root)";
141
+ return ` • ${where}: ${issue.message}`;
142
+ });
143
+ return `Validation failed with ${issues.length} issue${issues.length > 1 ? "s" : ""}:\n${lines.join("\n")}`;
144
+ }
145
+
146
+ /**
147
+ * Groups messages by path, which is handy for forms.
148
+ *
149
+ * @example
150
+ * error.flatten(); // { email: ["Invalid email address"], age: ["Must be at least 18"] }
151
+ *
152
+ * @returns {Record<string, string[]>} Messages by dotted path (`""` for the root).
153
+ */
154
+ flatten() {
155
+ /** @type {Record<string, string[]>} */
156
+ const out = {};
157
+ for (const issue of this.issues) {
158
+ const key = issue.path.join(".");
159
+ (out[key] ??= []).push(issue.message);
160
+ }
161
+ return out;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Thrown by `nc.http` when the response status isn't 2xx (unless you pass
167
+ * `throwHttpErrors: false`), and for network failures (`status` 0).
168
+ *
169
+ * @example
170
+ * try {
171
+ * await nc.http.get(url);
172
+ * } catch (error) {
173
+ * if (error instanceof nc.errors.HttpError) console.log(error.status, error.data);
174
+ * }
175
+ */
176
+ class HttpError extends NodeComfortError {
177
+ /**
178
+ * @param {string} message
179
+ * @param {NodeComfortErrorOptions & { status?: number, statusText?: string, url?: string, method?: string, headers?: Record<string, string>, data?: unknown }} [options]
180
+ */
181
+ constructor(message, options = {}) {
182
+ super(message, { code: "ERR_HTTP", ...options });
183
+ /** HTTP status, like `404`. `0` when no response came back. */
184
+ this.status = options.status ?? 0;
185
+ /** HTTP status text, like `"Not Found"`. */
186
+ this.statusText = options.statusText ?? "";
187
+ /** The requested URL. */
188
+ this.url = options.url ?? "";
189
+ /** The HTTP method, like `"GET"`. */
190
+ this.method = options.method ?? "GET";
191
+ /** Response headers, with lower-cased names. */
192
+ this.headers = options.headers ?? {};
193
+ /** The response body: parsed JSON when possible, text otherwise. */
194
+ this.data = options.data;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Thrown by `nc.crypto.verifyJWT()`. The `code` tells you why:
200
+ * `ERR_JWT_MALFORMED`, `ERR_JWT_ALGORITHM`, `ERR_JWT_SIGNATURE`,
201
+ * `ERR_JWT_EXPIRED`, `ERR_JWT_NOT_BEFORE` or `ERR_JWT_CLAIM`.
202
+ *
203
+ * @example
204
+ * try {
205
+ * return nc.crypto.verifyJWT(token, secret);
206
+ * } catch (error) {
207
+ * if (error.code === "ERR_JWT_EXPIRED") return refreshSession();
208
+ * throw error;
209
+ * }
210
+ */
211
+ class JWTError extends NodeComfortError {
212
+ /**
213
+ * @param {string} message
214
+ * @param {NodeComfortErrorOptions & { expiredAt?: Date }} [options]
215
+ */
216
+ constructor(message, options = {}) {
217
+ super(message, { code: "ERR_JWT", ...options });
218
+ /** When the token expired. Only set for `ERR_JWT_EXPIRED`. */
219
+ this.expiredAt = options.expiredAt;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Thrown by `nc.sys.run()` and `nc.sys.exec()` when a command fails, is
225
+ * killed or times out. Its output is kept on the error.
226
+ *
227
+ * @example
228
+ * try {
229
+ * await nc.sys.run("git", ["push"]);
230
+ * } catch (error) {
231
+ * console.error(error.exitCode, error.stderr);
232
+ * }
233
+ */
234
+ class ProcessError extends NodeComfortError {
235
+ /**
236
+ * @param {string} message
237
+ * @param {NodeComfortErrorOptions & { command?: string, exitCode?: number | null, signal?: string | null, stdout?: string, stderr?: string, timedOut?: boolean }} [options]
238
+ */
239
+ constructor(message, options = {}) {
240
+ super(message, { code: options.timedOut ? "ETIMEDOUT" : "ERR_PROCESS", ...options });
241
+ /** The command that ran. */
242
+ this.command = options.command ?? "";
243
+ /** Exit code, or `null` if a signal killed the process. */
244
+ this.exitCode = options.exitCode ?? null;
245
+ /** The signal that killed the process, like `"SIGTERM"`. */
246
+ this.signal = options.signal ?? null;
247
+ /** Everything written to stdout. */
248
+ this.stdout = options.stdout ?? "";
249
+ /** Everything written to stderr. */
250
+ this.stderr = options.stderr ?? "";
251
+ /** `true` if the process was killed for exceeding its `timeout`. */
252
+ this.timedOut = options.timedOut ?? false;
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Thrown by `nc.SQLite` when a statement fails. Check `sqliteCode` to handle
258
+ * specific cases like a duplicate value.
259
+ *
260
+ * @example
261
+ * try {
262
+ * db.insert("users", { email });
263
+ * } catch (error) {
264
+ * if (error.sqliteCode === "SQLITE_CONSTRAINT_UNIQUE") return "Email already taken";
265
+ * throw error;
266
+ * }
267
+ */
268
+ class SQLiteError extends NodeComfortError {
269
+ /**
270
+ * @param {string} message
271
+ * @param {NodeComfortErrorOptions & { sql?: string, sqliteCode?: string }} [options]
272
+ */
273
+ constructor(message, options = {}) {
274
+ super(message, { code: "ERR_SQLITE", ...options });
275
+ /** The SQL that failed, when there is one. */
276
+ this.sql = options.sql;
277
+ /** SQLite's error code, like `"SQLITE_CONSTRAINT_UNIQUE"`, when known. */
278
+ this.sqliteCode = options.sqliteCode;
279
+ }
280
+ }
281
+
282
+ module.exports = {
283
+ NodeComfortError,
284
+ AssertionError,
285
+ TimeoutError,
286
+ AbortError,
287
+ ValidationError,
288
+ HttpError,
289
+ JWTError,
290
+ ProcessError,
291
+ SQLiteError,
292
+ };