@settlemint/sdk-utils 2.3.2-pr3dad35bd → 2.3.2-pr472d8b55

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 (97) hide show
  1. package/dist/environment.cjs +17705 -384
  2. package/dist/environment.cjs.map +1 -1
  3. package/dist/environment.d.cts +263 -98
  4. package/dist/environment.d.ts +263 -98
  5. package/dist/environment.js +17743 -0
  6. package/dist/environment.js.map +1 -0
  7. package/dist/filesystem.cjs +6746 -113
  8. package/dist/filesystem.cjs.map +1 -1
  9. package/dist/filesystem.d.cts +22 -1
  10. package/dist/filesystem.d.ts +22 -1
  11. package/dist/filesystem.js +6766 -0
  12. package/dist/filesystem.js.map +1 -0
  13. package/dist/http.cjs +211 -157
  14. package/dist/http.cjs.map +1 -1
  15. package/dist/http.d.cts +9 -1
  16. package/dist/http.d.ts +9 -1
  17. package/dist/http.js +226 -0
  18. package/dist/http.js.map +1 -0
  19. package/dist/index.cjs +287 -171
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +9 -0
  22. package/dist/index.d.ts +9 -0
  23. package/dist/index.js +306 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/json.cjs +83 -0
  26. package/dist/json.cjs.map +1 -0
  27. package/dist/json.d.cts +56 -0
  28. package/dist/json.d.ts +56 -0
  29. package/dist/json.js +80 -0
  30. package/dist/json.js.map +1 -0
  31. package/dist/logging.cjs +209 -137
  32. package/dist/logging.cjs.map +1 -1
  33. package/dist/logging.d.cts +23 -14
  34. package/dist/logging.d.ts +23 -14
  35. package/dist/logging.js +221 -0
  36. package/dist/logging.js.map +1 -0
  37. package/dist/package-manager.cjs +7350 -173
  38. package/dist/package-manager.cjs.map +1 -1
  39. package/dist/package-manager.d.cts +26 -3
  40. package/dist/package-manager.d.ts +26 -3
  41. package/dist/package-manager.js +7382 -0
  42. package/dist/package-manager.js.map +1 -0
  43. package/dist/retry.cjs +137 -0
  44. package/dist/retry.cjs.map +1 -0
  45. package/dist/retry.d.cts +19 -0
  46. package/dist/retry.d.ts +19 -0
  47. package/dist/retry.js +136 -0
  48. package/dist/retry.js.map +1 -0
  49. package/dist/runtime.cjs +58 -40
  50. package/dist/runtime.cjs.map +1 -1
  51. package/dist/runtime.d.cts +3 -0
  52. package/dist/runtime.d.ts +3 -0
  53. package/dist/runtime.js +45 -0
  54. package/dist/runtime.js.map +1 -0
  55. package/dist/string.cjs +76 -0
  56. package/dist/string.cjs.map +1 -0
  57. package/dist/string.d.cts +58 -0
  58. package/dist/string.d.ts +58 -0
  59. package/dist/string.js +72 -0
  60. package/dist/string.js.map +1 -0
  61. package/dist/terminal.cjs +423 -229
  62. package/dist/terminal.cjs.map +1 -1
  63. package/dist/terminal.d.cts +54 -24
  64. package/dist/terminal.d.ts +54 -24
  65. package/dist/terminal.js +438 -0
  66. package/dist/terminal.js.map +1 -0
  67. package/dist/url.cjs +25 -0
  68. package/dist/url.cjs.map +1 -0
  69. package/dist/url.d.cts +20 -0
  70. package/dist/url.d.ts +20 -0
  71. package/dist/url.js +24 -0
  72. package/dist/url.js.map +1 -0
  73. package/dist/validation.cjs +10486 -193
  74. package/dist/validation.cjs.map +1 -1
  75. package/dist/validation.d.cts +124 -94
  76. package/dist/validation.d.ts +124 -94
  77. package/dist/validation.js +10482 -0
  78. package/dist/validation.js.map +1 -0
  79. package/package.json +6 -6
  80. package/dist/environment.mjs +0 -384
  81. package/dist/environment.mjs.map +0 -1
  82. package/dist/filesystem.mjs +0 -105
  83. package/dist/filesystem.mjs.map +0 -1
  84. package/dist/http.mjs +0 -146
  85. package/dist/http.mjs.map +0 -1
  86. package/dist/index.mjs +0 -164
  87. package/dist/index.mjs.map +0 -1
  88. package/dist/logging.mjs +0 -123
  89. package/dist/logging.mjs.map +0 -1
  90. package/dist/package-manager.mjs +0 -167
  91. package/dist/package-manager.mjs.map +0 -1
  92. package/dist/runtime.mjs +0 -23
  93. package/dist/runtime.mjs.map +0 -1
  94. package/dist/terminal.mjs +0 -230
  95. package/dist/terminal.mjs.map +0 -1
  96. package/dist/validation.mjs +0 -161
  97. package/dist/validation.mjs.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,199 +1,315 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
1
 
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- camelCaseToWords: () => camelCaseToWords,
24
- capitalizeFirstLetter: () => capitalizeFirstLetter,
25
- extractBaseUrlBeforeSegment: () => extractBaseUrlBeforeSegment,
26
- extractJsonObject: () => extractJsonObject,
27
- makeJsonStringifiable: () => makeJsonStringifiable,
28
- replaceUnderscoresAndHyphensWithSpaces: () => replaceUnderscoresAndHyphensWithSpaces,
29
- retryWhenFailed: () => retryWhenFailed,
30
- truncate: () => truncate,
31
- tryParseJson: () => tryParseJson
32
- });
33
- module.exports = __toCommonJS(index_exports);
34
-
35
- // src/json.ts
2
+ //#region src/json.ts
3
+ /**
4
+ * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.
5
+ *
6
+ * @param value - The JSON string to parse
7
+ * @param defaultValue - The value to return if parsing fails or results in null/undefined
8
+ * @returns The parsed JSON value as type T, or the default value if parsing fails
9
+ *
10
+ * @example
11
+ * import { tryParseJson } from "@settlemint/sdk-utils";
12
+ *
13
+ * const config = tryParseJson<{ port: number }>(
14
+ * '{"port": 3000}',
15
+ * { port: 8080 }
16
+ * );
17
+ * // Returns: { port: 3000 }
18
+ *
19
+ * const invalid = tryParseJson<string[]>(
20
+ * 'invalid json',
21
+ * []
22
+ * );
23
+ * // Returns: []
24
+ */
36
25
  function tryParseJson(value, defaultValue = null) {
37
- try {
38
- const parsed = JSON.parse(value);
39
- if (parsed === void 0 || parsed === null) {
40
- return defaultValue;
41
- }
42
- return parsed;
43
- } catch (err) {
44
- return defaultValue;
45
- }
26
+ try {
27
+ const parsed = JSON.parse(value);
28
+ if (parsed === undefined || parsed === null) {
29
+ return defaultValue;
30
+ }
31
+ return parsed;
32
+ } catch (err) {
33
+ return defaultValue;
34
+ }
46
35
  }
