@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.
Files changed (98) hide show
  1. package/README.md +51 -7
  2. package/dist/environment.cjs +17708 -384
  3. package/dist/environment.cjs.map +1 -1
  4. package/dist/environment.d.cts +263 -98
  5. package/dist/environment.d.ts +263 -98
  6. package/dist/environment.js +17746 -0
  7. package/dist/environment.js.map +1 -0
  8. package/dist/filesystem.cjs +6746 -113
  9. package/dist/filesystem.cjs.map +1 -1
  10. package/dist/filesystem.d.cts +22 -1
  11. package/dist/filesystem.d.ts +22 -1
  12. package/dist/filesystem.js +6766 -0
  13. package/dist/filesystem.js.map +1 -0
  14. package/dist/http.cjs +214 -94
  15. package/dist/http.cjs.map +1 -1
  16. package/dist/http.d.cts +9 -1
  17. package/dist/http.d.ts +9 -1
  18. package/dist/http.js +226 -0
  19. package/dist/http.js.map +1 -0
  20. package/dist/index.cjs +295 -104
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +26 -1
  23. package/dist/index.d.ts +26 -1
  24. package/dist/index.js +306 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/json.cjs +83 -0
  27. package/dist/json.cjs.map +1 -0
  28. package/dist/json.d.cts +56 -0
  29. package/dist/json.d.ts +56 -0
  30. package/dist/json.js +80 -0
  31. package/dist/json.js.map +1 -0
  32. package/dist/logging.cjs +209 -137
  33. package/dist/logging.cjs.map +1 -1
  34. package/dist/logging.d.cts +23 -14
  35. package/dist/logging.d.ts +23 -14
  36. package/dist/logging.js +221 -0
  37. package/dist/logging.js.map +1 -0
  38. package/dist/package-manager.cjs +7353 -173
  39. package/dist/package-manager.cjs.map +1 -1
  40. package/dist/package-manager.d.cts +26 -3
  41. package/dist/package-manager.d.ts +26 -3
  42. package/dist/package-manager.js +7385 -0
  43. package/dist/package-manager.js.map +1 -0
  44. package/dist/retry.cjs +137 -0
  45. package/dist/retry.cjs.map +1 -0
  46. package/dist/retry.d.cts +19 -0
  47. package/dist/retry.d.ts +19 -0
  48. package/dist/retry.js +136 -0
  49. package/dist/retry.js.map +1 -0
  50. package/dist/runtime.cjs +58 -40
  51. package/dist/runtime.cjs.map +1 -1
  52. package/dist/runtime.d.cts +3 -0
  53. package/dist/runtime.d.ts +3 -0
  54. package/dist/runtime.js +45 -0
  55. package/dist/runtime.js.map +1 -0
  56. package/dist/string.cjs +76 -0
  57. package/dist/string.cjs.map +1 -0
  58. package/dist/string.d.cts +58 -0
  59. package/dist/string.d.ts +58 -0
  60. package/dist/string.js +72 -0
  61. package/dist/string.js.map +1 -0
  62. package/dist/terminal.cjs +426 -229
  63. package/dist/terminal.cjs.map +1 -1
  64. package/dist/terminal.d.cts +54 -24
  65. package/dist/terminal.d.ts +54 -24
  66. package/dist/terminal.js +441 -0
  67. package/dist/terminal.js.map +1 -0
  68. package/dist/url.cjs +25 -0
  69. package/dist/url.cjs.map +1 -0
  70. package/dist/url.d.cts +20 -0
  71. package/dist/url.d.ts +20 -0
  72. package/dist/url.js +24 -0
  73. package/dist/url.js.map +1 -0
  74. package/dist/validation.cjs +10486 -193
  75. package/dist/validation.cjs.map +1 -1
  76. package/dist/validation.d.cts +124 -94
  77. package/dist/validation.d.ts +124 -94
  78. package/dist/validation.js +10482 -0
  79. package/dist/validation.js.map +1 -0
  80. package/package.json +6 -6
  81. package/dist/environment.mjs +0 -384
  82. package/dist/environment.mjs.map +0 -1
  83. package/dist/filesystem.mjs +0 -105
  84. package/dist/filesystem.mjs.map +0 -1
  85. package/dist/http.mjs +0 -80
  86. package/dist/http.mjs.map +0 -1
  87. package/dist/index.mjs +0 -90
  88. package/dist/index.mjs.map +0 -1
  89. package/dist/logging.mjs +0 -123
  90. package/dist/logging.mjs.map +0 -1
  91. package/dist/package-manager.mjs +0 -167
  92. package/dist/package-manager.mjs.map +0 -1
  93. package/dist/runtime.mjs +0 -23
  94. package/dist/runtime.mjs.map +0 -1
  95. package/dist/terminal.mjs +0 -230
  96. package/dist/terminal.mjs.map +0 -1
  97. package/dist/validation.mjs +0 -161
  98. package/dist/validation.mjs.map +0 -1
