@settlemint/sdk-utils 2.3.2-pr708c218f → 2.3.2-pr74f654b5

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 (89) hide show
  1. package/README.md +51 -7
  2. package/dist/environment.cjs +25 -409
  3. package/dist/environment.d.cts +3 -176
  4. package/dist/environment.d.ts +3 -176
  5. package/dist/environment.js +4 -0
  6. package/dist/filesystem.cjs +39 -123
  7. package/dist/filesystem.d.cts +4 -59
  8. package/dist/filesystem.d.ts +4 -59
  9. package/dist/filesystem.js +5 -0
  10. package/dist/http.cjs +34 -98
  11. package/dist/http.d.cts +4 -55
  12. package/dist/http.d.ts +4 -55
  13. package/dist/http.js +5 -0
  14. package/dist/index.cjs +27 -118
  15. package/dist/index.d.cts +4 -122
  16. package/dist/index.d.ts +4 -122
  17. package/dist/index.js +7 -0
  18. package/dist/json.cjs +83 -0
  19. package/dist/json.cjs.map +1 -0
  20. package/dist/json.d.cts +56 -0
  21. package/dist/json.d.ts +56 -0
  22. package/dist/json.js +80 -0
  23. package/dist/json.js.map +1 -0
  24. package/dist/logging.cjs +34 -141
  25. package/dist/logging.d.cts +4 -70
  26. package/dist/logging.d.ts +4 -70
  27. package/dist/logging.js +5 -0
  28. package/dist/package-manager.cjs +51 -196
  29. package/dist/package-manager.d.cts +7 -114
  30. package/dist/package-manager.d.ts +7 -114
  31. package/dist/package-manager.js +9 -0
  32. package/dist/retry.cjs +69 -0
  33. package/dist/retry.cjs.map +1 -0
  34. package/dist/retry.d.cts +19 -0
  35. package/dist/retry.d.ts +19 -0
  36. package/dist/retry.js +46 -0
  37. package/dist/retry.js.map +1 -0
  38. package/dist/runtime.cjs +38 -42
  39. package/dist/runtime.d.cts +2 -32
  40. package/dist/runtime.d.ts +2 -32
  41. package/dist/runtime.js +3 -0
  42. package/dist/string.cjs +76 -0
  43. package/dist/string.cjs.map +1 -0
  44. package/dist/string.d.cts +58 -0
  45. package/dist/string.d.ts +58 -0
  46. package/dist/string.js +72 -0
  47. package/dist/string.js.map +1 -0
  48. package/dist/terminal.cjs +91 -258
  49. package/dist/terminal.d.cts +11 -219
  50. package/dist/terminal.d.ts +11 -219
  51. package/dist/terminal.js +12 -0
  52. package/dist/url.cjs +25 -0
  53. package/dist/url.cjs.map +1 -0
  54. package/dist/url.d.cts +20 -0
  55. package/dist/url.d.ts +20 -0
  56. package/dist/url.js +24 -0
  57. package/dist/url.js.map +1 -0
  58. package/dist/validation.cjs +89 -186
  59. package/dist/validation.d.cts +7 -243
  60. package/dist/validation.d.ts +7 -243
  61. package/dist/validation.js +8 -0
  62. package/package.json +6 -6
  63. package/dist/environment.cjs.map +0 -1
  64. package/dist/environment.mjs +0 -384
  65. package/dist/environment.mjs.map +0 -1
  66. package/dist/filesystem.cjs.map +0 -1
  67. package/dist/filesystem.mjs +0 -105
  68. package/dist/filesystem.mjs.map +0 -1
  69. package/dist/http.cjs.map +0 -1
  70. package/dist/http.mjs +0 -80
  71. package/dist/http.mjs.map +0 -1
  72. package/dist/index.cjs.map +0 -1
  73. package/dist/index.mjs +0 -90
  74. package/dist/index.mjs.map +0 -1
  75. package/dist/logging.cjs.map +0 -1
  76. package/dist/logging.mjs +0 -123
  77. package/dist/logging.mjs.map +0 -1
  78. package/dist/package-manager.cjs.map +0 -1
  79. package/dist/package-manager.mjs +0 -167
  80. package/dist/package-manager.mjs.map +0 -1
  81. package/dist/runtime.cjs.map +0 -1
  82. package/dist/runtime.mjs +0 -23
  83. package/dist/runtime.mjs.map +0 -1
  84. package/dist/terminal.cjs.map +0 -1
  85. package/dist/terminal.mjs +0 -230
  86. package/dist/terminal.mjs.map +0 -1
  87. package/dist/validation.cjs.map +0 -1
  88. package/dist/validation.mjs +0 -161
  89. package/dist/validation.mjs.map +0 -1