36
+ /**
37
+ * Extracts a JSON object from a string.
38
+ *
39
+ * @param value - The string to extract the JSON object from
40
+ * @returns The parsed JSON object, or null if no JSON object is found
41
+ * @throws {Error} If the input string is too long (longer than 5000 characters)
42
+ * @example
43
+ * import { extractJsonObject } from "@settlemint/sdk-utils";
44
+ *
45
+ * const json = extractJsonObject<{ port: number }>(
46
+ * 'port info: {"port": 3000}',
47
+ * );
48
+ * // Returns: { port: 3000 }
49
+ */
47
50
  function extractJsonObject(value) {
48
- if (value.length > 5e3) {
49
- throw new Error("Input too long");
50
- }
51
- const result = /\{([\s\S]*)\}/.exec(value);
52
- if (!result) {
53
- return null;
54
- }
55
- return tryParseJson(result[0]);
51
+ if (value.length > 5e3) {
52
+ throw new Error("Input too long");
53
+ }
54
+ const result = /\{([\s\S]*)\}/.exec(value);
55
+ if (!result) {
56
+ return null;
57
+ }
58
+ return tryParseJson(result[0]);
56
59
  }
60
+ /**
61
+ * Converts a value to a JSON stringifiable format.
62
+ *
63
+ * @param value - The value to convert
64
+ * @returns The JSON stringifiable value
65
+ *
66
+ * @example
67
+ * import { makeJsonStringifiable } from "@settlemint/sdk-utils";
68
+ *
69
+ * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });
70
+ * // Returns: '{"amount":"1000"}'
71
+ */
57
72
  function makeJsonStringifiable(value) {
58
- if (value === void 0 || value === null) {
59
- return value;
60
- }
61
- return tryParseJson(
62
- JSON.stringify(
63
- value,
64
- (_, value2) => typeof value2 === "bigint" ? value2.toString() : value2
65
- // return everything else unchanged
66
- )
67
- );
73
+ if (value === undefined || value === null) {
74
+ return value;
75
+ }
76
+ return tryParseJson(JSON.stringify(value, (_, value$1) => typeof value$1 === "bigint" ? value$1.toString() : value$1));
68
77
  }
69
78
 
