@settlemint/sdk-utils 2.3.2-pre186542e → 2.3.2-prede7bc05
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/README.md +51 -7
- package/dist/environment.cjs +17708 -384
- package/dist/environment.cjs.map +1 -1
- package/dist/environment.d.cts +263 -98
- package/dist/environment.d.ts +263 -98
- package/dist/environment.js +17746 -0
- package/dist/environment.js.map +1 -0
- package/dist/filesystem.cjs +6746 -113
- package/dist/filesystem.cjs.map +1 -1
- package/dist/filesystem.d.cts +22 -1
- package/dist/filesystem.d.ts +22 -1
- package/dist/filesystem.js +6766 -0
- package/dist/filesystem.js.map +1 -0
- package/dist/http.cjs +214 -94
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +9 -1
- package/dist/http.d.ts +9 -1
- package/dist/http.js +226 -0
- package/dist/http.js.map +1 -0
- package/dist/index.cjs +295 -104
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -1
- package/dist/index.d.ts +26 -1
- package/dist/index.js +306 -0
- package/dist/index.js.map +1 -0
- package/dist/json.cjs +83 -0
- package/dist/json.cjs.map +1 -0
- package/dist/json.d.cts +56 -0
- package/dist/json.d.ts +56 -0
- package/dist/json.js +80 -0
- package/dist/json.js.map +1 -0
- package/dist/logging.cjs +209 -137
- package/dist/logging.cjs.map +1 -1
- package/dist/logging.d.cts +23 -14
- package/dist/logging.d.ts +23 -14
- package/dist/logging.js +221 -0
- package/dist/logging.js.map +1 -0
- package/dist/package-manager.cjs +7353 -173
- package/dist/package-manager.cjs.map +1 -1
- package/dist/package-manager.d.cts +26 -3
- package/dist/package-manager.d.ts +26 -3
- package/dist/package-manager.js +7385 -0
- package/dist/package-manager.js.map +1 -0
- package/dist/retry.cjs +137 -0
- package/dist/retry.cjs.map +1 -0
- package/dist/retry.d.cts +19 -0
- package/dist/retry.d.ts +19 -0
- package/dist/retry.js +136 -0
- package/dist/retry.js.map +1 -0
- package/dist/runtime.cjs +58 -40
- package/dist/runtime.cjs.map +1 -1
- package/dist/runtime.d.cts +3 -0
- package/dist/runtime.d.ts +3 -0
- package/dist/runtime.js +45 -0
- package/dist/runtime.js.map +1 -0
- package/dist/string.cjs +76 -0
- package/dist/string.cjs.map +1 -0
- package/dist/string.d.cts +58 -0
- package/dist/string.d.ts +58 -0
- package/dist/string.js +72 -0
- package/dist/string.js.map +1 -0
- package/dist/terminal.cjs +426 -229
- package/dist/terminal.cjs.map +1 -1
- package/dist/terminal.d.cts +54 -24
- package/dist/terminal.d.ts +54 -24
- package/dist/terminal.js +441 -0
- package/dist/terminal.js.map +1 -0
- package/dist/url.cjs +25 -0
- package/dist/url.cjs.map +1 -0
- package/dist/url.d.cts +20 -0
- package/dist/url.d.ts +20 -0
- package/dist/url.js +24 -0
- package/dist/url.js.map +1 -0
- package/dist/validation.cjs +10486 -193
- package/dist/validation.cjs.map +1 -1
- package/dist/validation.d.cts +124 -94
- package/dist/validation.d.ts +124 -94
- package/dist/validation.js +10482 -0
- package/dist/validation.js.map +1 -0
- package/package.json +6 -6
- package/dist/environment.mjs +0 -384
- package/dist/environment.mjs.map +0 -1
- package/dist/filesystem.mjs +0 -105
- package/dist/filesystem.mjs.map +0 -1
- package/dist/http.mjs +0 -80
- package/dist/http.mjs.map +0 -1
- package/dist/index.mjs +0 -90
- package/dist/index.mjs.map +0 -1
- package/dist/logging.mjs +0 -123
- package/dist/logging.mjs.map +0 -1
- package/dist/package-manager.mjs +0 -167
- package/dist/package-manager.mjs.map +0 -1
- package/dist/runtime.mjs +0 -23
- package/dist/runtime.mjs.map +0 -1
- package/dist/terminal.mjs +0 -230
- package/dist/terminal.mjs.map +0 -1
- package/dist/validation.mjs +0 -161
- package/dist/validation.mjs.map +0 -1
package/dist/http.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.js","names":["output: string","options: LoggerOptions","logLevels: Record<LogLevel, number>","args: unknown[]","level: LogLevel","level","message: string","fn: () => Promise<T>","stopOnError?: (error: Error) => boolean","input: RequestInfo | URL","init?: RequestInit","input: RequestInfo | URL","init?: RequestInit","json: { errors?: { message: string }[]; data: Data }","headers: MaybeLazy<HeadersInit> | undefined","additionalHeaders: Record<string, string | undefined>"],"sources":["../src/logging/mask-tokens.ts","../src/logging/logger.ts","../src/retry.ts","../src/http/fetch-with-retry.ts","../src/http/graphql-fetch-with-retry.ts","../src/http/headers.ts"],"sourcesContent":["/**\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","import { retryWhenFailed } from \"../retry.js\";\n\n/**\n * Retry an HTTP request with exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n *\n * @param input - The URL or Request object to fetch\n * @param init - The fetch init options\n * @param maxRetries - Maximum number of retry attempts\n * @param initialSleepTime - Initial sleep time between retries in ms\n * @returns The fetch Response\n * @throws Error if all retries fail\n * @example\n * import { fetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const response = await fetchWithRetry(\"https://api.example.com/data\");\n */\nexport async function fetchWithRetry(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Response> {\n return retryWhenFailed(\n async () => {\n const response = await fetch(input, init);\n if (response.ok) {\n return response;\n }\n // Only retry on 5xx server errors, 429 rate limit, timeout, and network errors\n if (response.status < 500 && response.status !== 429 && response.status !== 408 && response.status !== 0) {\n return response;\n }\n throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);\n },\n maxRetries,\n initialSleepTime,\n );\n}\n","import { retryWhenFailed } from \"../retry.js\";\nimport { fetchWithRetry } from \"./fetch-with-retry.js\";\n\n/**\n * Executes a GraphQL request with automatic retries using exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n * Will also retry if the GraphQL response contains errors.\n *\n * @param input - The URL or Request object for the GraphQL endpoint\n * @param init - Optional fetch configuration options\n * @param maxRetries - Maximum retry attempts before failing (default: 5)\n * @param initialSleepTime - Initial delay between retries in milliseconds (default: 3000)\n * @returns The parsed GraphQL response data\n * @throws Error if all retries fail or if GraphQL response contains errors\n * @example\n * import { graphqlFetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const data = await graphqlFetchWithRetry<{ user: { id: string } }>(\n * \"https://api.example.com/graphql\",\n * {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({\n * query: `query GetUser($id: ID!) {\n * user(id: $id) {\n * id\n * }\n * }`,\n * variables: { id: \"123\" }\n * })\n * }\n * );\n */\nexport async function graphqlFetchWithRetry<Data>(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Data> {\n return retryWhenFailed<Data>(\n async () => {\n const response = await fetchWithRetry(input, init);\n const json: { errors?: { message: string }[]; data: Data } = await response.json();\n if (json.errors) {\n throw new Error(`GraphQL errors in response: ${json.errors.map((error) => error.message).join(\", \")}`);\n }\n return json.data;\n },\n maxRetries,\n initialSleepTime,\n );\n}\n","type MaybeLazy<T> = T | (() => T);\n\nexport function appendHeaders(\n headers: MaybeLazy<HeadersInit> | undefined,\n additionalHeaders: Record<string, string | undefined>,\n) {\n const defaultHeaders = typeof headers === \"function\" ? headers() : headers;\n const filteredAdditionalHeaders = Object.entries(additionalHeaders).filter(([_, value]) => value !== undefined) as [\n string,\n string,\n ][];\n if (Array.isArray(defaultHeaders)) {\n return [...defaultHeaders, ...filteredAdditionalHeaders];\n }\n if (defaultHeaders instanceof Headers) {\n return new Headers([...defaultHeaders, ...filteredAdditionalHeaders]);\n }\n return {\n ...defaultHeaders,\n ...Object.fromEntries(filteredAdditionalHeaders),\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,aAAa,CAACA,WAA2B;AACpD,QAAO,OAAO,QAAQ,kCAAkC,MAAM;AAC/D;;;;;;;;;;;;;;;;;;;;ACmCD,SAAgB,aAAaC,UAAyB,CAAE,GAAU;CAChE,MAAM,EAAE,QAAQ,QAAQ,SAAS,IAAI,GAAG;CAExC,MAAMC,YAAsC;EAC1C,OAAO;EACP,MAAM;EACN,MAAM;EACN,OAAO;EACP,MAAM;CACP;CAED,MAAM,oBAAoB,UAAU;CAEpC,MAAM,aAAa,CAACC,SAA4B;AAC9C,MAAI,KAAK,WAAW,KAAK,KAAK,MAAM,CAAC,QAAQ,QAAQ,aAAa,QAAQ,KAAK,EAAE;AAC/E,UAAO;EACR;EAED,MAAM,YAAY,KACf,IAAI,CAAC,QAAQ;AACZ,OAAI,eAAe,OAAO;AACxB,YAAQ,IAAI,IAAI,SAAS,IAAI,QAAQ;GACtC;AACD,cAAW,QAAQ,YAAY,QAAQ,MAAM;AAC3C,YAAQ,IAAI,KAAK,UAAU,KAAK,MAAM,EAAE,CAAC;GAC1C;AACD,WAAQ,GAAG,OAAO,IAAI,CAAC;EACxB,EAAC,CACD,KAAK,GAAG;AAEX,UAAQ,SAAS,UAAU;CAC5B;CAED,MAAM,YAAY,CAACC,YAA6B;AAC9C,SAAO,UAAUC,YAAU;CAC5B;AAED,QAAO;EACL,OAAO,CAACC,SAAiB,GAAG,SAAoB;AAC9C,OAAI,UAAU,QAAQ,EAAE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,OAAO,YAAY,0BAA0B;CACjD;AACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,124 +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
|
-
|
|
20
|
-
// src/index.ts
|
|
21
|
-
var index_exports = {};
|
|
22
|
-
__export(index_exports, {
|
|
23
|
-
camelCaseToWords: () => camelCaseToWords,
|
|
24
|
-
capitalizeFirstLetter: () => capitalizeFirstLetter,
|
|
25
|
-
extractJsonObject: () => extractJsonObject,
|
|
26
|
-
makeJsonStringifiable: () => makeJsonStringifiable,
|
|
27
|
-
replaceUnderscoresAndHyphensWithSpaces: () => replaceUnderscoresAndHyphensWithSpaces,
|
|
28
|
-
retryWhenFailed: () => retryWhenFailed,
|
|
29
|
-
truncate: () => truncate,
|
|
30
|
-
tryParseJson: () => tryParseJson
|
|
31
|
-
});
|
|
32
|
-
module.exports = __toCommonJS(index_exports);
|
|
33
1
|
|
|
34
|
-
|
|
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
|
+
*/
|
|
35
25
|
function tryParseJson(value, defaultValue = null) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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
|
+
}
|
|
45
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
|
+
*/
|
|
46
50
|
function extractJsonObject(value) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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]);
|
|
55
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
|
+
*/
|
|
56
72
|
function makeJsonStringifiable(value) {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
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));
|
|
77
|
+
}
|
|
78
|
+
|
|
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, "***");
|
|
95
|
+
};
|
|
96
|
+
|
|
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
|
+
*/
|
|
115
|
+
function createLogger(options = {}) {
|
|
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
|
+
};
|
|
67
165
|
}
|
|
166
|
+
/**
|
|
167
|
+
* Default logger instance with standard configuration
|
|
168
|
+
*/
|
|
169
|
+
const logger = createLogger();
|
|
68
170
|
|
|
69
|
-
|
|
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
|
+
*/
|
|
70
186
|
async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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");
|
|
92
211
|
}
|
|
93
212
|
|
|
94
|
-
|
|
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
|
+
*/
|
|
95
227
|
function capitalizeFirstLetter(val) {
|
|
96
|
-
|
|
228
|
+
return String(val).charAt(0).toUpperCase() + String(val).slice(1);
|
|
97
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
|
+
*/
|
|
98
242
|
function camelCaseToWords(s) {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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();
|
|
103
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
|
+
*/
|
|
104
260
|
function replaceUnderscoresAndHyphensWithSpaces(s) {
|
|
105
|
-
|
|
261
|
+
return s.replace(/[-_]/g, " ");
|
|
106
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
|
+
*/
|
|
107
276
|
function truncate(value, maxLength) {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
277
|
+
if (value.length <= maxLength) {
|
|
278
|
+
return value;
|
|
279
|
+
}
|
|
280
|
+
return `${value.slice(0, maxLength)}...`;
|
|
112
281
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
282
|
+
|
|
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
|
+
*/
|
|
299
|
+
function extractBaseUrlBeforeSegment(baseUrl, pathSegment) {
|
|
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);
|
|
303
|
+
}
|
|
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;
|
|
124
315
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/json.ts","../src/retry.ts","../src/string.ts"],"sourcesContent":["export * from \"./json.js\";\nexport * from \"./retry.js\";\nexport * from \"./string.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 * 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 attempt = 0;\n\n while (attempt < maxRetries) {\n try {\n return await fn();\n } catch (e) {\n if (typeof stopOnError === \"function\") {\n const error = e as Error;\n if (stopOnError(error)) {\n throw error;\n }\n }\n attempt += 1;\n if (attempt >= maxRetries) {\n throw e;\n }\n // Exponential backoff with full jitter to prevent thundering herd\n const jitter = Math.random();\n const delay = 2 ** attempt * initialSleepTime * jitter; // 0-1x of 1s, 2s, 4s base\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"],"mappings":";;;;;;;;;;;;;;;;;;;;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,C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","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,OA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ED
|
@@ -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,4 +124,24 @@ declare function replaceUnderscoresAndHyphensWithSpaces(s: string): string;
|
|
|
119
124
|
*/
|
|
120
125
|
declare function truncate(value: string, maxLength: number): string;
|
|
121
126
|
|
|
122
|
-
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/url.d.ts
|
|
129
|
+
/**
|
|
130
|
+
* Extracts the base URL before a specific segment in a URL.
|
|
131
|
+
*
|
|
132
|
+
* @param baseUrl - The base URL to extract the path from
|
|
133
|
+
* @param pathSegment - The path segment to start from
|
|
134
|
+
* @returns The base URL before the specified segment
|
|
135
|
+
* @example
|
|
136
|
+
* ```typescript
|
|
137
|
+
* import { extractBaseUrlBeforeSegment } from "@settlemint/sdk-utils/url";
|
|
138
|
+
*
|
|
139
|
+
* const baseUrl = extractBaseUrlBeforeSegment("https://example.com/api/v1/subgraphs/name/my-subgraph", "/subgraphs");
|
|
140
|
+
* // Returns: "https://example.com/api/v1"
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
declare function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string): string;
|
|
144
|
+
|
|
145
|
+
//#endregion
|
|
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,4 +124,24 @@ declare function replaceUnderscoresAndHyphensWithSpaces(s: string): string;
|
|
|
119
124
|
*/
|
|
120
125
|
declare function truncate(value: string, maxLength: number): string;
|
|
121
126
|
|
|
122
|
-
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/url.d.ts
|
|
129
|
+
/**
|
|
130
|
+
* Extracts the base URL before a specific segment in a URL.
|
|
131
|
+
*
|
|
132
|
+
* @param baseUrl - The base URL to extract the path from
|
|
133
|
+
* @param pathSegment - The path segment to start from
|
|
134
|
+
* @returns The base URL before the specified segment
|
|
135
|
+
* @example
|
|
136
|
+
* ```typescript
|
|
137
|
+
* import { extractBaseUrlBeforeSegment } from "@settlemint/sdk-utils/url";
|
|
138
|
+
*
|
|
139
|
+
* const baseUrl = extractBaseUrlBeforeSegment("https://example.com/api/v1/subgraphs/name/my-subgraph", "/subgraphs");
|
|
140
|
+
* // Returns: "https://example.com/api/v1"
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
declare function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string): string;
|
|
144
|
+
|
|
145
|
+
//#endregion
|
|
146
|
+
export { camelCaseToWords, capitalizeFirstLetter, extractBaseUrlBeforeSegment, extractJsonObject, makeJsonStringifiable, replaceUnderscoresAndHyphensWithSpaces, retryWhenFailed, truncate, tryParseJson };
|
|
147
|
+
//# sourceMappingURL=index.d.ts.map
|