@@ -1,105 +0,0 @@
1
- // src/filesystem/project-root.ts
2
- import { dirname } from "path";
3
- import { findUp } from "find-up";
4
- async function projectRoot(fallbackToCwd = false, cwd) {
5
- const packageJsonPath = await findUp("package.json", { cwd });
6
- if (!packageJsonPath) {
7
- if (fallbackToCwd) {
8
- return process.cwd();
9
- }
10
- throw new Error("Unable to find project root (no package.json found)");
11
- }
12
- return dirname(packageJsonPath);
13
- }
14
-
15
- // src/filesystem/exists.ts
16
- import { stat } from "fs/promises";
17
- async function exists(path) {
18
- try {
19
- await stat(path);
20
- return true;
21
- } catch {
22
- return false;
23
- }
24
- }
25
-
26
- // src/filesystem/mono-repo.ts
27
- import { readFile } from "fs/promises";
28
- import { dirname as dirname2, join } from "path";
29
-
30
- // src/json.ts
31
- function tryParseJson(value, defaultValue = null) {
32
- try {
33
- const parsed = JSON.parse(value);
34
- if (parsed === void 0 || parsed === null) {
35
- return defaultValue;
36
- }
37
- return parsed;
38
- } catch (err) {
39
- return defaultValue;
40
- }
41
- }
42
-
43
- // src/filesystem/mono-repo.ts
44
- import { findUp as findUp2 } from "find-up";
45
- import { glob } from "glob";
46
- async function findMonoRepoRoot(startDir) {
47
- const lockFilePath = await findUp2(["package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lockb", "bun.lock"], {
48
- cwd: startDir
49
- });
50
- if (lockFilePath) {
51
- const packageJsonPath = join(dirname2(lockFilePath), "package.json");
52
- const hasWorkSpaces = await packageJsonHasWorkspaces(packageJsonPath);
53
- return hasWorkSpaces ? dirname2(lockFilePath) : null;
54
- }
55
- let currentDir = startDir;
56
- while (currentDir !== "/") {
57
- const packageJsonPath = join(currentDir, "package.json");
58
- if (await packageJsonHasWorkspaces(packageJsonPath)) {
59
- return currentDir;
60
- }
61
- const parentDir = dirname2(currentDir);
62
- if (parentDir === currentDir) {
63
- break;
64
- }
65
- currentDir = parentDir;
66
- }
67
- return null;
68
- }
69
- async function findMonoRepoPackages(projectDir) {
70
- try {
71
- const monoRepoRoot = await findMonoRepoRoot(projectDir);
72
- if (!monoRepoRoot) {
73
- return [projectDir];
74
- }
75
- const packageJsonPath = join(monoRepoRoot, "package.json");
76
- const packageJson = tryParseJson(await readFile(packageJsonPath, "utf-8"));
77
- const workspaces = packageJson?.workspaces ?? [];
78
- const packagePaths = await Promise.all(
79
- workspaces.map(async (workspace) => {
80
- const matches = await glob(join(monoRepoRoot, workspace, "package.json"));
81
- return matches.map((match) => join(match, ".."));
82
- })
83
- );
84
- const allPaths = packagePaths.flat();
85
- return allPaths.length === 0 ? [projectDir] : [monoRepoRoot, ...allPaths];
86
- } catch (error) {
87
- return [projectDir];
88
- }
89
- }
90
- async function packageJsonHasWorkspaces(packageJsonPath) {
91
- if (await exists(packageJsonPath)) {
92
- const packageJson = tryParseJson(await readFile(packageJsonPath, "utf-8"));
93
- if (packageJson?.workspaces && Array.isArray(packageJson?.workspaces) && packageJson?.workspaces.length > 0) {
94
- return true;
95
- }
96
- }
97
- return false;
98
- }
99
- export {
100
- exists,
101
- findMonoRepoPackages,
102
- findMonoRepoRoot,
103
- projectRoot
104
- };
105
- //# sourceMappingURL=filesystem.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/filesystem/project-root.ts","../src/filesystem/exists.ts","../src/filesystem/mono-repo.ts","../src/json.ts"],"sourcesContent":["import { dirname } from \"node:path\";\nimport { findUp } from \"find-up\";\n\n/**\n * Finds the root directory of the current project by locating the nearest package.json file\n *\n * @param fallbackToCwd - If true, will return the current working directory if no package.json is found\n * @param cwd - The directory to start searching for the package.json file from (defaults to process.cwd())\n * @returns Promise that resolves to the absolute path of the project root directory\n * @throws Will throw an error if no package.json is found in the directory tree\n * @example\n * import { projectRoot } from \"@settlemint/sdk-utils/filesystem\";\n *\n * // Get project root path\n * const rootDir = await projectRoot();\n * console.log(`Project root is at: ${rootDir}`);\n */\nexport async function projectRoot(fallbackToCwd = false, cwd?: string): Promise<string> {\n const packageJsonPath = await findUp(\"package.json\", { cwd });\n if (!packageJsonPath) {\n if (fallbackToCwd) {\n return process.cwd();\n }\n throw new Error(\"Unable to find project root (no package.json found)\");\n }\n return dirname(packageJsonPath);\n}\n","import type { PathLike } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\n\n/**\n * Checks if a file or directory exists at the given path\n *\n * @param path - The file system path to check for existence\n * @returns Promise that resolves to true if the path exists, false otherwise\n * @example\n * import { exists } from \"@settlemint/sdk-utils/filesystem\";\n *\n * // Check if file exists before reading\n * if (await exists('/path/to/file.txt')) {\n * // File exists, safe to read\n * }\n */\nexport async function exists(path: PathLike): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { exists } from \"@/filesystem.js\";\nimport { tryParseJson } from \"@/json.js\";\nimport { findUp } from \"find-up\";\nimport { glob } from \"glob\";\n\n/**\n * Finds the root directory of a monorepo\n *\n * @param startDir - The directory to start searching from\n * @returns The root directory of the monorepo or null if not found\n * @example\n * import { findMonoRepoRoot } from \"@settlemint/sdk-utils/filesystem\";\n *\n * const root = await findMonoRepoRoot(\"/path/to/your/project\");\n * console.log(root); // Output: /path/to/your/project/packages/core\n */\nexport async function findMonoRepoRoot(startDir: string): Promise<string | null> {\n const lockFilePath = await findUp([\"package-lock.json\", \"yarn.lock\", \"pnpm-lock.yaml\", \"bun.lockb\", \"bun.lock\"], {\n cwd: startDir,\n });\n if (lockFilePath) {\n const packageJsonPath = join(dirname(lockFilePath), \"package.json\");\n const hasWorkSpaces = await packageJsonHasWorkspaces(packageJsonPath);\n return hasWorkSpaces ? dirname(lockFilePath) : null;\n }\n\n let currentDir = startDir;\n\n while (currentDir !== \"/\") {\n const packageJsonPath = join(currentDir, \"package.json\");\n\n if (await packageJsonHasWorkspaces(packageJsonPath)) {\n return currentDir;\n }\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n break; // We've reached the root\n }\n currentDir = parentDir;\n }\n\n return null;\n}\n\n/**\n * Finds all packages in a monorepo\n *\n * @param projectDir - The directory to start searching from\n * @returns An array of package directories\n * @example\n * import { findMonoRepoPackages } from \"@settlemint/sdk-utils/filesystem\";\n *\n * const packages = await findMonoRepoPackages(\"/path/to/your/project\");\n * console.log(packages); // Output: [\"/path/to/your/project/packages/core\", \"/path/to/your/project/packages/ui\"]\n */\nexport async function findMonoRepoPackages(projectDir: string): Promise<string[]> {\n try {\n const monoRepoRoot = await findMonoRepoRoot(projectDir);\n if (!monoRepoRoot) {\n return [projectDir];\n }\n\n const packageJsonPath = join(monoRepoRoot, \"package.json\");\n const packageJson = tryParseJson<{ workspaces: string[] }>(await readFile(packageJsonPath, \"utf-8\"));\n const workspaces = packageJson?.workspaces ?? [];\n\n const packagePaths = await Promise.all(\n workspaces.map(async (workspace: string) => {\n const matches = await glob(join(monoRepoRoot, workspace, \"package.json\"));\n return matches.map((match) => join(match, \"..\"));\n }),\n );\n\n const allPaths = packagePaths.flat();\n // If no packages found in workspaces, treat as non-monorepo\n return allPaths.length === 0 ? [projectDir] : [monoRepoRoot, ...allPaths];\n } catch (error) {\n // If any error occurs, treat as non-monorepo\n return [projectDir];\n }\n}\n\nasync function packageJsonHasWorkspaces(packageJsonPath: string): Promise<boolean> {\n if (await exists(packageJsonPath)) {\n const packageJson = tryParseJson<{ workspaces: string[] }>(await readFile(packageJsonPath, \"utf-8\"));\n if (packageJson?.workspaces && Array.isArray(packageJson?.workspaces) && packageJson?.workspaces.length > 0) {\n return true;\n }\n }\n return false;\n}\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"],"mappings":";AAAA,SAAS,eAAe;AACxB,SAAS,cAAc;AAgBvB,eAAsB,YAAY,gBAAgB,OAAO,KAA+B;AACtF,QAAM,kBAAkB,MAAM,OAAO,gBAAgB,EAAE,IAAI,CAAC;AAC5D,MAAI,CAAC,iBAAiB;AACpB,QAAI,eAAe;AACjB,aAAO,QAAQ,IAAI;AAAA,IACrB;AACA,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AACA,SAAO,QAAQ,eAAe;AAChC;;;ACzBA,SAAS,YAAY;AAerB,eAAsB,OAAO,MAAkC;AAC7D,MAAI;AACF,UAAM,KAAK,IAAI;AACf,WAAO;AAAA,EACT,QAAQ;AACN,W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OAAO,cAAsB;AAC1C,cAAM,UAAU,MAAM,KAAK,KAAK,cAAc,WAAW,cAAc,CAAC;AACxE,eAAO,QAAQ,IAAI,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC;AAAA,MACjD,CAAC;AAAA,IACH;AAEA,UAAM,WAAW,aAAa,KAAK;AAEnC,WAAO,SAAS,WAAW,IAAI,CAAC,UAAU,IAAI,CAAC,cAAc,GAAG,QAAQ;AAAA,EAC1E,SAAS,OAAO;AAEd,WAAO,CAAC,UAAU;AAAA,EACpB;AACF;AAEA,eAAe,yBAAyB,iBAA2C;AACjF,MAAI,MAAM,OAAO,eAAe,GAAG;AACjC,UAAM,cAAc,aAAuC,MAAM,SAAS,iBAAiB,OAAO,CAAC;AACnG,QAAI,aAAa,cAAc,MAAM,QAAQ,aAAa,UAAU,KAAK,aAAa,WAAW,SAAS,GAAG;AAC3G,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;","names":["dirname","findUp","dirname"]}
package/dist/http.cjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/http.ts","../src/retry.ts","../src/http/fetch-with-retry.ts","../src/http/graphql-fetch-with-retry.ts","../src/http/headers.ts"],"sourcesContent":["export { fetchWithRetry } from \"./http/fetch-with-retry.js\";\nexport { graphqlFetchWithRetry } from \"./http/graphql-fetch-with-retry.js\";\nexport { appendHeaders } from \"./http/headers.js\";\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","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":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,eAAsB,gBACpB,IACA,aAAa,GACb,mBAAmB,KACnB,aACY;AACZ,MAAI,UA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,cACd,SACA,mBACA;AACA,QAAM,iBAAiB,OAAO,YAAY,aAAa,QAAQ,IAAI;AACnE,QAAM,4BAA4B,OAAO,QAAQ,iBAAiB,EAAE,OAAO,CAAC,CAAC,GAAG,KAAK,MAAM,UAAU,MAAS;AAI9G,MAAI,MAAM,QAAQ,cAAc,GAAG;AACjC,WAAO,CAAC,GAAG,gBAAgB,GAAG,yBAAyB;AAAA,EACzD;AACA,MAAI,0BAA0B,SAAS;AACrC,WAAO,IAAI,QAAQ,CAAC,GAAG,gBAAgB,GAAG,yBAAyB,CAAC;AAAA,EACtE;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG,OAAO,YAAY,yBAAyB;AAAA,EACjD;AACF;","names":[]}
package/dist/http.mjs DELETED
@@ -1,80 +0,0 @@
1
- // src/retry.ts
2
- async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
3
- let attempt = 0;
4
- while (attempt < maxRetries) {
5
- try {
6
- return await fn();
7
- } catch (e) {
8
- if (typeof stopOnError === "function") {
9
- const error = e;
10
- if (stopOnError(error)) {
11
- throw error;
12
- }
13
- }
14
- attempt += 1;
15
- if (attempt >= maxRetries) {
16
- throw e;
17
- }
18
- const jitter = Math.random();
19
- const delay = 2 ** attempt * initialSleepTime * jitter;
20
- await new Promise((resolve) => setTimeout(resolve, delay));
21
- }
22
- }
23
- throw new Error("Retry failed");
24
- }
25
-
26
- // src/http/fetch-with-retry.ts
27
- async function fetchWithRetry(input, init, maxRetries = 5, initialSleepTime = 3e3) {
28
- return retryWhenFailed(
29
- async () => {
30
- const response = await fetch(input, init);
31
- if (response.ok) {
32
- return response;
33
- }
34
- if (response.status < 500 && response.status !== 429 && response.status !== 408 && response.status !== 0) {
35
- return response;
36
- }
37
- throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);
38
- },
39
- maxRetries,
40
- initialSleepTime
41
- );
42
- }
43
-
44
- // src/http/graphql-fetch-with-retry.ts
45
- async function graphqlFetchWithRetry(input, init, maxRetries = 5, initialSleepTime = 3e3) {
46
- return retryWhenFailed(
47
- async () => {
48
- const response = await fetchWithRetry(input, init);
49
- const json = await response.json();
50
- if (json.errors) {
51
- throw new Error(`GraphQL errors in response: ${json.errors.map((error) => error.message).join(", ")}`);
52
- }
53
- return json.data;
54
- },
55
- maxRetries,
56
- initialSleepTime
57
- );
58
- }
59
-
60
- // src/http/headers.ts
61
- function appendHeaders(headers, additionalHeaders) {
62
- const defaultHeaders = typeof headers === "function" ? headers() : headers;
63
- const filteredAdditionalHeaders = Object.entries(additionalHeaders).filter(([_, value]) => value !== void 0);
64
- if (Array.isArray(defaultHeaders)) {
65
- return [...defaultHeaders, ...filteredAdditionalHeaders];
66
- }
67
- if (defaultHeaders instanceof Headers) {
68
- return new Headers([...defaultHeaders, ...filteredAdditionalHeaders]);
69
- }
70
- return {
71
- ...defaultHeaders,
72
- ...Object.fromEntries(filteredAdditionalHeaders)
73
- };
74
- }
75
- export {
76
- appendHeaders,
77
- fetchWithRetry,
78
- graphqlFetchWithRetry
79
- };
80
- //# sourceMappingURL=http.mjs.map
package/dist/http.mjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/retry.ts","../src/http/fetch-with-retry.ts","../src/http/graphql-fetch-with-retry.ts","../src/http/headers.ts"],"sourcesContent":["/**\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","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":";AAaA,eAAsB,gBACpB,IACA,aAAa,GACb,mBAAmB,KACnB,aACY;AACZ,MAAI,UAAU;AAEd,SAAO,UAAU,YAAY;AAC3B,QAAI;AACF,aAAO,MAAM,GAAG;AAAA,IAClB,SAAS,GAAG;AACV,UAAI,OAAO,gBAAgB,YAAY;AACr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AAC,CAAC,GAAG,KAAK,MAAM,UAAU,MAAS;AAI9G,MAAI,MAAM,QAAQ,cAAc,GAAG;AACjC,WAAO,CAAC,GAAG,gBAAgB,GAAG,yBAAyB;AAAA,EACzD;AACA,MAAI,0BAA0B,SAAS;AACrC,WAAO,IAAI,QAAQ,CAAC,GAAG,gBAAgB,GAAG,yBAAyB,CAAC;AAAA,EACtE;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG,OAAO,YAAY,yBAAyB;AAAA,EACjD;AACF;","names":[]}
@@ -1 +0,0 @@
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;A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sB,KAAa;AACjD,SAAO,OAAO,GAAG,EAAE,OAAO,CAAC,EAAE,YAAY,IAAI,OAAO,GAAG,EAAE,MAAM,CAAC;AAClE;AAcO,SAAS,iBAAiB,GAAW;AAC1C,QAAM,SAAS,EAAE,QAAQ,mBAAmB,OAAO;AACnD,QAAM,aAAa,OAAO,QAAQ,mBAAmB,OAAO;AAC5D,QAAM,cAAc,sBAAsB,UAAU;AACpD,SAAO,YAAY,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAC/C;AAcO,SAAS,uCAAuC,GAAW;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;","names":["value"]}
package/dist/index.mjs DELETED
@@ -1,90 +0,0 @@
1
- // src/json.ts
2
- function tryParseJson(value, defaultValue = null) {
3
- try {
4
- const parsed = JSON.parse(value);
5
- if (parsed === void 0 || parsed === null) {
6
- return defaultValue;
7
- }
8
- return parsed;
9
- } catch (err) {
10
- return defaultValue;
11
- }
12
- }
13
- function extractJsonObject(value) {
14
- if (value.length > 5e3) {
15
- throw new Error("Input too long");
16
- }
17
- const result = /\{([\s\S]*)\}/.exec(value);
18
- if (!result) {
19
- return null;
20
- }
21
- return tryParseJson(result[0]);
22
- }
23
- function makeJsonStringifiable(value) {
24
- if (value === void 0 || value === null) {
25
- return value;
26
- }
27
- return tryParseJson(
28
- JSON.stringify(
29
- value,
30
- (_, value2) => typeof value2 === "bigint" ? value2.toString() : value2
31
- // return everything else unchanged
32
- )
33
- );
34
- }
35
-
36
- // src/retry.ts
37
- async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
38
- let attempt = 0;
39
- while (attempt < maxRetries) {
40
- try {
41
- return await fn();
42
- } catch (e) {
43
- if (typeof stopOnError === "function") {
44
- const error = e;
45
- if (stopOnError(error)) {
46
- throw error;
47
- }
48
- }
49
- attempt += 1;
50
- if (attempt >= maxRetries) {
51
- throw e;
52
- }
53
- const jitter = Math.random();
54
- const delay = 2 ** attempt * initialSleepTime * jitter;
55
- await new Promise((resolve) => setTimeout(resolve, delay));
56
- }
57
- }
58
- throw new Error("Retry failed");
59
- }
60
-
61
- // src/string.ts
62
- function capitalizeFirstLetter(val) {
63
- return String(val).charAt(0).toUpperCase() + String(val).slice(1);
64
- }
65
- function camelCaseToWords(s) {
66
- const result = s.replace(/([a-z])([A-Z])/g, "$1 $2");
67
- const withSpaces = result.replace(/([A-Z])([a-z])/g, " $1$2");
68
- const capitalized = capitalizeFirstLetter(withSpaces);
69
- return capitalized.replace(/\s+/g, " ").trim();
70
- }
71
- function replaceUnderscoresAndHyphensWithSpaces(s) {
72
- return s.replace(/[-_]/g, " ");
73
- }
74
- function truncate(value, maxLength) {
75
- if (value.length <= maxLength) {
76
- return value;
77
- }
78
- return `${value.slice(0, maxLength)}...`;
79
- }
80
- export {
81
- camelCaseToWords,
82
- capitalizeFirstLetter,
83
- extractJsonObject,
84
- makeJsonStringifiable,
85
- replaceUnderscoresAndHyphensWithSpaces,
86
- retryWhenFailed,
87
- truncate,
88
- tryParseJson
89
- };
90
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/json.ts","../src/retry.ts","../src/string.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 * 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":";AAsBO,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;;;ACrEA,eAAsB,gBACpB,IACA,aAAa,GACb,mBAAmB,KACnB,aACY;AACZ,MAAI,UAAU;AAEd,SAAO,UAAU,YAAY;AAC3B,QAAI;AACF,aAAO,MAAM,GAAG;AAAA,IAClB,SAAS,GAAG;AACV,UAAI,OAAO,gBAAgB,YAAY;AACrC,cAAM,QAAQ;AACd,YAAI,YAAY,KAAK,GAAG;AACtB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,iBAAW;AACX,UAAI,WAAW,YAAY;AACzB,cAAM;AAAA,MACR;AAEA,YAAM,SAAS,KAAK,OAAO;AAC3B,YAAM,QAAQ,KAAK,UAAU,mBAAmB;AAChD,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,KAAK,CAAC;AAAA,IAC3D;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,cAAc;AAChC;;;AC/BO,SAAS,sBAAsB,KAAa;AACjD,SAAO,OAAO,GAAG,EAAE,OAAO,CAAC,EAAE,YAAY,IAAI,OAAO,GAAG,EAAE,MAAM,CAAC;AAClE;AAcO,SAAS,iBAAiB,GAAW;AAC1C,QAAM,SAAS,EAAE,QAAQ,mBAAmB,OAAO;AACnD,QAAM,aAAa,OAAO,QAAQ,mBAAmB,OAAO;AAC5D,QAAM,cAAc,sBAAsB,UAAU;AACpD,SAAO,YAAY,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAC/C;AAcO,SAAS,uCAAuC,GAAW;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;","names":["value"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/logging.ts","../src/logging/mask-tokens.ts","../src/logging/logger.ts","../src/string.ts","../src/logging/request-logger.ts"],"sourcesContent":["export { createLogger, type Logger, type LoggerOptions, type LogLevel } from \"./logging/logger.js\";\nexport { requestLogger } from \"./logging/request-logger.js\";\nexport { maskTokens } from \"./logging/mask-tokens.js\";\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","/**\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","import { truncate } from \"../string.js\";\nimport type { Logger } from \"./logger.js\";\n\nconst WARNING_THRESHOLD = 500;\nconst TRUNCATE_LENGTH = 50;\n\n/**\n * Logs the request and duration of a fetch call (> 500ms is logged as warn, otherwise info)\n * @param logger - The logger to use\n * @param name - The name of the request\n * @param fn - The fetch function to use\n * @returns The fetch function\n */\nexport function requestLogger(logger: Logger, name: string, fn: typeof fetch) {\n return async (...args: Parameters<typeof fetch>) => {\n const start = Date.now();\n try {\n return await fn(...args);\n } finally {\n const end = Date.now();\n const duration = end - start;\n const body = extractInfoFromBody(args[1]?.body ?? \"{}\");\n const message = `${name} path: ${args[0]}, took ${formatDuration(duration)}`;\n if (duration > WARNING_THRESHOLD) {\n logger.warn(message, body);\n } else {\n logger.info(message, body);\n }\n }\n };\n}\n\nfunction formatDuration(duration: number) {\n return duration < 1000 ? `${duration}ms` : `${(duration / 1000).toFixed(3)}s`;\n}\n\nfunction extractInfoFromBody(body: BodyInit) {\n try {\n const parsedBody = typeof body === \"string\" ? JSON.parse(body) : body;\n\n if (parsedBody === null || parsedBody === undefined || Object.keys(parsedBody).length === 0) {\n return null;\n }\n\n const dataToKeep: Record<string, unknown> = {};\n // Check for graphql fields\n if (\"query\" in parsedBody) {\n dataToKeep.query = truncate(parsedBody.query, TRUNCATE_LENGTH);\n }\n if (\"variables\" in parsedBody) {\n dataToKeep.variables = truncate(JSON.stringify(parsedBody.variables), TRUNCATE_LENGTH);\n }\n if (\"operationName\" in parsedBody) {\n dataToKeep.operationName = truncate(parsedBody.operationName, TRUNCATE_LENGTH);\n }\n\n if (Object.keys(dataToKeep).length > 0) {\n return JSON.stringify(dataToKeep);\n }\n\n // Not graphql, return the body as is\n return truncate(JSON.stringify(parsedBody || \"{}\"), TRUNCATE_LENGTH);\n } catch {\n return \"{}\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYO,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,oBAAoB,UAAU,KAAK;AAEzC,QAAM,aAAa,CAAC,SAA4B;AAC9C,QAAI,KAAK,WAAW,KAAK,KAAK,MAAM,CAAC,QAAQ,QAAQ,UAAa,QAAQ,IAAI,GAAG;AAC/E,aAAO;AAAA,IACT;AAEA,UAAM,YAAY,KACf,IAAI,CAAC,QAAQ;AACZ,UAAI,eAAe,OAAO;AACxB,eAAO;AAAA,EAAK,IAAI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,KAAK,UAAU,EAAE,SAAS,GAAG;AACtC,aAAO,KAAK,UAAU,UAAU;AAAA,IAClC;AAGA,WAAO,SAAS,KAAK,UAAU,cAAc,IAAI,GAAG,eAAe;AAAA,EACrE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["level","logger"]}
package/dist/logging.mjs DELETED
@@ -1,123 +0,0 @@
1
- // src/logging/mask-tokens.ts
2
- var maskTokens = (output) => {
3
- return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
4
- };
5
-
6
- // src/logging/logger.ts
7
- function createLogger(options = {}) {
8
- const { level = "warn", prefix = "" } = options;
9
- const logLevels = {
10
- debug: 0,
11
- info: 1,
12
- warn: 2,
13
- error: 3,
14
- none: 4
15
- };
16
- const currentLevelValue = logLevels[level];
17
- const formatArgs = (args) => {
18
- if (args.length === 0 || args.every((arg) => arg === void 0 || arg === null)) {
19
- return "";
20
- }
21
- const formatted = args.map((arg) => {
22
- if (arg instanceof Error) {
23
- return `
24
- ${arg.stack || arg.message}`;
25
- }
26
- if (typeof arg === "object" && arg !== null) {
27
- return `
28
- ${JSON.stringify(arg, null, 2)}`;
29
- }
30
- return ` ${String(arg)}`;
31
- }).join("");
32
- return `, args:${formatted}`;
33
- };
34
- const shouldLog = (level2) => {
35
- return logLevels[level2] >= currentLevelValue;
36
- };
37
- return {
38
- debug: (message, ...args) => {
39
- if (shouldLog("debug")) {
40
- console.debug(`\x1B[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
41
- }
42
- },
43
- info: (message, ...args) => {
44
- if (shouldLog("info")) {
45
- console.info(`\x1B[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
46
- }
47
- },
48
- warn: (message, ...args) => {
49
- if (shouldLog("warn")) {
50
- console.warn(`\x1B[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
51
- }
52
- },
53
- error: (message, ...args) => {
54
- if (shouldLog("error")) {
55
- console.error(`\x1B[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1B[0m`);
56
- }
57
- }
58
- };
59
- }
60
- var logger = createLogger();
61
-
62
- // src/string.ts
63
- function truncate(value, maxLength) {
64
- if (value.length <= maxLength) {
65
- return value;
66
- }
67
- return `${value.slice(0, maxLength)}...`;
68
- }
69
-
70
- // src/logging/request-logger.ts
71
- var WARNING_THRESHOLD = 500;
72
- var TRUNCATE_LENGTH = 50;
73
- function requestLogger(logger2, name, fn) {
74
- return async (...args) => {
75
- const start = Date.now();
76
- try {
77
- return await fn(...args);
78
- } finally {
79
- const end = Date.now();
80
- const duration = end - start;
81
- const body = extractInfoFromBody(args[1]?.body ?? "{}");
82
- const message = `${name} path: ${args[0]}, took ${formatDuration(duration)}`;
83
- if (duration > WARNING_THRESHOLD) {
84
- logger2.warn(message, body);
85
- } else {
86
- logger2.info(message, body);
87
- }
88
- }
89
- };
90
- }
91
- function formatDuration(duration) {
92
- return duration < 1e3 ? `${duration}ms` : `${(duration / 1e3).toFixed(3)}s`;
93
- }
94
- function extractInfoFromBody(body) {
95
- try {
96
- const parsedBody = typeof body === "string" ? JSON.parse(body) : body;
97
- if (parsedBody === null || parsedBody === void 0 || Object.keys(parsedBody).length === 0) {
98
- return null;
99
- }
100
- const dataToKeep = {};
101
- if ("query" in parsedBody) {
102
- dataToKeep.query = truncate(parsedBody.query, TRUNCATE_LENGTH);
103
- }
104
- if ("variables" in parsedBody) {
105
- dataToKeep.variables = truncate(JSON.stringify(parsedBody.variables), TRUNCATE_LENGTH);
106
- }
107
- if ("operationName" in parsedBody) {
108
- dataToKeep.operationName = truncate(parsedBody.operationName, TRUNCATE_LENGTH);
109
- }
110
- if (Object.keys(dataToKeep).length > 0) {
111
- return JSON.stringify(dataToKeep);
112
- }
113
- return truncate(JSON.stringify(parsedBody || "{}"), TRUNCATE_LENGTH);
114
- } catch {
115
- return "{}";
116
- }
117
- }
118
- export {
119
- createLogger,
120
- maskTokens,
121
- requestLogger
122
- };
123
- //# sourceMappingURL=logging.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/logging/mask-tokens.ts","../src/logging/logger.ts","../src/string.ts","../src/logging/request-logger.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","/**\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","import { truncate } from \"../string.js\";\nimport type { Logger } from \"./logger.js\";\n\nconst WARNING_THRESHOLD = 500;\nconst TRUNCATE_LENGTH = 50;\n\n/**\n * Logs the request and duration of a fetch call (> 500ms is logged as warn, otherwise info)\n * @param logger - The logger to use\n * @param name - The name of the request\n * @param fn - The fetch function to use\n * @returns The fetch function\n */\nexport function requestLogger(logger: Logger, name: string, fn: typeof fetch) {\n return async (...args: Parameters<typeof fetch>) => {\n const start = Date.now();\n try {\n return await fn(...args);\n } finally {\n const end = Date.now();\n const duration = end - start;\n const body = extractInfoFromBody(args[1]?.body ?? \"{}\");\n const message = `${name} path: ${args[0]}, took ${formatDuration(duration)}`;\n if (duration > WARNING_THRESHOLD) {\n logger.warn(message, body);\n } else {\n logger.info(message, body);\n }\n }\n };\n}\n\nfunction formatDuration(duration: number) {\n return duration < 1000 ? `${duration}ms` : `${(duration / 1000).toFixed(3)}s`;\n}\n\nfunction extractInfoFromBody(body: BodyInit) {\n try {\n const parsedBody = typeof body === \"string\" ? JSON.parse(body) : body;\n\n if (parsedBody === null || parsedBody === undefined || Object.keys(parsedBody).length === 0) {\n return null;\n }\n\n const dataToKeep: Record<string, unknown> = {};\n // Check for graphql fields\n if (\"query\" in parsedBody) {\n dataToKeep.query = truncate(parsedBody.query, TRUNCATE_LENGTH);\n }\n if (\"variables\" in parsedBody) {\n dataToKeep.variables = truncate(JSON.stringify(parsedBody.variables), TRUNCATE_LENGTH);\n }\n if (\"operationName\" in parsedBody) {\n dataToKeep.operationName = truncate(parsedBody.operationName, TRUNCATE_LENGTH);\n }\n\n if (Object.keys(dataToKeep).length > 0) {\n return JSON.stringify(dataToKeep);\n }\n\n // Not graphql, return the body as is\n return truncate(JSON.stringify(parsedBody || \"{}\"), TRUNCATE_LENGTH);\n } catch {\n return \"{}\";\n }\n}\n"],"mappings":";AAYO,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,oBAAoB,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