70
- // src/logging/mask-tokens.ts
71
- var maskTokens = (output) => {
72
- return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
79
+ //#endregion
80
+ //#region src/logging/mask-tokens.ts
81
+ /**
82
+ * Masks sensitive SettleMint tokens in output text by replacing them with asterisks.
83
+ * Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT).
84
+ *
85
+ * @param output - The text string that may contain sensitive tokens
86
+ * @returns The text with any sensitive tokens masked with asterisks
87
+ * @example
88
+ * import { maskTokens } from "@settlemint/sdk-utils/terminal";
89
+ *
90
+ * // Masks a token in text
91
+ * const masked = maskTokens("Token: sm_pat_****"); // "Token: ***"
92
+ */
93
+ const maskTokens = (output) => {
94
+ return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
73
95
  };
74
96
 
75
- // src/logging/logger.ts
97
+ //#endregion
98
+ //#region src/logging/logger.ts
99
+ /**
100
+ * Creates a simple logger with configurable log level
101
+ *
102
+ * @param options - Configuration options for the logger
103
+ * @param options.level - The minimum log level to output (default: warn)
104
+ * @param options.prefix - The prefix to add to the log message (default: "")
105
+ * @returns A logger instance with debug, info, warn, and error methods
106
+ *
107
+ * @example
108
+ * import { createLogger } from "@/utils/logging/logger";
109
+ *
110
+ * const logger = createLogger({ level: 'info' });
111
+ *
112
+ * logger.info('User logged in', { userId: '123' });
113
+ * logger.error('Operation failed', new Error('Connection timeout'));
114
+ */
76
115
  function createLogger(options = {}) {
77
- const { level = "warn", prefix = "" } = options;
78
- const logLevels = {
79
- debug: 0,
80
- info: 1,
81
- warn: 2,
82
- error: 3,
83
- none: 4
84
- };
85
- const currentLevelValue = logLevels[level];
86
- const formatArgs = (args) => {
87
- if (args.length === 0 || args.every((arg) => arg === void 0 || arg === null)) {
88
- return "";
89
- }
90
- const formatted = args.map((arg) => {
91
- if (arg instanceof Error) {
92
- return `
93
- ${arg.stack || arg.message}`;
94
- }
95
- if (typeof arg === "object" && arg !== null) {
96
- return `
97
- ${JSON.stringify(arg, null, 2)}`;
98
- }
99
- return ` ${String(arg)}`;
100
- }).join("");
101
- return `, args:${formatted}`;
102
- };
103
- const shouldLog = (level2) => {
104
- return logLevels[level2] >= currentLevelValue;
105
- };
106
- return {
107
- debug: (message, ...args) => {
108
- if (shouldLog("debug")) {
109
- console.debug(`\x1B[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
110
- }
111
- },
112
- info: (message, ...args) => {
113
- if (shouldLog("info")) {
114
- console.info(`\x1B[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
115
- }
116
- },
117
- warn: (message, ...args) => {
118
- if (shouldLog("warn")) {
119
- console.warn(`\x1B[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
120
- }
121
- },
122
- error: (message, ...args) => {
123
- if (shouldLog("error")) {
124
- console.error(`\x1B[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
125
- }
126
- }
127
- };
116
+ const { level = "warn", prefix = "" } = options;
117
+ const logLevels = {
118
+ debug: 0,
119
+ info: 1,
120
+ warn: 2,
121
+ error: 3,
122
+ none: 4
123
+ };
124
+ const currentLevelValue = logLevels[level];
125
+ const formatArgs = (args) => {
126
+ if (args.length === 0 || args.every((arg) => arg === undefined || arg === null)) {
127
+ return "";
128
+ }
129
+ const formatted = args.map((arg) => {
130
+ if (arg instanceof Error) {
131
+ return `\n${arg.stack || arg.message}`;
132
+ }
133
+ if (typeof arg === "object" && arg !== null) {
134
+ return `\n${JSON.stringify(arg, null, 2)}`;
135
+ }
136
+ return ` ${String(arg)}`;
137
+ }).join("");
138
+ return `, args:${formatted}`;
139
+ };
140
+ const shouldLog = (level$1) => {
141
+ return logLevels[level$1] >= currentLevelValue;
142
+ };
143
+ return {
144
+ debug: (message, ...args) => {
145
+ if (shouldLog("debug")) {
146
+ console.debug(`\x1b[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
147
+ }
148
+ },
149
+ info: (message, ...args) => {
150
+ if (shouldLog("info")) {
151
+ console.info(`\x1b[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
152
+ }
153
+ },
154
+ warn: (message, ...args) => {
155
+ if (shouldLog("warn")) {
156
+ console.warn(`\x1b[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
157
+ }
158
+ },
159
+ error: (message, ...args) => {
160
+ if (shouldLog("error")) {
161
+ console.error(`\x1b[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
162
+ }
163
+ }
164
+ };
128
165
  }
129
- var logger = createLogger();
166
+ /**
167
+ * Default logger instance with standard configuration
168
+ */
169
+ const logger = createLogger();
130
170
 
131
- // src/retry.ts
171
+ //#endregion
172
+ //#region src/retry.ts
173
+ /**
174
+ * Retry a function when it fails.
175
+ * @param fn - The function to retry.
176
+ * @param maxRetries - The maximum number of retries.
177
+ * @param initialSleepTime - The initial time to sleep between exponential backoff retries.
178
+ * @param stopOnError - The function to stop on error.
179
+ * @returns The result of the function or undefined if it fails.
180
+ * @example
181
+ * import { retryWhenFailed } from "@settlemint/sdk-utils";
182
+ * import { readFile } from "node:fs/promises";
183
+ *
184
+ * const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
185
+ */
132
186
  async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
133
- let retries = 0;
134
- const maxAttempts = maxRetries + 1;
135
- while (retries < maxAttempts) {
136
- try {
137
- return await fn();
138
- } catch (e) {
139
- const error = e;
140
- if (typeof stopOnError === "function") {
141
- if (stopOnError(error)) {
142
- throw error;
143
- }
144
- }
145
- if (retries >= maxRetries) {
146
- throw e;
147
- }
148
- const baseDelay = 2 ** retries * initialSleepTime;
149
- const jitterAmount = initialSleepTime * (Math.random() / 10);
150
- const delay = baseDelay + jitterAmount;
151
- retries += 1;
152
- logger.warn(
153
- `An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`
154
- );
155
- await new Promise((resolve) => setTimeout(resolve, delay));
156
- }
157
- }
158
- throw new Error("Retry failed");
187
+ let retries = 0;
188
+ const maxAttempts = maxRetries + 1;
189
+ while (retries < maxAttempts) {
190
+ try {
191
+ return await fn();
192
+ } catch (e) {
193
+ const error = e;
194
+ if (typeof stopOnError === "function") {
195
+ if (stopOnError(error)) {
196
+ throw error;
197
+ }
198
+ }
199
+ if (retries >= maxRetries) {
200
+ throw e;
201
+ }
202
+ const baseDelay = 2 ** retries * initialSleepTime;
203
+ const jitterAmount = initialSleepTime * (Math.random() / 10);
204
+ const delay = baseDelay + jitterAmount;
205
+ retries += 1;
206
+ logger.warn(`An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`);
207
+ await new Promise((resolve) => setTimeout(resolve, delay));
208
+ }
209
+ }
210
+ throw new Error("Retry failed");
159
211
  }
160
212
 
161
- // src/string.ts
213
+ //#endregion
214
+ //#region src/string.ts
215
+ /**
216
+ * Capitalizes the first letter of a string.
217
+ *
218
+ * @param val - The string to capitalize
219
+ * @returns The input string with its first letter capitalized
220
+ *
221
+ * @example
222
+ * import { capitalizeFirstLetter } from "@settlemint/sdk-utils";
223
+ *
224
+ * const capitalized = capitalizeFirstLetter("hello");
225
+ * // Returns: "Hello"
226
+ */
162
227
  function capitalizeFirstLetter(val) {
163
- return String(val).charAt(0).toUpperCase() + String(val).slice(1);
228
+ return String(val).charAt(0).toUpperCase() + String(val).slice(1);
164
229
  }
230
+ /**
231
+ * Converts a camelCase string to a human-readable string.
232
+ *
233
+ * @param s - The camelCase string to convert
234
+ * @returns The human-readable string
235
+ *
236
+ * @example
237
+ * import { camelCaseToWords } from "@settlemint/sdk-utils";
238
+ *
239
+ * const words = camelCaseToWords("camelCaseString");
240
+ * // Returns: "Camel Case String"
241
+ */
165
242
  function camelCaseToWords(s) {
166
- const result = s.replace(/([a-z])([A-Z])/g, "$1 $2");
167
- const withSpaces = result.replace(/([A-Z])([a-z])/g, " $1$2");
168
- const capitalized = capitalizeFirstLetter(withSpaces);
169
- return capitalized.replace(/\s+/g, " ").trim();
243
+ const result = s.replace(/([a-z])([A-Z])/g, "$1 $2");
244
+ const withSpaces = result.replace(/([A-Z])([a-z])/g, " $1$2");
245
+ const capitalized = capitalizeFirstLetter(withSpaces);
246
+ return capitalized.replace(/\s+/g, " ").trim();
170
247
  }
248
+ /**
249
+ * Replaces underscores and hyphens with spaces.
250
+ *
251
+ * @param s - The string to replace underscores and hyphens with spaces
252
+ * @returns The input string with underscores and hyphens replaced with spaces
253
+ *
254
+ * @example
255
+ * import { replaceUnderscoresAndHyphensWithSpaces } from "@settlemint/sdk-utils";
256
+ *
257
+ * const result = replaceUnderscoresAndHyphensWithSpaces("Already_Spaced-Second");
258
+ * // Returns: "Already Spaced Second"
259
+ */
171
260
  function replaceUnderscoresAndHyphensWithSpaces(s) {
172
- return s.replace(/[-_]/g, " ");
261
+ return s.replace(/[-_]/g, " ");
173
262
  }
263
+ /**
264
+ * Truncates a string to a maximum length and appends "..." if it is longer.
265
+ *
266
+ * @param value - The string to truncate
267
+ * @param maxLength - The maximum length of the string
268
+ * @returns The truncated string or the original string if it is shorter than the maximum length
269
+ *
270
+ * @example
271
+ * import { truncate } from "@settlemint/sdk-utils";
272
+ *
273
+ * const truncated = truncate("Hello, world!", 10);
274
+ * // Returns: "Hello, wor..."
275
+ */
174
276
  function truncate(value, maxLength) {
175
- if (value.length <= maxLength) {
176
- return value;
177
- }
178
- return `${value.slice(0, maxLength)}...`;
277
+ if (value.length <= maxLength) {
278
+ return value;
279
+ }
280
+ return `${value.slice(0, maxLength)}...`;
179
281
  }
180
282
 
181
- // src/url.ts
283
+ //#endregion
284
+ //#region src/url.ts
285
+ /**
286
+ * Extracts the base URL before a specific segment in a URL.
287
+ *
288
+ * @param baseUrl - The base URL to extract the path from
289
+ * @param pathSegment - The path segment to start from
290
+ * @returns The base URL before the specified segment
291
+ * @example
292
+ * ```typescript
293
+ * import { extractBaseUrlBeforeSegment } from "@settlemint/sdk-utils/url";
294
+ *
295
+ * const baseUrl = extractBaseUrlBeforeSegment("https://example.com/api/v1/subgraphs/name/my-subgraph", "/subgraphs");
296
+ * // Returns: "https://example.com/api/v1"
297
+ * ```
298
+ */
182
299
  function extractBaseUrlBeforeSegment(baseUrl, pathSegment) {
183
- const url = new URL(baseUrl);
184
- const segmentIndex = url.pathname.indexOf(pathSegment);
185
- return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);
300
+ const url = new URL(baseUrl);
301
+ const segmentIndex = url.pathname.indexOf(pathSegment);
302
+ return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);
186
303
  }
187
- // Annotate the CommonJS export names for ESM import in node:
188
- 0 && (module.exports = {
189
- camelCaseToWords,
190
- capitalizeFirstLetter,
191
- extractBaseUrlBeforeSegment,
192
- extractJsonObject,
193
- makeJsonStringifiable,
194
- replaceUnderscoresAndHyphensWithSpaces,
195
- retryWhenFailed,
196
- truncate,
197
- tryParseJson
198
- });
304
+
305
+ //#endregion
306
+ exports.camelCaseToWords = camelCaseToWords;
307
+ exports.capitalizeFirstLetter = capitalizeFirstLetter;
308
+ exports.extractBaseUrlBeforeSegment = extractBaseUrlBeforeSegment;
309
+ exports.extractJsonObject = extractJsonObject;
310
+ exports.makeJsonStringifiable = makeJsonStringifiable;
311
+ exports.replaceUnderscoresAndHyphensWithSpaces = replaceUnderscoresAndHyphensWithSpaces;
312
+ exports.retryWhenFailed = retryWhenFailed;
313
+ exports.truncate = truncate;
314
+ exports.tryParseJson = tryParseJson;
199
315
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/json.ts","../src/logging/mask-tokens.ts","../src/logging/logger.ts","../src/retry.ts","../src/string.ts","../src/url.ts"],"sourcesContent":["export * from \"./json.js\";\nexport * from \"./retry.js\";\nexport * from \"./string.js\";\nexport * from \"./url.js\";\n","/**\n * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.\n *\n * @param value - The JSON string to parse\n * @param defaultValue - The value to return if parsing fails or results in null/undefined\n * @returns The parsed JSON value as type T, or the default value if parsing fails\n *\n * @example\n * import { tryParseJson } from \"@settlemint/sdk-utils\";\n *\n * const config = tryParseJson<{ port: number }>(\n * '{\"port\": 3000}',\n * { port: 8080 }\n * );\n * // Returns: { port: 3000 }\n *\n * const invalid = tryParseJson<string[]>(\n * 'invalid json',\n * []\n * );\n * // Returns: []\n */\nexport function tryParseJson<T>(value: string, defaultValue: T | null = null): T | null {\n try {\n const parsed = JSON.parse(value) as T;\n if (parsed === undefined || parsed === null) {\n return defaultValue;\n }\n return parsed;\n } catch (err) {\n // Invalid json\n return defaultValue;\n }\n}\n\n/**\n * Extracts a JSON object from a string.\n *\n * @param value - The string to extract the JSON object from\n * @returns The parsed JSON object, or null if no JSON object is found\n * @throws {Error} If the input string is too long (longer than 5000 characters)\n * @example\n * import { extractJsonObject } from \"@settlemint/sdk-utils\";\n *\n * const json = extractJsonObject<{ port: number }>(\n * 'port info: {\"port\": 3000}',\n * );\n * // Returns: { port: 3000 }\n */\nexport function extractJsonObject<T>(value: string): T | null {\n if (value.length > 5000) {\n throw new Error(\"Input too long\");\n }\n const result = /\\{([\\s\\S]*)\\}/.exec(value);\n if (!result) {\n return null;\n }\n return tryParseJson<T>(result[0]);\n}\n\n/**\n * Converts a value to a JSON stringifiable format.\n *\n * @param value - The value to convert\n * @returns The JSON stringifiable value\n *\n * @example\n * import { makeJsonStringifiable } from \"@settlemint/sdk-utils\";\n *\n * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });\n * // Returns: '{\"amount\":\"1000\"}'\n */\nexport function makeJsonStringifiable<T>(value: unknown): T {\n if (value === undefined || value === null) {\n return value as T;\n }\n return tryParseJson<T>(\n JSON.stringify(\n value,\n (_, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ),\n ) as T;\n}\n","/**\n * Masks sensitive SettleMint tokens in output text by replacing them with asterisks.\n * Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT).\n *\n * @param output - The text string that may contain sensitive tokens\n * @returns The text with any sensitive tokens masked with asterisks\n * @example\n * import { maskTokens } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Masks a token in text\n * const masked = maskTokens(\"Token: sm_pat_****\"); // \"Token: ***\"\n */\nexport const maskTokens = (output: string): string => {\n return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, \"***\");\n};\n","import { maskTokens } from \"./mask-tokens.js\";\n\n/**\n * Log levels supported by the logger\n */\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"none\";\n\n/**\n * Configuration options for the logger\n * @interface LoggerOptions\n */\nexport interface LoggerOptions {\n /** The minimum log level to output */\n level?: LogLevel;\n /** The prefix to add to the log message */\n prefix?: string;\n}\n\n/**\n * Simple logger interface with basic logging methods\n * @interface Logger\n */\nexport interface Logger {\n /** Log debug information */\n debug: (message: string, ...args: unknown[]) => void;\n /** Log general information */\n info: (message: string, ...args: unknown[]) => void;\n /** Log warnings */\n warn: (message: string, ...args: unknown[]) => void;\n /** Log errors */\n error: (message: string, ...args: unknown[]) => void;\n}\n\n/**\n * Creates a simple logger with configurable log level\n *\n * @param options - Configuration options for the logger\n * @param options.level - The minimum log level to output (default: warn)\n * @param options.prefix - The prefix to add to the log message (default: \"\")\n * @returns A logger instance with debug, info, warn, and error methods\n *\n * @example\n * import { createLogger } from \"@/utils/logging/logger\";\n *\n * const logger = createLogger({ level: 'info' });\n *\n * logger.info('User logged in', { userId: '123' });\n * logger.error('Operation failed', new Error('Connection timeout'));\n */\nexport function createLogger(options: LoggerOptions = {}): Logger {\n const { level = \"warn\", prefix = \"\" } = options;\n\n const logLevels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n none: 4,\n };\n\n const currentLevelValue = logLevels[level];\n\n const formatArgs = (args: unknown[]): string => {\n if (args.length === 0 || args.every((arg) => arg === undefined || arg === null)) {\n return \"\";\n }\n\n const formatted = args\n .map((arg) => {\n if (arg instanceof Error) {\n return `\\n${arg.stack || arg.message}`;\n }\n if (typeof arg === \"object\" && arg !== null) {\n return `\\n${JSON.stringify(arg, null, 2)}`;\n }\n return ` ${String(arg)}`;\n })\n .join(\"\");\n\n return `, args:${formatted}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return logLevels[level] >= currentLevelValue;\n };\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"debug\")) {\n console.debug(`\\x1b[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"info\")) {\n console.info(`\\x1b[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"warn\")) {\n console.warn(`\\x1b[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"error\")) {\n console.error(`\\x1b[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n };\n}\n\n/**\n * Default logger instance with standard configuration\n */\nexport const logger = createLogger();\n","import { logger } from \"./logging/logger.js\";\n\n/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let retries = 0;\n const maxAttempts = maxRetries + 1;\n\n while (retries < maxAttempts) {\n try {\n return await fn();\n } catch (e) {\n const error = e as Error;\n if (typeof stopOnError === \"function\") {\n if (stopOnError(error)) {\n throw error;\n }\n }\n if (retries >= maxRetries) {\n throw e;\n }\n // Exponential backoff with jitter to prevent thundering herd\n // Jitter: Random value between 0-10% of initialSleepTime\n const baseDelay = 2 ** retries * initialSleepTime;\n const jitterAmount = initialSleepTime * (Math.random() / 10);\n const delay = baseDelay + jitterAmount;\n retries += 1;\n logger.warn(\n `An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","/**\n * Capitalizes the first letter of a string.\n *\n * @param val - The string to capitalize\n * @returns The input string with its first letter capitalized\n *\n * @example\n * import { capitalizeFirstLetter } from \"@settlemint/sdk-utils\";\n *\n * const capitalized = capitalizeFirstLetter(\"hello\");\n * // Returns: \"Hello\"\n */\nexport function capitalizeFirstLetter(val: string) {\n return String(val).charAt(0).toUpperCase() + String(val).slice(1);\n}\n\n/**\n * Converts a camelCase string to a human-readable string.\n *\n * @param s - The camelCase string to convert\n * @returns The human-readable string\n *\n * @example\n * import { camelCaseToWords } from \"@settlemint/sdk-utils\";\n *\n * const words = camelCaseToWords(\"camelCaseString\");\n * // Returns: \"Camel Case String\"\n */\nexport function camelCaseToWords(s: string) {\n const result = s.replace(/([a-z])([A-Z])/g, \"$1 $2\");\n const withSpaces = result.replace(/([A-Z])([a-z])/g, \" $1$2\");\n const capitalized = capitalizeFirstLetter(withSpaces);\n return capitalized.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Replaces underscores and hyphens with spaces.\n *\n * @param s - The string to replace underscores and hyphens with spaces\n * @returns The input string with underscores and hyphens replaced with spaces\n *\n * @example\n * import { replaceUnderscoresAndHyphensWithSpaces } from \"@settlemint/sdk-utils\";\n *\n * const result = replaceUnderscoresAndHyphensWithSpaces(\"Already_Spaced-Second\");\n * // Returns: \"Already Spaced Second\"\n */\nexport function replaceUnderscoresAndHyphensWithSpaces(s: string) {\n return s.replace(/[-_]/g, \" \");\n}\n\n/**\n * Truncates a string to a maximum length and appends \"...\" if it is longer.\n *\n * @param value - The string to truncate\n * @param maxLength - The maximum length of the string\n * @returns The truncated string or the original string if it is shorter than the maximum length\n *\n * @example\n * import { truncate } from \"@settlemint/sdk-utils\";\n *\n * const truncated = truncate(\"Hello, world!\", 10);\n * // Returns: \"Hello, wor...\"\n */\nexport function truncate(value: string, maxLength: number) {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}...`;\n}\n","/**\n * Extracts the base URL before a specific segment in a URL.\n *\n * @param baseUrl - The base URL to extract the path from\n * @param pathSegment - The path segment to start from\n * @returns The base URL before the specified segment\n * @example\n * ```typescript\n * import { extractBaseUrlBeforeSegment } from \"@settlemint/sdk-utils/url\";\n *\n * const baseUrl = extractBaseUrlBeforeSegment(\"https://example.com/api/v1/subgraphs/name/my-subgraph\", \"/subgraphs\");\n * // Returns: \"https://example.com/api/v1\"\n * ```\n */\nexport function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string) {\n const url = new URL(baseUrl);\n const segmentIndex = url.pathname.indexOf(pathSegment);\n return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBO,SAAS,aAAgB,OAAe,eAAyB,MAAgB;AACtF,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,QAAI,WAAW,UAAa,WAAW,MAAM;AAC3C,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,SAAS,KAAK;AAEZ,WAAO;AAAA,EACT;AACF;AAgBO,SAAS,kBAAqB,OAAyB;AAC5D,MAAI,MAAM,SAAS,KAAM;AACvB,UAAM,IAAI,MAAM,gBAAgB;AAAA,EAClC;AACA,QAAM,SAAS,gBAAgB,KAAK,KAAK;AACzC,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AACA,SAAO,aAAgB,OAAO,CAAC,CAAC;AAClC;AAcO,SAAS,sBAAyB,OAAmB;AAC1D,MAAI,UAAU,UAAa,UAAU,MAAM;AACzC,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL,KAAK;AAAA,MACH;AAAA,MACA,CAAC,GAAGA,WAAW,OAAOA,WAAU,WAAWA,OAAM,SAAS,IAAIA;AAAA;AAAA,IAChE;AAAA,EACF;AACF;;;ACtEO,IAAM,aAAa,CAAC,WAA2B;AACpD,SAAO,OAAO,QAAQ,kCAAkC,KAAK;AAC/D;;;ACmCO,SAAS,aAAa,UAAyB,CAAC,GAAW;AAChE,QAAM,EAAE,QAAQ,QAAQ,SAAS,GAAG,IAAI;AAExC,QAAM,YAAsC;AAAA,IAC1C,OAAO;AAAA,IACP,MAAM;AAAA,IACN,MAAM;AAAA,IACN,OAAO;AAAA,IACP,MAAM;AAAA,EACR;AAEA,QAAM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AAChE,SAAO,EAAE,QAAQ,SAAS,GAAG;AAC/B;AAeO,SAAS,SAAS,OAAe,WAAmB;AACzD,MAAI,MAAM,UAAU,WAAW;AAC7B,WAAO;AAAA,EACT;AACA,SAAO,GAAG,MAAM,MAAM,GAAG,SAAS,CAAC;AACrC;;;ACvDO,SAAS,4BAA4B,SAAiB,aAAqB;AAChF,QAAM,MAAM,IAAI,IAAI,OAAO;AAC3B,QAAM,eAAe,IAAI,SAAS,QAAQ,WAAW;AACrD,SAAO,IAAI,UAAU,gBAAgB,IAAI,IAAI,SAAS,UAAU,GAAG,YAAY,IAAI,IAAI;AACzF;","names":["value","level"]}
1
+ {"version":3,"file":"index.cjs","names":["value: string","defaultValue: T | null","value: unknown","value","output: string","options: LoggerOptions","logLevels: Record<LogLevel, number>","args: unknown[]","level: LogLevel","level","message: string","fn: () => Promise<T>","stopOnError?: (error: Error) => boolean","val: string","s: string","value: string","maxLength: number","baseUrl: string","pathSegment: string"],"sources":["../src/json.ts","../src/logging/mask-tokens.ts","../src/logging/logger.ts","../src/retry.ts","../src/string.ts","../src/url.ts"],"sourcesContent":["/**\n * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.\n *\n * @param value - The JSON string to parse\n * @param defaultValue - The value to return if parsing fails or results in null/undefined\n * @returns The parsed JSON value as type T, or the default value if parsing fails\n *\n * @example\n * import { tryParseJson } from \"@settlemint/sdk-utils\";\n *\n * const config = tryParseJson<{ port: number }>(\n * '{\"port\": 3000}',\n * { port: 8080 }\n * );\n * // Returns: { port: 3000 }\n *\n * const invalid = tryParseJson<string[]>(\n * 'invalid json',\n * []\n * );\n * // Returns: []\n */\nexport function tryParseJson<T>(value: string, defaultValue: T | null = null): T | null {\n try {\n const parsed = JSON.parse(value) as T;\n if (parsed === undefined || parsed === null) {\n return defaultValue;\n }\n return parsed;\n } catch (err) {\n // Invalid json\n return defaultValue;\n }\n}\n\n/**\n * Extracts a JSON object from a string.\n *\n * @param value - The string to extract the JSON object from\n * @returns The parsed JSON object, or null if no JSON object is found\n * @throws {Error} If the input string is too long (longer than 5000 characters)\n * @example\n * import { extractJsonObject } from \"@settlemint/sdk-utils\";\n *\n * const json = extractJsonObject<{ port: number }>(\n * 'port info: {\"port\": 3000}',\n * );\n * // Returns: { port: 3000 }\n */\nexport function extractJsonObject<T>(value: string): T | null {\n if (value.length > 5000) {\n throw new Error(\"Input too long\");\n }\n const result = /\\{([\\s\\S]*)\\}/.exec(value);\n if (!result) {\n return null;\n }\n return tryParseJson<T>(result[0]);\n}\n\n/**\n * Converts a value to a JSON stringifiable format.\n *\n * @param value - The value to convert\n * @returns The JSON stringifiable value\n *\n * @example\n * import { makeJsonStringifiable } from \"@settlemint/sdk-utils\";\n *\n * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });\n * // Returns: '{\"amount\":\"1000\"}'\n */\nexport function makeJsonStringifiable<T>(value: unknown): T {\n if (value === undefined || value === null) {\n return value as T;\n }\n return tryParseJson<T>(\n JSON.stringify(\n value,\n (_, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ),\n ) as T;\n}\n","/**\n * Masks sensitive SettleMint tokens in output text by replacing them with asterisks.\n * Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT).\n *\n * @param output - The text string that may contain sensitive tokens\n * @returns The text with any sensitive tokens masked with asterisks\n * @example\n * import { maskTokens } from \"@settlemint/sdk-utils/terminal\";\n *\n * // Masks a token in text\n * const masked = maskTokens(\"Token: sm_pat_****\"); // \"Token: ***\"\n */\nexport const maskTokens = (output: string): string => {\n return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, \"***\");\n};\n","import { maskTokens } from \"./mask-tokens.js\";\n\n/**\n * Log levels supported by the logger\n */\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\" | \"none\";\n\n/**\n * Configuration options for the logger\n * @interface LoggerOptions\n */\nexport interface LoggerOptions {\n /** The minimum log level to output */\n level?: LogLevel;\n /** The prefix to add to the log message */\n prefix?: string;\n}\n\n/**\n * Simple logger interface with basic logging methods\n * @interface Logger\n */\nexport interface Logger {\n /** Log debug information */\n debug: (message: string, ...args: unknown[]) => void;\n /** Log general information */\n info: (message: string, ...args: unknown[]) => void;\n /** Log warnings */\n warn: (message: string, ...args: unknown[]) => void;\n /** Log errors */\n error: (message: string, ...args: unknown[]) => void;\n}\n\n/**\n * Creates a simple logger with configurable log level\n *\n * @param options - Configuration options for the logger\n * @param options.level - The minimum log level to output (default: warn)\n * @param options.prefix - The prefix to add to the log message (default: \"\")\n * @returns A logger instance with debug, info, warn, and error methods\n *\n * @example\n * import { createLogger } from \"@/utils/logging/logger\";\n *\n * const logger = createLogger({ level: 'info' });\n *\n * logger.info('User logged in', { userId: '123' });\n * logger.error('Operation failed', new Error('Connection timeout'));\n */\nexport function createLogger(options: LoggerOptions = {}): Logger {\n const { level = \"warn\", prefix = \"\" } = options;\n\n const logLevels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n none: 4,\n };\n\n const currentLevelValue = logLevels[level];\n\n const formatArgs = (args: unknown[]): string => {\n if (args.length === 0 || args.every((arg) => arg === undefined || arg === null)) {\n return \"\";\n }\n\n const formatted = args\n .map((arg) => {\n if (arg instanceof Error) {\n return `\\n${arg.stack || arg.message}`;\n }\n if (typeof arg === \"object\" && arg !== null) {\n return `\\n${JSON.stringify(arg, null, 2)}`;\n }\n return ` ${String(arg)}`;\n })\n .join(\"\");\n\n return `, args:${formatted}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return logLevels[level] >= currentLevelValue;\n };\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"debug\")) {\n console.debug(`\\x1b[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"info\")) {\n console.info(`\\x1b[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"warn\")) {\n console.warn(`\\x1b[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (shouldLog(\"error\")) {\n console.error(`\\x1b[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\\x1b[0m`);\n }\n },\n };\n}\n\n/**\n * Default logger instance with standard configuration\n */\nexport const logger = createLogger();\n","import { logger } from \"./logging/logger.js\";\n\n/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let retries = 0;\n const maxAttempts = maxRetries + 1;\n\n while (retries < maxAttempts) {\n try {\n return await fn();\n } catch (e) {\n const error = e as Error;\n if (typeof stopOnError === \"function\") {\n if (stopOnError(error)) {\n throw error;\n }\n }\n if (retries >= maxRetries) {\n throw e;\n }\n // Exponential backoff with jitter to prevent thundering herd\n // Jitter: Random value between 0-10% of initialSleepTime\n const baseDelay = 2 ** retries * initialSleepTime;\n const jitterAmount = initialSleepTime * (Math.random() / 10);\n const delay = baseDelay + jitterAmount;\n retries += 1;\n logger.warn(\n `An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","/**\n * Capitalizes the first letter of a string.\n *\n * @param val - The string to capitalize\n * @returns The input string with its first letter capitalized\n *\n * @example\n * import { capitalizeFirstLetter } from \"@settlemint/sdk-utils\";\n *\n * const capitalized = capitalizeFirstLetter(\"hello\");\n * // Returns: \"Hello\"\n */\nexport function capitalizeFirstLetter(val: string) {\n return String(val).charAt(0).toUpperCase() + String(val).slice(1);\n}\n\n/**\n * Converts a camelCase string to a human-readable string.\n *\n * @param s - The camelCase string to convert\n * @returns The human-readable string\n *\n * @example\n * import { camelCaseToWords } from \"@settlemint/sdk-utils\";\n *\n * const words = camelCaseToWords(\"camelCaseString\");\n * // Returns: \"Camel Case String\"\n */\nexport function camelCaseToWords(s: string) {\n const result = s.replace(/([a-z])([A-Z])/g, \"$1 $2\");\n const withSpaces = result.replace(/([A-Z])([a-z])/g, \" $1$2\");\n const capitalized = capitalizeFirstLetter(withSpaces);\n return capitalized.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Replaces underscores and hyphens with spaces.\n *\n * @param s - The string to replace underscores and hyphens with spaces\n * @returns The input string with underscores and hyphens replaced with spaces\n *\n * @example\n * import { replaceUnderscoresAndHyphensWithSpaces } from \"@settlemint/sdk-utils\";\n *\n * const result = replaceUnderscoresAndHyphensWithSpaces(\"Already_Spaced-Second\");\n * // Returns: \"Already Spaced Second\"\n */\nexport function replaceUnderscoresAndHyphensWithSpaces(s: string) {\n return s.replace(/[-_]/g, \" \");\n}\n\n/**\n * Truncates a string to a maximum length and appends \"...\" if it is longer.\n *\n * @param value - The string to truncate\n * @param maxLength - The maximum length of the string\n * @returns The truncated string or the original string if it is shorter than the maximum length\n *\n * @example\n * import { truncate } from \"@settlemint/sdk-utils\";\n *\n * const truncated = truncate(\"Hello, world!\", 10);\n * // Returns: \"Hello, wor...\"\n */\nexport function truncate(value: string, maxLength: number) {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}...`;\n}\n","/**\n * Extracts the base URL before a specific segment in a URL.\n *\n * @param baseUrl - The base URL to extract the path from\n * @param pathSegment - The path segment to start from\n * @returns The base URL before the specified segment\n * @example\n * ```typescript\n * import { extractBaseUrlBeforeSegment } from \"@settlemint/sdk-utils/url\";\n *\n * const baseUrl = extractBaseUrlBeforeSegment(\"https://example.com/api/v1/subgraphs/name/my-subgraph\", \"/subgraphs\");\n * // Returns: \"https://example.com/api/v1\"\n * ```\n */\nexport function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string) {\n const url = new URL(baseUrl);\n const segmentIndex = url.pathname.indexOf(pathSegment);\n return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,aAAgBA,OAAeC,eAAyB,MAAgB;AACtF,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,MAAM;AAChC,MAAI,WAAW,aAAa,WAAW,MAAM;AAC3C,UAAO;EACR;AACD,SAAO;CACR,SAAQ,KAAK;AAEZ,SAAO;CACR;AACF;;;;;;;;;;;;;;;AAgBD,SAAgB,kBAAqBD,OAAyB;AAC5D,KAAI,MAAM,SAAS,KAAM;AACvB,QAAM,IAAI,MAAM;CACjB;CACD,MAAM,SAAS,gBAAgB,KAAK,MAAM;AAC1C,MAAK,QAAQ;AACX,SAAO;CACR;AACD,QAAO,aAAgB,OAAO,GAAG;AAClC;;;;;;;;;;;;;AAcD,SAAgB,sBAAyBE,OAAmB;AAC1D,KAAI,UAAU,aAAa,UAAU,MAAM;AACzC,SAAO;CACR;AACD,QAAO,aACL,KAAK,UACH,OACA,CAAC,GAAGC,mBAAkBA,YAAU,WAAW,QAAM,UAAU,GAAGA,QAC/D,CACF;AACF;;;;;;;;;;;;;;;;ACtED,MAAa,aAAa,CAACC,WAA2B;AACpD,QAAO,OAAO,QAAQ,kCAAkC,MAAM;AAC/D;;;;;;;;;;;;;;;;;;;;ACmCD,SAAgB,aAAaC,UAAyB,CAAE,GAAU;CAChE,MAAM,EAAE,QAAQ,QA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AuCA,GAAW;AAChE,QAAO,EAAE,QAAQ,SAAS,IAAI;AAC/B;;;;;;;;;;;;;;AAeD,SAAgB,SAASC,OAAeC,WAAmB;AACzD,KAAI,MAAM,UAAU,WAAW;AAC7B,SAAO;CACR;AACD,SAAQ,EAAE,MAAM,MAAM,GAAG,UAAU,CAAC;AACrC;;;;;;;;;;;;;;;;;;ACvDD,SAAgB,4BAA4BC,SAAiBC,aAAqB;CAChF,MAAM,MAAM,IAAI,IAAI;CACpB,MAAM,eAAe,IAAI,SAAS,QAAQ,YAAY;AACtD,QAAO,IAAI,UAAU,gBAAgB,IAAI,IAAI,SAAS,UAAU,GAAG,aAAa,GAAG,IAAI;AACxF"}
package/dist/index.d.cts CHANGED
@@ -1,3 +1,4 @@
1
+ //#region src/json.d.ts
1
2
  /**
2
3
  * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.
3
4
  *
@@ -50,6 +51,8 @@ declare function extractJsonObject<T>(value: string): T | null;
50
51
  */
51
52
  declare function makeJsonStringifiable<T>(value: unknown): T;
52
53
 
54
+ //#endregion
55
+ //#region src/retry.d.ts
53
56
  /**
54
57
  * Retry a function when it fails.
55
58
  * @param fn - The function to retry.
@@ -65,6 +68,8 @@ declare function makeJsonStringifiable<T>(value: unknown): T;
65
68
  */
66
69
  declare function retryWhenFailed<T>(fn: () => Promise<T>, maxRetries?: number, initialSleepTime?: number, stopOnError?: (error: Error) => boolean): Promise<T>;
67
70
 
71
+ //#endregion
72
+ //#region src/string.d.ts
68
73
  /**
69
74
  * Capitalizes the first letter of a string.
70
75
  *
@@ -119,6 +124,8 @@ declare function replaceUnderscoresAndHyphensWithSpaces(s: string): string;
119
124
  */
120
125
  declare function truncate(value: string, maxLength: number): string;
121
126
 
127
+ //#endregion
128
+ //#region src/url.d.ts
122
129
  /**
123
130
  * Extracts the base URL before a specific segment in a URL.
124
131
  *
@@ -135,4 +142,6 @@ declare function truncate(value: string, maxLength: number): string;
135
142
  */
136
143
  declare function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string): string;
137
144
 
145
+ //#endregion
138
146
  export { camelCaseToWords, capitalizeFirstLetter, extractBaseUrlBeforeSegment, extractJsonObject, makeJsonStringifiable, replaceUnderscoresAndHyphensWithSpaces, retryWhenFailed, truncate, tryParseJson };
147
+ //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ //#region src/json.d.ts
1
2
  /**
2
3
  * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.
3
4
  *
@@ -50,6 +51,8 @@ declare function extractJsonObject<T>(value: string): T | null;
50
51
  */
51
52
  declare function makeJsonStringifiable<T>(value: unknown): T;
52
53
 
54
+ //#endregion
55
+ //#region src/retry.d.ts
53
56
  /**
54
57
  * Retry a function when it fails.
55
58
  * @param fn - The function to retry.
@@ -65,6 +68,8 @@ declare function makeJsonStringifiable<T>(value: unknown): T;
65
68
  */
66
69
  declare function retryWhenFailed<T>(fn: () => Promise<T>, maxRetries?: number, initialSleepTime?: number, stopOnError?: (error: Error) => boolean): Promise<T>;
67
70
 
71
+ //#endregion
72
+ //#region src/string.d.ts
68
73
  /**
69
74
  * Capitalizes the first letter of a string.
70
75
  *
@@ -119,6 +124,8 @@ declare function replaceUnderscoresAndHyphensWithSpaces(s: string): string;
119
124
  */
120
125
  declare function truncate(value: string, maxLength: number): string;
121
126
 
127
+ //#endregion
128
+ //#region src/url.d.ts
122
129
  /**
123
130
  * Extracts the base URL before a specific segment in a URL.
124
131
  *
@@ -135,4 +142,6 @@ declare function truncate(value: string, maxLength: number): string;
135
142
  */
136
143
  declare function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string): string;
137
144
 
145
+ //#endregion
138
146
  export { camelCaseToWords, capitalizeFirstLetter, extractBaseUrlBeforeSegment, extractJsonObject, makeJsonStringifiable, replaceUnderscoresAndHyphensWithSpaces, retryWhenFailed, truncate, tryParseJson };
147
+ //# sourceMappingURL=index.d.ts.map