package/dist/retry.cjs ADDED
@@ -0,0 +1,137 @@
1
+
2
+ //#region src/logging/mask-tokens.ts
3
+ /**
4
+ * Masks sensitive SettleMint tokens in output text by replacing them with asterisks.
5
+ * Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT).
6
+ *
7
+ * @param output - The text string that may contain sensitive tokens
8
+ * @returns The text with any sensitive tokens masked with asterisks
9
+ * @example
10
+ * import { maskTokens } from "@settlemint/sdk-utils/terminal";
11
+ *
12
+ * // Masks a token in text
13
+ * const masked = maskTokens("Token: sm_pat_****"); // "Token: ***"
14
+ */
15
+ const maskTokens = (output) => {
16
+ return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
17
+ };
18
+
19
+ //#endregion
20
+ //#region src/logging/logger.ts
21
+ /**
22
+ * Creates a simple logger with configurable log level
23
+ *
24
+ * @param options - Configuration options for the logger
25
+ * @param options.level - The minimum log level to output (default: warn)
26
+ * @param options.prefix - The prefix to add to the log message (default: "")
27
+ * @returns A logger instance with debug, info, warn, and error methods
28
+ *
29
+ * @example
30
+ * import { createLogger } from "@/utils/logging/logger";
31
+ *
32
+ * const logger = createLogger({ level: 'info' });
33
+ *
34
+ * logger.info('User logged in', { userId: '123' });
35
+ * logger.error('Operation failed', new Error('Connection timeout'));
36
+ */
37
+ function createLogger(options = {}) {
38
+ const { level = "warn", prefix = "" } = options;
39
+ const logLevels = {
40
+ debug: 0,
41
+ info: 1,
42
+ warn: 2,
43
+ error: 3,
44
+ none: 4
45
+ };
46
+ const currentLevelValue = logLevels[level];
47
+ const formatArgs = (args) => {
48
+ if (args.length === 0 || args.every((arg) => arg === undefined || arg === null)) {
49
+ return "";
50
+ }
51
+ const formatted = args.map((arg) => {
52
+ if (arg instanceof Error) {
53
+ return `\n${arg.stack || arg.message}`;
54
+ }
55
+ if (typeof arg === "object" && arg !== null) {
56
+ return `\n${JSON.stringify(arg, null, 2)}`;
57
+ }
58
+ return ` ${String(arg)}`;
59
+ }).join("");
60
+ return `, args:${formatted}`;
61
+ };
62
+ const shouldLog = (level$1) => {
63
+ return logLevels[level$1] >= currentLevelValue;
64
+ };
65
+ return {
66
+ debug: (message, ...args) => {
67
+ if (shouldLog("debug")) {
68
+ console.debug(`\x1b[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
69
+ }
70
+ },
71
+ info: (message, ...args) => {
72
+ if (shouldLog("info")) {
73
+ console.info(`\x1b[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
74
+ }
75
+ },
76
+ warn: (message, ...args) => {
77
+ if (shouldLog("warn")) {
78
+ console.warn(`\x1b[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
79
+ }
80
+ },
81
+ error: (message, ...args) => {
82
+ if (shouldLog("error")) {
83
+ console.error(`\x1b[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
84
+ }
85
+ }
86
+ };
87
+ }
88
+ /**
89
+ * Default logger instance with standard configuration
90
+ */
91
+ const logger = createLogger();
92
+
93
+ //#endregion
94
+ //#region src/retry.ts
95
+ /**
96
+ * Retry a function when it fails.
97
+ * @param fn - The function to retry.
98
+ * @param maxRetries - The maximum number of retries.
99
+ * @param initialSleepTime - The initial time to sleep between exponential backoff retries.
100
+ * @param stopOnError - The function to stop on error.
101
+ * @returns The result of the function or undefined if it fails.
102
+ * @example
103
+ * import { retryWhenFailed } from "@settlemint/sdk-utils";
104
+ * import { readFile } from "node:fs/promises";
105
+ *
106
+ * const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
107
+ */
108
+ async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
109
+ let retries = 0;
110
+ const maxAttempts = maxRetries + 1;
111
+ while (retries < maxAttempts) {
112
+ try {
113
+ return await fn();
114
+ } catch (e) {
115
+ const error = e;
116
+ if (typeof stopOnError === "function") {
117
+ if (stopOnError(error)) {
118
+ throw error;
119
+ }
120
+ }
121
+ if (retries >= maxRetries) {
122
+ throw e;
123
+ }
124
+ const baseDelay = 2 ** retries * initialSleepTime;
125
+ const jitterAmount = initialSleepTime * (Math.random() / 10);
126
+ const delay = baseDelay + jitterAmount;
127
+ retries += 1;
128
+ logger.warn(`An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`);
129
+ await new Promise((resolve) => setTimeout(resolve, delay));
130
+ }
131
+ }
132
+ throw new Error("Retry failed");
133
+ }
134
+
135
+ //#endregion
136
+ exports.retryWhenFailed = retryWhenFailed;
137
+ //# sourceMappingURL=retry.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.cjs","names":["output: string","options: LoggerOptions","logLevels: Record<LogLevel, number>","args: unknown[]","level: LogLevel","level","message: string","fn: () => Promise<T>","stopOnError?: (error: Error) => boolean"],"sources":["../src/logging/mask-tokens.ts","../src/logging/logger.ts","../src/retry.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"],"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;AACtB,YAAQ,OAAO,UAAU,OAAO,UAAU,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACvG;EACF;EACD,MAAM,CAACA,SAAiB,GAAG,SAAoB;AAC7C,OAAI,UAAU,OAAO,EAAE;AACrB,YAAQ,MAAM,UAAU,OAAO,SAAS,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACrG;EACF;EACD,MAAM,CAACA,SAAiB,GAAG,SAAoB;AAC7C,OAAI,UAAU,OAAO,EAAE;AACrB,YAAQ,MAAM,UAAU,OAAO,SAAS,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACrG;EACF;EACD,OAAO,CAACA,SAAiB,GAAG,SAAoB;AAC9C,OAAI,UAAU,QAAQ,EAAE;AACtB,YAAQ,OAAO,UAAU,OAAO,UAAU,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACvG;EACF;CACF;AACF;;;;AAKD,MAAa,SAAS,cAAc;;;;;;;;;;;;;;;;;AClGpC,eAAsB,gBACpBC,IACA,aAAa,GACb,mBAAmB,KACnBC,aACY;CACZ,IAAI,UAAU;CACd,MAAM,cAAc,aAAa;AAEjC,QAAO,UAAU,aAAa;AAC5B,MAAI;AACF,UAAO,MAAM,IAAI;EAClB,SAAQ,GAAG;GACV,MAAM,QAAQ;AACd,cAAW,gBAAgB,YAAY;AACrC,QAAI,YAAY,MAAM,EAAE;AACtB,WAAM;IACP;GACF;AACD,OAAI,WAAW,YAAY;AACzB,UAAM;GACP;GAGD,MAAM,YAAY,KAAK,UAAU;GACjC,MAAM,eAAe,oBAAoB,KAAK,QAAQ,GAAG;GACzD,MAAM,QAAQ,YAAY;AAC1B,cAAW;AACX,UAAO,MACJ,oBAAoB,MAAM,QAAQ,gBAAgB,MAAM,QAAQ,EAAE,CAAC,YAAY,QAAQ,MAAM,WAAW,MAC1G;AACD,SAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,MAAM;EAC1D;CACF;AAED,OAAM,IAAI,MAAM;AACjB"}
@@ -0,0 +1,19 @@
1
+ //#region src/retry.d.ts
2
+ /**
3
+ * Retry a function when it fails.
4
+ * @param fn - The function to retry.
5
+ * @param maxRetries - The maximum number of retries.
6
+ * @param initialSleepTime - The initial time to sleep between exponential backoff retries.
7
+ * @param stopOnError - The function to stop on error.
8
+ * @returns The result of the function or undefined if it fails.
9
+ * @example
10
+ * import { retryWhenFailed } from "@settlemint/sdk-utils";
11
+ * import { readFile } from "node:fs/promises";
12
+ *
13
+ * const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
14
+ */
15
+ declare function retryWhenFailed<T>(fn: () => Promise<T>, maxRetries?: number, initialSleepTime?: number, stopOnError?: (error: Error) => boolean): Promise<T>;
16
+
17
+ //#endregion
18
+ export { retryWhenFailed };
19
+ //# sourceMappingURL=retry.d.cts.map
@@ -0,0 +1,19 @@
1
+ //#region src/retry.d.ts
2
+ /**
3
+ * Retry a function when it fails.
4
+ * @param fn - The function to retry.
5
+ * @param maxRetries - The maximum number of retries.
6
+ * @param initialSleepTime - The initial time to sleep between exponential backoff retries.
7
+ * @param stopOnError - The function to stop on error.
8
+ * @returns The result of the function or undefined if it fails.
9
+ * @example
10
+ * import { retryWhenFailed } from "@settlemint/sdk-utils";
11
+ * import { readFile } from "node:fs/promises";
12
+ *
13
+ * const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
14
+ */
15
+ declare function retryWhenFailed<T>(fn: () => Promise<T>, maxRetries?: number, initialSleepTime?: number, stopOnError?: (error: Error) => boolean): Promise<T>;
16
+
17
+ //#endregion
18
+ export { retryWhenFailed };
19
+ //# sourceMappingURL=retry.d.ts.map
package/dist/retry.js ADDED
@@ -0,0 +1,136 @@
1
+ //#region src/logging/mask-tokens.ts
2
+ /**
3
+ * Masks sensitive SettleMint tokens in output text by replacing them with asterisks.
4
+ * Handles personal access tokens (PAT), application access tokens (AAT), and service account tokens (SAT).
5
+ *
6
+ * @param output - The text string that may contain sensitive tokens
7
+ * @returns The text with any sensitive tokens masked with asterisks
8
+ * @example
9
+ * import { maskTokens } from "@settlemint/sdk-utils/terminal";
10
+ *
11
+ * // Masks a token in text
12
+ * const masked = maskTokens("Token: sm_pat_****"); // "Token: ***"
13
+ */
14
+ const maskTokens = (output) => {
15
+ return output.replace(/sm_(pat|aat|sat)_[0-9a-zA-Z]+/g, "***");
16
+ };
17
+
18
+ //#endregion
19
+ //#region src/logging/logger.ts
20
+ /**
21
+ * Creates a simple logger with configurable log level
22
+ *
23
+ * @param options - Configuration options for the logger
24
+ * @param options.level - The minimum log level to output (default: warn)
25
+ * @param options.prefix - The prefix to add to the log message (default: "")
26
+ * @returns A logger instance with debug, info, warn, and error methods
27
+ *
28
+ * @example
29
+ * import { createLogger } from "@/utils/logging/logger";
30
+ *
31
+ * const logger = createLogger({ level: 'info' });
32
+ *
33
+ * logger.info('User logged in', { userId: '123' });
34
+ * logger.error('Operation failed', new Error('Connection timeout'));
35
+ */
36
+ function createLogger(options = {}) {
37
+ const { level = "warn", prefix = "" } = options;
38
+ const logLevels = {
39
+ debug: 0,
40
+ info: 1,
41
+ warn: 2,
42
+ error: 3,
43
+ none: 4
44
+ };
45
+ const currentLevelValue = logLevels[level];
46
+ const formatArgs = (args) => {
47
+ if (args.length === 0 || args.every((arg) => arg === undefined || arg === null)) {
48
+ return "";
49
+ }
50
+ const formatted = args.map((arg) => {
51
+ if (arg instanceof Error) {
52
+ return `\n${arg.stack || arg.message}`;
53
+ }
54
+ if (typeof arg === "object" && arg !== null) {
55
+ return `\n${JSON.stringify(arg, null, 2)}`;
56
+ }
57
+ return ` ${String(arg)}`;
58
+ }).join("");
59
+ return `, args:${formatted}`;
60
+ };
61
+ const shouldLog = (level$1) => {
62
+ return logLevels[level$1] >= currentLevelValue;
63
+ };
64
+ return {
65
+ debug: (message, ...args) => {
66
+ if (shouldLog("debug")) {
67
+ console.debug(`\x1b[32m${prefix}[DEBUG] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
68
+ }
69
+ },
70
+ info: (message, ...args) => {
71
+ if (shouldLog("info")) {
72
+ console.info(`\x1b[34m${prefix}[INFO] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
73
+ }
74
+ },
75
+ warn: (message, ...args) => {
76
+ if (shouldLog("warn")) {
77
+ console.warn(`\x1b[33m${prefix}[WARN] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
78
+ }
79
+ },
80
+ error: (message, ...args) => {
81
+ if (shouldLog("error")) {
82
+ console.error(`\x1b[31m${prefix}[ERROR] ${maskTokens(message)}${maskTokens(formatArgs(args))}\x1b[0m`);
83
+ }
84
+ }
85
+ };
86
+ }
87
+ /**
88
+ * Default logger instance with standard configuration
89
+ */
90
+ const logger = createLogger();
91
+
92
+ //#endregion
93
+ //#region src/retry.ts
94
+ /**
95
+ * Retry a function when it fails.
96
+ * @param fn - The function to retry.
97
+ * @param maxRetries - The maximum number of retries.
98
+ * @param initialSleepTime - The initial time to sleep between exponential backoff retries.
99
+ * @param stopOnError - The function to stop on error.
100
+ * @returns The result of the function or undefined if it fails.
101
+ * @example
102
+ * import { retryWhenFailed } from "@settlemint/sdk-utils";
103
+ * import { readFile } from "node:fs/promises";
104
+ *
105
+ * const result = await retryWhenFailed(() => readFile("/path/to/file.txt"), 3, 1_000);
106
+ */
107
+ async function retryWhenFailed(fn, maxRetries = 5, initialSleepTime = 1e3, stopOnError) {
108
+ let retries = 0;
109
+ const maxAttempts = maxRetries + 1;
110
+ while (retries < maxAttempts) {
111
+ try {
112
+ return await fn();
113
+ } catch (e) {
114
+ const error = e;
115
+ if (typeof stopOnError === "function") {
116
+ if (stopOnError(error)) {
117
+ throw error;
118
+ }
119
+ }
120
+ if (retries >= maxRetries) {
121
+ throw e;
122
+ }
123
+ const baseDelay = 2 ** retries * initialSleepTime;
124
+ const jitterAmount = initialSleepTime * (Math.random() / 10);
125
+ const delay = baseDelay + jitterAmount;
126
+ retries += 1;
127
+ logger.warn(`An error occurred ${error.message}, retrying in ${delay.toFixed(0)}ms (retry ${retries} of ${maxRetries})...`);
128
+ await new Promise((resolve) => setTimeout(resolve, delay));
129
+ }
130
+ }
131
+ throw new Error("Retry failed");
132
+ }
133
+
134
+ //#endregion
135
+ export { retryWhenFailed };
136
+ //# sourceMappingURL=retry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retry.js","names":["output: string","options: LoggerOptions","logLevels: Record<LogLevel, number>","args: unknown[]","level: LogLevel","level","message: string","fn: () => Promise<T>","stopOnError?: (error: Error) => boolean"],"sources":["../src/logging/mask-tokens.ts","../src/logging/logger.ts","../src/retry.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"],"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;AACtB,YAAQ,OAAO,UAAU,OAAO,UAAU,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACvG;EACF;EACD,MAAM,CAACA,SAAiB,GAAG,SAAoB;AAC7C,OAAI,UAAU,OAAO,EAAE;AACrB,YAAQ,MAAM,UAAU,OAAO,SAAS,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACrG;EACF;EACD,MAAM,CAACA,SAAiB,GAAG,SAAoB;AAC7C,OAAI,UAAU,OAAO,EAAE;AACrB,YAAQ,MAAM,UAAU,OAAO,SAAS,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACrG;EACF;EACD,OAAO,CAACA,SAAiB,GAAG,SAAoB;AAC9C,OAAI,UAAU,QAAQ,EAAE;AACtB,YAAQ,OAAO,UAAU,OAAO,UAAU,WAAW,QAAQ,CAAC,EAAE,WAAW,WAAW,KAAK,CAAC,CAAC,SAAS;GACvG;EACF;CACF;AACF;;;;AAKD,MAAa,SAAS,cAAc;;;;;;;;;;;;;;;;;AClGpC,eAAsB,gBACpBC,IACA,aAAa,GACb,mBAAmB,KACnBC,aACY;CACZ,IAAI,UAAU;CACd,MAAM,cAAc,aAAa;AAEjC,QAAO,UAAU,aAAa;AAC5B,MAAI;AACF,UAAO,MAAM,IAAI;EAClB,SAAQ,GAAG;GACV,MAAM,QAAQ;AACd,cAAW,gBAAgB,YAAY;AACrC,QAAI,YAAY,MAAM,EAAE;AACtB,WAAM;IACP;GACF;AACD,OAAI,WAAW,YAAY;AACzB,UAAM;GACP;GAGD,MAAM,YAAY,KAAK,UAAU;GACjC,MAAM,eAAe,oBAAoB,KAAK,QAAQ,GAAG;GACzD,MAAM,QAAQ,YAAY;AAC1B,cAAW;AACX,UAAO,MACJ,oBAAoB,MAAM,QAAQ,gBAAgB,MAAM,QAAQ,EAAE,CAAC,YAAY,QAAQ,MAAM,WAAW,MAC1G;AACD,SAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,MAAM;EAC1D;CACF;AAED,OAAM,IAAI,MAAM;AACjB"}
package/dist/runtime.cjs CHANGED
@@ -1,53 +1,71 @@
1
- "use strict";
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  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
8
  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;
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
17
  };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
19
22
 
20
- // src/runtime.ts
21
- var runtime_exports = {};
22
- __export(runtime_exports, {
23
- ensureBrowser: () => ensureBrowser,
24
- ensureServer: () => ensureServer,
25
- runsInBrowser: () => runsInBrowser,
26
- runsOnServer: () => runsOnServer
27
- });
28
- module.exports = __toCommonJS(runtime_exports);
23
+ //#endregion
24
+ const environment = __toESM(require("environment"));
29
25
 
30
- // src/runtime/ensure-server.ts
31
- var import_environment = require("environment");
26
+ //#region src/runtime/ensure-server.ts
27
+ /**
28
+ * Ensures that code is running on the server and not in a browser environment.
29
+ *
30
+ * @throws {Error} If called from a browser environment
31
+ * @example
32
+ * import { ensureServer } from "@settlemint/sdk-utils/runtime";
33
+ *
34
+ * // Will throw if running in browser
35
+ * ensureServer();
36
+ */
32
37
  function ensureServer() {
33
- if (import_environment.isBrowser) {
34
- throw new Error(
35
- "This function can only be used on the server as including it in the browser will expose your access token."
36
- );
37
- }
38
+ if (environment.isBrowser) {
39
+ throw new Error("This function can only be used on the server as including it in the browser will expose your access token.");
40
+ }
38
41
  }
42
+ /**
43
+ * Ensures that code is running in a browser environment and not on the server.
44
+ *
45
+ * @throws {Error} If called from a server environment
46
+ * @example
47
+ * import { ensureBrowser } from "@settlemint/sdk-utils/runtime";
48
+ *
49
+ * // Will throw if running on server
50
+ * ensureBrowser();
51
+ */
39
52
  function ensureBrowser() {
40
- if (!import_environment.isBrowser) {
41
- throw new Error("This function can only be used on the browser as it is missing the access token.");
42
- }
53
+ if (!environment.isBrowser) {
54
+ throw new Error("This function can only be used on the browser as it is missing the access token.");
55
+ }
43
56
  }
44
- var runsInBrowser = import_environment.isBrowser;
45
- var runsOnServer = !import_environment.isBrowser;
46
- // Annotate the CommonJS export names for ESM import in node:
47
- 0 && (module.exports = {
48
- ensureBrowser,
49
- ensureServer,
50
- runsInBrowser,
51
- runsOnServer
52
- });
57
+ /**
58
+ * Boolean indicating if code is currently running in a browser environment
59
+ */
60
+ const runsInBrowser = environment.isBrowser;
61
+ /**
62
+ * Boolean indicating if code is currently running in a server environment
63
+ */
64
+ const runsOnServer = !environment.isBrowser;
65
+
66
+ //#endregion
67
+ exports.ensureBrowser = ensureBrowser;
68
+ exports.ensureServer = ensureServer;
69
+ exports.runsInBrowser = runsInBrowser;
70
+ exports.runsOnServer = runsOnServer;
53
71
  //# sourceMappingURL=runtime.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runtime.ts","../src/runtime/ensure-server.ts"],"sourcesContent":["export { ensureBrowser, ensureServer, runsInBrowser, runsOnServer } from \"./runtime/ensure-server.js\";\n","import { isBrowser } from \"environment\";\n\n/**\n * Ensures that code is running on the server and not in a browser environment.\n *\n * @throws {Error} If called from a browser environment\n * @example\n * import { ensureServer } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running in browser\n * ensureServer();\n */\nexport function ensureServer(): void {\n if (isBrowser) {\n throw new Error(\n \"This function can only be used on the server as including it in the browser will expose your access token.\",\n );\n }\n}\n\n/**\n * Ensures that code is running in a browser environment and not on the server.\n *\n * @throws {Error} If called from a server environment\n * @example\n * import { ensureBrowser } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running on server\n * ensureBrowser();\n */\nexport function ensureBrowser(): void {\n if (!isBrowser) {\n throw new Error(\"This function can only be used on the browser as it is missing the access token.\");\n }\n}\n\n/**\n * Boolean indicating if code is currently running in a browser environment\n */\nexport const runsInBrowser = isBrowser;\n\n/**\n * Boolean indicating if code is currently running in a server environment\n */\nexport const runsOnServer = !isBrowser;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA0B;AAYnB,SAAS,eAAqB;AACnC,MAAI,8BAAW;AACb,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;AAYO,SAAS,gBAAsB;AACpC,MAAI,CAAC,8BAAW;AACd,UAAM,IAAI,MAAM,kFAAkF;AAAA,EACpG;AACF;AAKO,IAAM,gBAAgB;AAKtB,IAAM,eAAe,CAAC;","names":[]}
1
+ {"version":3,"file":"runtime.cjs","names":["isBrowser"],"sources":["../src/runtime/ensure-server.ts"],"sourcesContent":["import { isBrowser } from \"environment\";\n\n/**\n * Ensures that code is running on the server and not in a browser environment.\n *\n * @throws {Error} If called from a browser environment\n * @example\n * import { ensureServer } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running in browser\n * ensureServer();\n */\nexport function ensureServer(): void {\n if (isBrowser) {\n throw new Error(\n \"This function can only be used on the server as including it in the browser will expose your access token.\",\n );\n }\n}\n\n/**\n * Ensures that code is running in a browser environment and not on the server.\n *\n * @throws {Error} If called from a server environment\n * @example\n * import { ensureBrowser } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running on server\n * ensureBrowser();\n */\nexport function ensureBrowser(): void {\n if (!isBrowser) {\n throw new Error(\"This function can only be used on the browser as it is missing the access token.\");\n }\n}\n\n/**\n * Boolean indicating if code is currently running in a browser environment\n */\nexport const runsInBrowser = isBrowser;\n\n/**\n * Boolean indicating if code is currently running in a server environment\n */\nexport const runsOnServer = !isBrowser;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,SAAgB,eAAqB;AACnC,KAAIA,uBAAW;AACb,QAAM,IAAI,MACR;CAEH;AACF;;;;;;;;;;;AAYD,SAAgB,gBAAsB;AACpC,MAAKA,uBAAW;AACd,QAAM,IAAI,MAAM;CACjB;AACF;;;;AAKD,MAAa,gBAAgBA;;;;AAK7B,MAAa,gBAAgBA"}
@@ -1,3 +1,4 @@
1
+ //#region src/runtime/ensure-server.d.ts
1
2
  /**
2
3
  * Ensures that code is running on the server and not in a browser environment.
3
4
  *
@@ -29,4 +30,6 @@ declare const runsInBrowser: boolean;
29
30
  */
30
31
  declare const runsOnServer: boolean;
31
32
 
33
+ //#endregion
32
34
  export { ensureBrowser, ensureServer, runsInBrowser, runsOnServer };
35
+ //# sourceMappingURL=runtime.d.cts.map
package/dist/runtime.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ //#region src/runtime/ensure-server.d.ts
1
2
  /**
2
3
  * Ensures that code is running on the server and not in a browser environment.
3
4
  *
@@ -29,4 +30,6 @@ declare const runsInBrowser: boolean;
29
30
  */
30
31
  declare const runsOnServer: boolean;
31
32
 
33
+ //#endregion
32
34
  export { ensureBrowser, ensureServer, runsInBrowser, runsOnServer };
35
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1,45 @@
1
+ import { isBrowser } from "environment";
2
+
3
+ //#region src/runtime/ensure-server.ts
4
+ /**
5
+ * Ensures that code is running on the server and not in a browser environment.
6
+ *
7
+ * @throws {Error} If called from a browser environment
8
+ * @example
9
+ * import { ensureServer } from "@settlemint/sdk-utils/runtime";
10
+ *
11
+ * // Will throw if running in browser
12
+ * ensureServer();
13
+ */
14
+ function ensureServer() {
15
+ if (isBrowser) {
16
+ throw new Error("This function can only be used on the server as including it in the browser will expose your access token.");
17
+ }
18
+ }
19
+ /**
20
+ * Ensures that code is running in a browser environment and not on the server.
21
+ *
22
+ * @throws {Error} If called from a server environment
23
+ * @example
24
+ * import { ensureBrowser } from "@settlemint/sdk-utils/runtime";
25
+ *
26
+ * // Will throw if running on server
27
+ * ensureBrowser();
28
+ */
29
+ function ensureBrowser() {
30
+ if (!isBrowser) {
31
+ throw new Error("This function can only be used on the browser as it is missing the access token.");
32
+ }
33
+ }
34
+ /**
35
+ * Boolean indicating if code is currently running in a browser environment
36
+ */
37
+ const runsInBrowser = isBrowser;
38
+ /**
39
+ * Boolean indicating if code is currently running in a server environment
40
+ */
41
+ const runsOnServer = !isBrowser;
42
+
43
+ //#endregion
44
+ export { ensureBrowser, ensureServer, runsInBrowser, runsOnServer };
45
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","names":[],"sources":["../src/runtime/ensure-server.ts"],"sourcesContent":["import { isBrowser } from \"environment\";\n\n/**\n * Ensures that code is running on the server and not in a browser environment.\n *\n * @throws {Error} If called from a browser environment\n * @example\n * import { ensureServer } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running in browser\n * ensureServer();\n */\nexport function ensureServer(): void {\n if (isBrowser) {\n throw new Error(\n \"This function can only be used on the server as including it in the browser will expose your access token.\",\n );\n }\n}\n\n/**\n * Ensures that code is running in a browser environment and not on the server.\n *\n * @throws {Error} If called from a server environment\n * @example\n * import { ensureBrowser } from \"@settlemint/sdk-utils/runtime\";\n *\n * // Will throw if running on server\n * ensureBrowser();\n */\nexport function ensureBrowser(): void {\n if (!isBrowser) {\n throw new Error(\"This function can only be used on the browser as it is missing the access token.\");\n }\n}\n\n/**\n * Boolean indicating if code is currently running in a browser environment\n */\nexport const runsInBrowser = isBrowser;\n\n/**\n * Boolean indicating if code is currently running in a server environment\n */\nexport const runsOnServer = !isBrowser;\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,eAAqB;AACnC,KAAI,WAAW;AACb,QAAM,IAAI,MACR;CAEH;AACF;;;;;;;;;;;AAYD,SAAgB,gBAAsB;AACpC,MAAK,WAAW;AACd,QAAM,IAAI,MAAM;CACjB;AACF;;;;AAKD,MAAa,gBAAgB;;;;AAK7B,MAAa,gBAAgB"}
@@ -0,0 +1,76 @@
1
+
2
+ //#region src/string.ts
3
+ /**
4
+ * Capitalizes the first letter of a string.
5
+ *
6
+ * @param val - The string to capitalize
7
+ * @returns The input string with its first letter capitalized
8
+ *
9
+ * @example
10
+ * import { capitalizeFirstLetter } from "@settlemint/sdk-utils";
11
+ *
12
+ * const capitalized = capitalizeFirstLetter("hello");
13
+ * // Returns: "Hello"
14
+ */
15
+ function capitalizeFirstLetter(val) {
16
+ return String(val).charAt(0).toUpperCase() + String(val).slice(1);
17
+ }
18
+ /**
19
+ * Converts a camelCase string to a human-readable string.
20
+ *
21
+ * @param s - The camelCase string to convert
22
+ * @returns The human-readable string
23
+ *
24
+ * @example
25
+ * import { camelCaseToWords } from "@settlemint/sdk-utils";
26
+ *
27
+ * const words = camelCaseToWords("camelCaseString");
28
+ * // Returns: "Camel Case String"
29
+ */
30
+ function camelCaseToWords(s) {
31
+ const result = s.replace(/([a-z])([A-Z])/g, "$1 $2");
32
+ const withSpaces = result.replace(/([A-Z])([a-z])/g, " $1$2");
33
+ const capitalized = capitalizeFirstLetter(withSpaces);
34
+ return capitalized.replace(/\s+/g, " ").trim();
35
+ }
36
+ /**
37
+ * Replaces underscores and hyphens with spaces.
38
+ *
39
+ * @param s - The string to replace underscores and hyphens with spaces
40
+ * @returns The input string with underscores and hyphens replaced with spaces
41
+ *
42
+ * @example
43
+ * import { replaceUnderscoresAndHyphensWithSpaces } from "@settlemint/sdk-utils";
44
+ *
45
+ * const result = replaceUnderscoresAndHyphensWithSpaces("Already_Spaced-Second");
46
+ * // Returns: "Already Spaced Second"
47
+ */
48
+ function replaceUnderscoresAndHyphensWithSpaces(s) {
49
+ return s.replace(/[-_]/g, " ");
50
+ }
51
+ /**
52
+ * Truncates a string to a maximum length and appends "..." if it is longer.
53
+ *
54
+ * @param value - The string to truncate
55
+ * @param maxLength - The maximum length of the string
56
+ * @returns The truncated string or the original string if it is shorter than the maximum length
57
+ *
58
+ * @example
59
+ * import { truncate } from "@settlemint/sdk-utils";
60
+ *
61
+ * const truncated = truncate("Hello, world!", 10);
62
+ * // Returns: "Hello, wor..."
63
+ */
64
+ function truncate(value, maxLength) {
65
+ if (value.length <= maxLength) {
66
+ return value;
67
+ }
68
+ return `${value.slice(0, maxLength)}...`;
69
+ }
70
+
71
+ //#endregion
72
+ exports.camelCaseToWords = camelCaseToWords;
73
+ exports.capitalizeFirstLetter = capitalizeFirstLetter;
74
+ exports.replaceUnderscoresAndHyphensWithSpaces = replaceUnderscoresAndHyphensWithSpaces;
75
+ exports.truncate = truncate;
76
+ //# sourceMappingURL=string.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"string.cjs","names":["val: string","s: string","value: string","maxLength: number"],"sources":["../src/string.ts"],"sourcesContent":["/**\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":";;;;;;;;;;;;;;AAYA,SAAgB,sBAAsBA,KAAa;AACjD,QAAO,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC,aAAa,GAAG,OAAO,IAAI,CAAC,MAAM,EAAE;AAClE;;;;;;;;;;;;;AAcD,SAAgB,iBAAiBC,GAAW;CAC1C,MAAM,SAAS,EAAE,QAAQ,mBAAmB,QAAQ;CACpD,MAAM,aAAa,OAAO,QAAQ,mBAAmB,QAAQ;CAC7D,MAAM,cAAc,sBAAsB,WAAW;AACrD,QAAO,YAAY,QAAQ,QAAQ,IAAI,CAAC,MAAM;AAC/C;;;;;;;;;;;;;AAcD,SAAgB,uCAAuCA,GAAW;AAChE,QAAO,EAAE,QAAQ,SAAS,IAAI;AAC/B;;;;;;;;;;;;;;AAeD,SAAgB,SAASC,OAAeC,WAAmB;AACzD,KAAI,MAAM,UAAU,WAAW;AAC7B,SAAO;CACR;AACD,SAAQ,EAAE,MAAM,MAAM,GAAG,UAAU,CAAC;AACrC"}