@venizia/ignis-helpers 0.4.0 → 0.4.2

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 (273) hide show
  1. package/dist/cjs/common/constants/duration.d.ts +4 -1
  2. package/dist/cjs/common/constants/duration.d.ts.map +1 -1
  3. package/dist/cjs/common/constants/duration.js +13 -8
  4. package/dist/cjs/common/constants/duration.js.map +1 -1
  5. package/dist/cjs/common/redact.js +1 -1
  6. package/dist/cjs/common/redact.js.map +1 -1
  7. package/dist/cjs/modules/base.js +1 -1
  8. package/dist/cjs/modules/base.js.map +1 -1
  9. package/dist/cjs/modules/crypto/algorithms/aes.algorithm.js +1 -1
  10. package/dist/cjs/modules/crypto/algorithms/aes.algorithm.js.map +1 -1
  11. package/dist/cjs/modules/env/app-env.d.ts.map +1 -1
  12. package/dist/cjs/modules/env/app-env.js +1 -1
  13. package/dist/cjs/modules/env/app-env.js.map +1 -1
  14. package/dist/cjs/modules/logger/common/constants.js +1 -1
  15. package/dist/cjs/modules/logger/common/constants.js.map +1 -1
  16. package/dist/cjs/modules/logger/factory.js +1 -1
  17. package/dist/cjs/modules/logger/factory.js.map +1 -1
  18. package/dist/cjs/modules/logger/formatting/deep-splat.js +1 -1
  19. package/dist/cjs/modules/logger/formatting/deep-splat.js.map +1 -1
  20. package/dist/cjs/modules/logger/formatting/error-prettier.js +4 -4
  21. package/dist/cjs/modules/logger/formatting/error-prettier.js.map +1 -1
  22. package/dist/cjs/modules/logger/hf/flusher.js +3 -3
  23. package/dist/cjs/modules/logger/hf/flusher.js.map +1 -1
  24. package/dist/cjs/modules/logger/hf/logger.d.ts.map +1 -1
  25. package/dist/cjs/modules/logger/hf/logger.js +3 -1
  26. package/dist/cjs/modules/logger/hf/logger.js.map +1 -1
  27. package/dist/cjs/modules/logger/resolver.js +3 -3
  28. package/dist/cjs/modules/logger/resolver.js.map +1 -1
  29. package/dist/cjs/modules/logger/winston/formatters/deep-splat.js +1 -1
  30. package/dist/cjs/modules/logger/winston/formatters/deep-splat.js.map +1 -1
  31. package/dist/cjs/modules/logger/winston/logger-factory.js +1 -1
  32. package/dist/cjs/modules/logger/winston/logger-factory.js.map +1 -1
  33. package/dist/cjs/modules/logger/winston/transports/dgram.transport.js +2 -2
  34. package/dist/cjs/modules/logger/winston/transports/dgram.transport.js.map +1 -1
  35. package/dist/cjs/modules/network/http-request/fetcher/axios-fetcher.js +1 -1
  36. package/dist/cjs/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  37. package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.d.ts +17 -14
  38. package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.d.ts.map +1 -1
  39. package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.js +3 -0
  40. package/dist/cjs/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  41. package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.d.ts +13 -4
  42. package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.d.ts.map +1 -1
  43. package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.js +34 -11
  44. package/dist/cjs/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
  45. package/dist/cjs/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
  46. package/dist/cjs/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
  47. package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.d.ts.map +1 -1
  48. package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.js +7 -6
  49. package/dist/cjs/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
  50. package/dist/cjs/modules/network/udp-socket/network-udp-client.helper.js +1 -1
  51. package/dist/cjs/modules/network/udp-socket/network-udp-client.helper.js.map +1 -1
  52. package/dist/cjs/modules/network/utilities/query-string.d.ts +27 -2
  53. package/dist/cjs/modules/network/utilities/query-string.d.ts.map +1 -1
  54. package/dist/cjs/modules/network/utilities/query-string.js +34 -2
  55. package/dist/cjs/modules/network/utilities/query-string.js.map +1 -1
  56. package/dist/cjs/modules/network/utilities/url-safety/ingest.js +1 -1
  57. package/dist/cjs/modules/network/utilities/url-safety/ingest.js.map +1 -1
  58. package/dist/cjs/modules/network/utilities/url-safety/policy.js +1 -1
  59. package/dist/cjs/modules/network/utilities/url-safety/policy.js.map +1 -1
  60. package/dist/cjs/modules/pool/abstract.js +4 -4
  61. package/dist/cjs/modules/pool/abstract.js.map +1 -1
  62. package/dist/cjs/modules/queue/bullmq/helper.js +2 -2
  63. package/dist/cjs/modules/queue/bullmq/helper.js.map +1 -1
  64. package/dist/cjs/modules/queue/kafka/bundler/platformatic-require.plugin.js.map +1 -1
  65. package/dist/cjs/modules/queue/kafka/bundler/platformatic-wasm.plugin.js +1 -1
  66. package/dist/cjs/modules/queue/kafka/bundler/platformatic-wasm.plugin.js.map +1 -1
  67. package/dist/cjs/modules/queue/kafka/consumer.js +2 -2
  68. package/dist/cjs/modules/queue/kafka/consumer.js.map +1 -1
  69. package/dist/cjs/modules/queue/mqtt/helper.js +4 -4
  70. package/dist/cjs/modules/queue/mqtt/helper.js.map +1 -1
  71. package/dist/cjs/modules/redis/base/abstract.helper.js +4 -4
  72. package/dist/cjs/modules/redis/base/abstract.helper.js.map +1 -1
  73. package/dist/cjs/modules/redis/cluster/cluster.helper.js +1 -1
  74. package/dist/cjs/modules/redis/cluster/cluster.helper.js.map +1 -1
  75. package/dist/cjs/modules/redis/sentinel/sentinel.helper.js +1 -1
  76. package/dist/cjs/modules/redis/sentinel/sentinel.helper.js.map +1 -1
  77. package/dist/cjs/modules/secrets/base/abstract.helper.d.ts.map +1 -1
  78. package/dist/cjs/modules/secrets/base/abstract.helper.js +7 -3
  79. package/dist/cjs/modules/secrets/base/abstract.helper.js.map +1 -1
  80. package/dist/cjs/modules/secrets/hashicorp/hashicorp.helper.js +2 -2
  81. package/dist/cjs/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
  82. package/dist/cjs/modules/socket/socket-io/browser.d.ts +5 -0
  83. package/dist/cjs/modules/socket/socket-io/browser.d.ts.map +1 -0
  84. package/dist/cjs/modules/socket/socket-io/browser.js +21 -0
  85. package/dist/cjs/modules/socket/socket-io/browser.js.map +1 -0
  86. package/dist/cjs/modules/socket/socket-io/client/browser-helper.d.ts +61 -0
  87. package/dist/cjs/modules/socket/socket-io/client/browser-helper.d.ts.map +1 -0
  88. package/dist/cjs/modules/socket/socket-io/client/browser-helper.js +250 -0
  89. package/dist/cjs/modules/socket/socket-io/client/browser-helper.js.map +1 -0
  90. package/dist/cjs/modules/socket/socket-io/client/helper.d.ts +8 -51
  91. package/dist/cjs/modules/socket/socket-io/client/helper.d.ts.map +1 -1
  92. package/dist/cjs/modules/socket/socket-io/client/helper.js +12 -230
  93. package/dist/cjs/modules/socket/socket-io/client/helper.js.map +1 -1
  94. package/dist/cjs/modules/socket/socket-io/server/helper.js +5 -5
  95. package/dist/cjs/modules/socket/socket-io/server/helper.js.map +1 -1
  96. package/dist/cjs/modules/socket/websocket/server/delivery.js +2 -2
  97. package/dist/cjs/modules/socket/websocket/server/delivery.js.map +1 -1
  98. package/dist/cjs/modules/socket/websocket/server/helper.js +4 -4
  99. package/dist/cjs/modules/socket/websocket/server/helper.js.map +1 -1
  100. package/dist/cjs/modules/storage/base.js +3 -3
  101. package/dist/cjs/modules/storage/base.js.map +1 -1
  102. package/dist/cjs/modules/storage/bun-s3/helper.js +1 -1
  103. package/dist/cjs/modules/storage/bun-s3/helper.js.map +1 -1
  104. package/dist/cjs/modules/storage/bun-s3/utility.js +6 -6
  105. package/dist/cjs/modules/storage/bun-s3/utility.js.map +1 -1
  106. package/dist/cjs/modules/storage/common/errors.js +1 -1
  107. package/dist/cjs/modules/storage/common/errors.js.map +1 -1
  108. package/dist/cjs/modules/storage/minio/helper.js +4 -4
  109. package/dist/cjs/modules/storage/minio/helper.js.map +1 -1
  110. package/dist/cjs/modules/temporal/abstract.js +5 -5
  111. package/dist/cjs/modules/temporal/abstract.js.map +1 -1
  112. package/dist/cjs/modules/temporal/adapters/intl.d.ts.map +1 -1
  113. package/dist/cjs/modules/temporal/adapters/intl.js +3 -1
  114. package/dist/cjs/modules/temporal/adapters/intl.js.map +1 -1
  115. package/dist/cjs/modules/temporal/locale/locale.js +4 -4
  116. package/dist/cjs/modules/temporal/locale/locale.js.map +1 -1
  117. package/dist/cjs/modules/tree/builder.js +2 -2
  118. package/dist/cjs/modules/tree/builder.js.map +1 -1
  119. package/dist/cjs/modules/uid/opaque.js +2 -2
  120. package/dist/cjs/modules/uid/opaque.js.map +1 -1
  121. package/dist/cjs/modules/uid/uuid/v5.js +1 -1
  122. package/dist/cjs/modules/uid/uuid/v5.js.map +1 -1
  123. package/dist/cjs/modules/worker-thread/bus/base.js +4 -4
  124. package/dist/cjs/modules/worker-thread/bus/base.js.map +1 -1
  125. package/dist/cjs/modules/worker-thread/thread/base.js +2 -2
  126. package/dist/cjs/modules/worker-thread/thread/base.js.map +1 -1
  127. package/dist/cjs/modules/worker-thread/worker/base.js +4 -4
  128. package/dist/cjs/modules/worker-thread/worker/base.js.map +1 -1
  129. package/dist/cjs/utilities/parse.utility.js +4 -4
  130. package/dist/cjs/utilities/parse.utility.js.map +1 -1
  131. package/dist/cjs/utilities/promise.utility.js +1 -1
  132. package/dist/cjs/utilities/promise.utility.js.map +1 -1
  133. package/dist/cjs/utilities/request.utility.js +1 -1
  134. package/dist/cjs/utilities/request.utility.js.map +1 -1
  135. package/dist/cjs/utilities/sleep.utility.js +1 -1
  136. package/dist/cjs/utilities/sleep.utility.js.map +1 -1
  137. package/dist/esm/common/constants/duration.d.ts +4 -1
  138. package/dist/esm/common/constants/duration.d.ts.map +1 -1
  139. package/dist/esm/common/constants/duration.js +13 -8
  140. package/dist/esm/common/constants/duration.js.map +1 -1
  141. package/dist/esm/common/redact.js +1 -1
  142. package/dist/esm/common/redact.js.map +1 -1
  143. package/dist/esm/modules/base.js +1 -1
  144. package/dist/esm/modules/base.js.map +1 -1
  145. package/dist/esm/modules/crypto/algorithms/aes.algorithm.js +1 -1
  146. package/dist/esm/modules/crypto/algorithms/aes.algorithm.js.map +1 -1
  147. package/dist/esm/modules/env/app-env.d.ts.map +1 -1
  148. package/dist/esm/modules/env/app-env.js +1 -1
  149. package/dist/esm/modules/env/app-env.js.map +1 -1
  150. package/dist/esm/modules/logger/common/constants.js +1 -1
  151. package/dist/esm/modules/logger/common/constants.js.map +1 -1
  152. package/dist/esm/modules/logger/factory.js +1 -1
  153. package/dist/esm/modules/logger/factory.js.map +1 -1
  154. package/dist/esm/modules/logger/formatting/deep-splat.js +1 -1
  155. package/dist/esm/modules/logger/formatting/deep-splat.js.map +1 -1
  156. package/dist/esm/modules/logger/formatting/error-prettier.js +4 -4
  157. package/dist/esm/modules/logger/formatting/error-prettier.js.map +1 -1
  158. package/dist/esm/modules/logger/hf/flusher.js +3 -3
  159. package/dist/esm/modules/logger/hf/flusher.js.map +1 -1
  160. package/dist/esm/modules/logger/hf/logger.d.ts.map +1 -1
  161. package/dist/esm/modules/logger/hf/logger.js +3 -1
  162. package/dist/esm/modules/logger/hf/logger.js.map +1 -1
  163. package/dist/esm/modules/logger/resolver.js +3 -3
  164. package/dist/esm/modules/logger/resolver.js.map +1 -1
  165. package/dist/esm/modules/logger/winston/formatters/deep-splat.js +1 -1
  166. package/dist/esm/modules/logger/winston/formatters/deep-splat.js.map +1 -1
  167. package/dist/esm/modules/logger/winston/logger-factory.js +1 -1
  168. package/dist/esm/modules/logger/winston/logger-factory.js.map +1 -1
  169. package/dist/esm/modules/logger/winston/transports/dgram.transport.js +2 -2
  170. package/dist/esm/modules/logger/winston/transports/dgram.transport.js.map +1 -1
  171. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js +1 -1
  172. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  173. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +17 -14
  174. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts.map +1 -1
  175. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js +3 -0
  176. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  177. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +13 -4
  178. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts.map +1 -1
  179. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +36 -13
  180. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
  181. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
  182. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
  183. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.d.ts.map +1 -1
  184. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js +7 -6
  185. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
  186. package/dist/esm/modules/network/udp-socket/network-udp-client.helper.js +1 -1
  187. package/dist/esm/modules/network/udp-socket/network-udp-client.helper.js.map +1 -1
  188. package/dist/esm/modules/network/utilities/query-string.d.ts +27 -2
  189. package/dist/esm/modules/network/utilities/query-string.d.ts.map +1 -1
  190. package/dist/esm/modules/network/utilities/query-string.js +31 -1
  191. package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
  192. package/dist/esm/modules/network/utilities/url-safety/ingest.js +1 -1
  193. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +1 -1
  194. package/dist/esm/modules/network/utilities/url-safety/policy.js +1 -1
  195. package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
  196. package/dist/esm/modules/pool/abstract.js +4 -4
  197. package/dist/esm/modules/pool/abstract.js.map +1 -1
  198. package/dist/esm/modules/queue/bullmq/helper.js +2 -2
  199. package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
  200. package/dist/esm/modules/queue/kafka/bundler/platformatic-require.plugin.js.map +1 -1
  201. package/dist/esm/modules/queue/kafka/bundler/platformatic-wasm.plugin.js +1 -1
  202. package/dist/esm/modules/queue/kafka/bundler/platformatic-wasm.plugin.js.map +1 -1
  203. package/dist/esm/modules/queue/kafka/consumer.js +2 -2
  204. package/dist/esm/modules/queue/kafka/consumer.js.map +1 -1
  205. package/dist/esm/modules/queue/mqtt/helper.js +4 -4
  206. package/dist/esm/modules/queue/mqtt/helper.js.map +1 -1
  207. package/dist/esm/modules/redis/base/abstract.helper.js +4 -4
  208. package/dist/esm/modules/redis/base/abstract.helper.js.map +1 -1
  209. package/dist/esm/modules/redis/cluster/cluster.helper.js +1 -1
  210. package/dist/esm/modules/redis/cluster/cluster.helper.js.map +1 -1
  211. package/dist/esm/modules/redis/sentinel/sentinel.helper.js +1 -1
  212. package/dist/esm/modules/redis/sentinel/sentinel.helper.js.map +1 -1
  213. package/dist/esm/modules/secrets/base/abstract.helper.d.ts.map +1 -1
  214. package/dist/esm/modules/secrets/base/abstract.helper.js +7 -3
  215. package/dist/esm/modules/secrets/base/abstract.helper.js.map +1 -1
  216. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js +2 -2
  217. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
  218. package/dist/esm/modules/socket/socket-io/browser.d.ts +5 -0
  219. package/dist/esm/modules/socket/socket-io/browser.d.ts.map +1 -0
  220. package/dist/esm/modules/socket/socket-io/browser.js +5 -0
  221. package/dist/esm/modules/socket/socket-io/browser.js.map +1 -0
  222. package/dist/esm/modules/socket/socket-io/client/browser-helper.d.ts +61 -0
  223. package/dist/esm/modules/socket/socket-io/client/browser-helper.d.ts.map +1 -0
  224. package/dist/esm/modules/socket/socket-io/client/browser-helper.js +246 -0
  225. package/dist/esm/modules/socket/socket-io/client/browser-helper.js.map +1 -0
  226. package/dist/esm/modules/socket/socket-io/client/helper.d.ts +8 -51
  227. package/dist/esm/modules/socket/socket-io/client/helper.d.ts.map +1 -1
  228. package/dist/esm/modules/socket/socket-io/client/helper.js +12 -230
  229. package/dist/esm/modules/socket/socket-io/client/helper.js.map +1 -1
  230. package/dist/esm/modules/socket/socket-io/server/helper.js +5 -5
  231. package/dist/esm/modules/socket/socket-io/server/helper.js.map +1 -1
  232. package/dist/esm/modules/socket/websocket/server/delivery.js +2 -2
  233. package/dist/esm/modules/socket/websocket/server/delivery.js.map +1 -1
  234. package/dist/esm/modules/socket/websocket/server/helper.js +4 -4
  235. package/dist/esm/modules/socket/websocket/server/helper.js.map +1 -1
  236. package/dist/esm/modules/storage/base.js +3 -3
  237. package/dist/esm/modules/storage/base.js.map +1 -1
  238. package/dist/esm/modules/storage/bun-s3/helper.js +1 -1
  239. package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
  240. package/dist/esm/modules/storage/bun-s3/utility.js +6 -6
  241. package/dist/esm/modules/storage/bun-s3/utility.js.map +1 -1
  242. package/dist/esm/modules/storage/common/errors.js +1 -1
  243. package/dist/esm/modules/storage/common/errors.js.map +1 -1
  244. package/dist/esm/modules/storage/minio/helper.js +4 -4
  245. package/dist/esm/modules/storage/minio/helper.js.map +1 -1
  246. package/dist/esm/modules/temporal/abstract.js +5 -5
  247. package/dist/esm/modules/temporal/abstract.js.map +1 -1
  248. package/dist/esm/modules/temporal/adapters/intl.d.ts.map +1 -1
  249. package/dist/esm/modules/temporal/adapters/intl.js +3 -1
  250. package/dist/esm/modules/temporal/adapters/intl.js.map +1 -1
  251. package/dist/esm/modules/temporal/locale/locale.js +4 -4
  252. package/dist/esm/modules/temporal/locale/locale.js.map +1 -1
  253. package/dist/esm/modules/tree/builder.js +2 -2
  254. package/dist/esm/modules/tree/builder.js.map +1 -1
  255. package/dist/esm/modules/uid/opaque.js +2 -2
  256. package/dist/esm/modules/uid/opaque.js.map +1 -1
  257. package/dist/esm/modules/uid/uuid/v5.js +1 -1
  258. package/dist/esm/modules/uid/uuid/v5.js.map +1 -1
  259. package/dist/esm/modules/worker-thread/bus/base.js +4 -4
  260. package/dist/esm/modules/worker-thread/bus/base.js.map +1 -1
  261. package/dist/esm/modules/worker-thread/thread/base.js +2 -2
  262. package/dist/esm/modules/worker-thread/thread/base.js.map +1 -1
  263. package/dist/esm/modules/worker-thread/worker/base.js +4 -4
  264. package/dist/esm/modules/worker-thread/worker/base.js.map +1 -1
  265. package/dist/esm/utilities/parse.utility.js +4 -4
  266. package/dist/esm/utilities/parse.utility.js.map +1 -1
  267. package/dist/esm/utilities/promise.utility.js +1 -1
  268. package/dist/esm/utilities/promise.utility.js.map +1 -1
  269. package/dist/esm/utilities/request.utility.js +1 -1
  270. package/dist/esm/utilities/request.utility.js.map +1 -1
  271. package/dist/esm/utilities/sleep.utility.js +1 -1
  272. package/dist/esm/utilities/sleep.utility.js.map +1 -1
  273. package/package.json +10 -4
@@ -13,11 +13,11 @@ class BaseWorkerThreadHelper extends abstract_1.AbstractWorkerThreadHelper {
13
13
  message: '[BaseWorker] Cannot start worker in MAIN_THREAD',
14
14
  });
15
15
  }
16
- this.buses = {};
16
+ this.buses = Object.create(null);
17
17
  }
18
18
  bindWorkerBus(opts) {
19
19
  if (!this.buses) {
20
- this.buses = {};
20
+ this.buses = Object.create(null);
21
21
  }
22
22
  const { key, bus } = opts;
23
23
  if (this.buses[key]) {
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/thread/base.ts"],"names":[],"mappings":";;;AAAA,2CAA2C;AAC3C,6DAAmD;AAEnD,yCAAwD;AAExD,MAAa,sBAAuB,SAAQ,qCAA0B;IACpE,YAAY,IAAuB;QACjC,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QACvB,KAAK,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC;QAEpC,IAAI,kCAAY,EAAE,CAAC;YACjB,MAAM,IAAA,gBAAQ,EAAC;gBACb,OAAO,EAAE,iDAAiD;aAC3D,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;IAClB,CAAC;IAED,aAAa,CAAS,IAA8C;Q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ClC,CAAC;CACF;AArDD,wDAqDC","sourcesContent":["import { getError } from '@/modules/error';\nimport { isMainThread } from 'node:worker_threads';\nimport { type IWorkerBus } from '../common';\nimport { AbstractWorkerThreadHelper } from './abstract';\n\nexport class BaseWorkerThreadHelper extends AbstractWorkerThreadHelper {\n constructor(opts: { scope: string }) {\n const { scope } = opts;\n super({ scope, identifier: scope });\n\n if (isMainThread) {\n throw getError({\n message: '[BaseWorker] Cannot start worker in MAIN_THREAD',\n });\n }\n\n this.buses = {};\n }\n\n bindWorkerBus<IC, IP>(opts: { key: string; bus: IWorkerBus<IC, IP> }) {\n if (!this.buses) {\n this.buses = {};\n }\n\n const { key, bus } = opts;\n if (this.buses[key]) {\n this.logger.for(this.bindWorkerBus.name).warn('Worker Bus existed | key: %s', key);\n return;\n }\n\n this.buses[key] = bus;\n }\n\n unbindWorkerBus(opts: { key: string }) {\n if (!this.buses) {\n return;\n }\n\n const { key } = opts;\n if (!(key in this.buses)) {\n this.logger.for(this.unbindWorkerBus.name).warn('Worker Bus not existed | key: %s', key);\n return;\n }\n\n this.buses[key]?.port?.removeAllListeners();\n delete this.buses[key];\n }\n\n getWorkerBus<IC, IP>(opts: { key: string }) {\n const rs = this.buses[opts.key];\n if (!rs) {\n throw getError({\n message: `[getWorkerBus] Not found worker bus | key: ${opts.key}`,\n });\n }\n\n return rs as IWorkerBus<IC, IP>;\n }\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/thread/base.ts"],"names":[],"mappings":";;;AAAA,2CAA2C;AAC3C,6DAAmD;AAEnD,yCAAwD;AAExD,MAAa,sBAAuB,SAAQ,qCAA0B;IACpE,YAAY,IAAuB;QACjC,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QACvB,KAAK,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC;QAEpC,IAAI,kCAAY,EAAE,CAAC;YACjB,MAAM,IAAA,gBAAQ,E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I,CAAC,GAAG,CAAC,CAAC;QAChC,IAAI,CAAC,EAAE,EAAE,CAAC;YACR,MAAM,IAAA,gBAAQ,EAAC;gBACb,OAAO,EAAE,8CAA8C,IAAI,CAAC,GAAG,EAAE;aAClE,CAAC,CAAC;QACL,CAAC;QAED,OAAO,EAAwB,CAAC;IAClC,CAAC;CACF;AArDD,wDAqDC","sourcesContent":["import { getError } from '@/modules/error';\nimport { isMainThread } from 'node:worker_threads';\nimport { type IWorkerBus } from '../common';\nimport { AbstractWorkerThreadHelper } from './abstract';\n\nexport class BaseWorkerThreadHelper extends AbstractWorkerThreadHelper {\n constructor(opts: { scope: string }) {\n const { scope } = opts;\n super({ scope, identifier: scope });\n\n if (isMainThread) {\n throw getError({\n message: '[BaseWorker] Cannot start worker in MAIN_THREAD',\n });\n }\n\n this.buses = Object.create(null);\n }\n\n bindWorkerBus<IC, IP>(opts: { key: string; bus: IWorkerBus<IC, IP> }) {\n if (!this.buses) {\n this.buses = Object.create(null);\n }\n\n const { key, bus } = opts;\n if (this.buses[key]) {\n this.logger.for(this.bindWorkerBus.name).warn('Worker Bus existed | key: %s', key);\n return;\n }\n\n this.buses[key] = bus;\n }\n\n unbindWorkerBus(opts: { key: string }) {\n if (!this.buses) {\n return;\n }\n\n const { key } = opts;\n if (!(key in this.buses)) {\n this.logger.for(this.unbindWorkerBus.name).warn('Worker Bus not existed | key: %s', key);\n return;\n }\n\n this.buses[key]?.port?.removeAllListeners();\n delete this.buses[key];\n }\n\n getWorkerBus<IC, IP>(opts: { key: string }) {\n const rs = this.buses[opts.key];\n if (!rs) {\n throw getError({\n message: `[getWorkerBus] Not found worker bus | key: ${opts.key}`,\n });\n }\n\n return rs as IWorkerBus<IC, IP>;\n }\n}\n"]}
@@ -79,19 +79,19 @@ class BaseWorkerHelper extends abstract_1.AbstractWorkerHelper {
79
79
  this.worker.on('online', () => {
80
80
  this.invokeHook({ scope: this.binding.name, execution: () => this.onOnline() });
81
81
  });
82
- this.worker.on('exit', code => {
82
+ this.worker.on('exit', (code) => {
83
83
  this.invokeHook({ scope: this.binding.name, execution: () => this.onExit({ code }) });
84
84
  });
85
- this.worker.on('error', error => {
85
+ this.worker.on('error', (error) => {
86
86
  this.invokeHook({
87
87
  scope: this.binding.name,
88
88
  execution: () => this.onError({ error: (0, promise_utility_1.toError)(error) }),
89
89
  });
90
90
  });
91
- this.worker.on('message', message => {
91
+ this.worker.on('message', (message) => {
92
92
  this.invokeHook({ scope: this.binding.name, execution: () => this.onMessage({ message }) });
93
93
  });
94
- this.worker.on('messageerror', error => {
94
+ this.worker.on('messageerror', (error) => {
95
95
  this.invokeHook({
96
96
  scope: this.binding.name,
97
97
  execution: () => this.onMessageError({ error }),
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/worker/base.ts"],"names":[],"mappings":";;;AAAA,iEAAqE;AACrE,6DAAiE;AAGjE,2CAA2C;AAE3C,yCAAkD;AAElD,MAAa,gBAA8B,SAAQ,+BAAiC;IAKlF,YAAY,IAQX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,gBAAgB,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QACrE,IAAI,CAAC,MAAM,GAAG,IAAI,4BAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QAClD,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC;QAExC,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED,0LAA0L;IAChL,UAAU,CAAC,IAA8D;QACjF,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QAElC,IAAI,CAAC;YACH,IAAA,+BAAa,EAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;QACxE,CAAC;QAAC,OAAO,KAAK,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AAC;QAC9F,CAAC,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,cAAc,EAAE,KAAK,CAAC,EAAE;YACrC,IAAI,CAAC,UAAU,CAAC;gBACd,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI;gBACxB,SAAS,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,cAAc,CAAC,EAAE,KAAK,EAAE,CAAC;aAChD,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA3HD,4CA2HC","sourcesContent":["import { toError, voidExecution } from '@/utilities/promise.utility';\nimport { Worker, type WorkerOptions } from 'node:worker_threads';\n\nimport { type ValueOrPromise } from '@/common/types';\nimport { getError } from '@/modules/error';\nimport { type IWorker } from '../common';\nimport { AbstractWorkerHelper } from './abstract';\n\nexport class BaseWorkerHelper<MessageType> extends AbstractWorkerHelper<MessageType> {\n protected eventHandlers?: Partial<\n Pick<IWorker<MessageType>, 'onOnline' | 'onExit' | 'onError' | 'onMessage' | 'onMessageError'>\n >;\n\n constructor(opts: {\n scope?: string;\n identifier: string;\n path: string | URL;\n options: WorkerOptions;\n eventHandlers?: Partial<\n Pick<IWorker<MessageType>, 'onOnline' | 'onExit' | 'onError' | 'onMessage' | 'onMessageError'>\n >;\n }) {\n super({ scope: BaseWorkerHelper.name, identifier: opts.identifier });\n this.worker = new Worker(opts.path, opts.options);\n this.eventHandlers = opts.eventHandlers;\n\n this.binding();\n }\n\n /** User handlers run inside worker listeners; a sync throw there is uncaught and kills the process, so wrap it - voidExecution alone can't catch a throw evaluated before it's called. */\n protected invokeHook(opts: { scope: string; execution: () => ValueOrPromise<void> }) {\n const { scope, execution } = opts;\n\n try {\n voidExecution({ logger: this.logger, scope, execution: execution() });\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n override onOnline(): ValueOrPromise<void> {\n if (this.eventHandlers?.onOnline) {\n this.invokeHook({\n scope: this.onOnline.name,\n execution: () => this.eventHandlers?.onOnline?.(),\n });\n return;\n }\n\n this.logger.for(this.onOnline.name).info('Worker ONLINE');\n }\n\n override onExit(opts: { code: string | number }): ValueOrPromise<void> {\n if (this.eventHandlers?.onExit) {\n this.invokeHook({\n scope: this.onExit.name,\n execution: () => this.eventHandlers?.onExit?.({ code: opts.code }),\n });\n return;\n }\n\n this.logger.for(this.onExit.name).warn('Worker EXIT | Code: %s', opts.code);\n }\n\n override onError(opts: { error: Error }): ValueOrPromise<void> {\n if (this.eventHandlers?.onError) {\n this.invokeHook({\n scope: this.onError.name,\n execution: () => this.eventHandlers?.onError?.({ error: opts.error }),\n });\n return;\n }\n\n this.logger.for(this.onError.name).error('Worker ERROR | Error: %s', opts.error);\n }\n\n override onMessage(opts: { message: MessageType }): ValueOrPromise<void> {\n if (this.eventHandlers?.onMessage) {\n this.invokeHook({\n scope: this.onMessage.name,\n execution: () => this.eventHandlers?.onMessage?.({ message: opts.message }),\n });\n return;\n }\n\n this.logger.for(this.onMessage.name).error('Worker MESSAGE | message: %j', opts.message);\n }\n\n override onMessageError(opts: { error: Error }): ValueOrPromise<void> {\n if (this.eventHandlers?.onMessageError) {\n this.invokeHook({\n scope: this.onMessageError.name,\n execution: () => this.eventHandlers?.onMessageError?.({ error: opts.error }),\n });\n return;\n }\n\n this.logger.for(this.onMessageError.name).error('Worker MESSAGE_ERROR | Error: %s', opts.error);\n }\n\n binding() {\n if (!this.worker) {\n throw getError({ message: '[binding] Invalid worker instance to bind event handlers' });\n }\n\n this.worker.on('online', () => {\n this.invokeHook({ scope: this.binding.name, execution: () => this.onOnline() });\n });\n\n this.worker.on('exit', code => {\n this.invokeHook({ scope: this.binding.name, execution: () => this.onExit({ code }) });\n });\n\n this.worker.on('error', error => {\n this.invokeHook({\n scope: this.binding.name,\n execution: () => this.onError({ error: toError(error) }),\n });\n });\n\n this.worker.on('message', message => {\n this.invokeHook({ scope: this.binding.name, execution: () => this.onMessage({ message }) });\n });\n\n this.worker.on('messageerror', error => {\n this.invokeHook({\n scope: this.binding.name,\n execution: () => this.onMessageError({ error }),\n });\n });\n }\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/worker/base.ts"],"names":[],"mappings":";;;AAAA,iEAAqE;AACrE,6DAAiE;AAGjE,2CAA2C;AAE3C,yCAAkD;AAElD,MAAa,gBAA8B,SAAQ,+BAAiC;IAKlF,YAAY,IAQX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,gBAAgB,CAAC,IAAI,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QACrE,IAAI,CAAC,MAAM,GAAG,IAAI,4BAAM,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QAClD,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC;QAExC,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED,0LAA0L;IAChL,UAAU,CAAC,IAA8D;QACjF,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;QAElC,IAAI,CAAC;YACH,IAAA,+BAAa,EAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;QACxE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,mCAAmC,EAAE,KAAK,CAAC,CAAC;QAC3E,CAAC;IACH,CAAC;IAEQ,QAAQ;QACf,IAAI,IAAI,CAAC,aAAa,EAAE,QAAQ,EAAE,CAAC;YACjC,IAAI,CAAC,UAAU,CAAC;gBACd,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI;gBACzB,SAAS,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,aAAa,EAAE,QAAQ,EAAE,EAAE;aAClD,CAA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idExecution } from '@/utilities/promise.utility';\nimport { Worker, type WorkerOptions } from 'node:worker_threads';\n\nimport { type ValueOrPromise } from '@/common/types';\nimport { getError } from '@/modules/error';\nimport { type IWorker } from '../common';\nimport { AbstractWorkerHelper } from './abstract';\n\nexport class BaseWorkerHelper<MessageType> extends AbstractWorkerHelper<MessageType> {\n protected eventHandlers?: Partial<\n Pick<IWorker<MessageType>, 'onOnline' | 'onExit' | 'onError' | 'onMessage' | 'onMessageError'>\n >;\n\n constructor(opts: {\n scope?: string;\n identifier: string;\n path: string | URL;\n options: WorkerOptions;\n eventHandlers?: Partial<\n Pick<IWorker<MessageType>, 'onOnline' | 'onExit' | 'onError' | 'onMessage' | 'onMessageError'>\n >;\n }) {\n super({ scope: BaseWorkerHelper.name, identifier: opts.identifier });\n this.worker = new Worker(opts.path, opts.options);\n this.eventHandlers = opts.eventHandlers;\n\n this.binding();\n }\n\n /** User handlers run inside worker listeners; a sync throw there is uncaught and kills the process, so wrap it - voidExecution alone can't catch a throw evaluated before it's called. */\n protected invokeHook(opts: { scope: string; execution: () => ValueOrPromise<void> }) {\n const { scope, execution } = opts;\n\n try {\n voidExecution({ logger: this.logger, scope, execution: execution() });\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n override onOnline(): ValueOrPromise<void> {\n if (this.eventHandlers?.onOnline) {\n this.invokeHook({\n scope: this.onOnline.name,\n execution: () => this.eventHandlers?.onOnline?.(),\n });\n return;\n }\n\n this.logger.for(this.onOnline.name).info('Worker ONLINE');\n }\n\n override onExit(opts: { code: string | number }): ValueOrPromise<void> {\n if (this.eventHandlers?.onExit) {\n this.invokeHook({\n scope: this.onExit.name,\n execution: () => this.eventHandlers?.onExit?.({ code: opts.code }),\n });\n return;\n }\n\n this.logger.for(this.onExit.name).warn('Worker EXIT | Code: %s', opts.code);\n }\n\n override onError(opts: { error: Error }): ValueOrPromise<void> {\n if (this.eventHandlers?.onError) {\n this.invokeHook({\n scope: this.onError.name,\n execution: () => this.eventHandlers?.onError?.({ error: opts.error }),\n });\n return;\n }\n\n this.logger.for(this.onError.name).error('Worker ERROR | Error: %s', opts.error);\n }\n\n override onMessage(opts: { message: MessageType }): ValueOrPromise<void> {\n if (this.eventHandlers?.onMessage) {\n this.invokeHook({\n scope: this.onMessage.name,\n execution: () => this.eventHandlers?.onMessage?.({ message: opts.message }),\n });\n return;\n }\n\n this.logger.for(this.onMessage.name).error('Worker MESSAGE | message: %j', opts.message);\n }\n\n override onMessageError(opts: { error: Error }): ValueOrPromise<void> {\n if (this.eventHandlers?.onMessageError) {\n this.invokeHook({\n scope: this.onMessageError.name,\n execution: () => this.eventHandlers?.onMessageError?.({ error: opts.error }),\n });\n return;\n }\n\n this.logger.for(this.onMessageError.name).error('Worker MESSAGE_ERROR | Error: %s', opts.error);\n }\n\n binding() {\n if (!this.worker) {\n throw getError({ message: '[binding] Invalid worker instance to bind event handlers' });\n }\n\n this.worker.on('online', () => {\n this.invokeHook({ scope: this.binding.name, execution: () => this.onOnline() });\n });\n\n this.worker.on('exit', (code) => {\n this.invokeHook({ scope: this.binding.name, execution: () => this.onExit({ code }) });\n });\n\n this.worker.on('error', (error) => {\n this.invokeHook({\n scope: this.binding.name,\n execution: () => this.onError({ error: toError(error) }),\n });\n });\n\n this.worker.on('message', (message) => {\n this.invokeHook({ scope: this.binding.name, execution: () => this.onMessage({ message }) });\n });\n\n this.worker.on('messageerror', (error) => {\n this.invokeHook({\n scope: this.binding.name,\n execution: () => this.onMessageError({ error }),\n });\n });\n }\n}\n"]}
@@ -32,7 +32,7 @@ exports.toCamel = toCamel;
32
32
  /** Arrays stay arrays - mapping one through the object branch would turn it into an index-keyed object - but their object elements still need their keys camelized. Dates are opaque values. */
33
33
  const camelizeValue = (value) => {
34
34
  if (Array.isArray(value)) {
35
- return value.map(element => camelizeValue(element));
35
+ return value.map((element) => camelizeValue(element));
36
36
  }
37
37
  if (!value || typeof value !== 'object' || value instanceof Date) {
38
38
  return value;
@@ -122,7 +122,7 @@ const parseArrayToMapWithKey = (arr, keyMap) => {
122
122
  if (!arr.length) {
123
123
  return resultMap;
124
124
  }
125
- arr.forEach(element => {
125
+ arr.forEach((element) => {
126
126
  if (!(keyMap in element)) {
127
127
  throw (0, error_1.getError)({
128
128
  message: 'Invalid keyMap',
@@ -140,8 +140,8 @@ const toDelimitedArray = (input, separator = ',') => {
140
140
  }
141
141
  return String(input)
142
142
  .split(separator)
143
- .map(entry => entry.trim())
144
- .filter(entry => entry.length > 0);
143
+ .map((entry) => entry.trim())
144
+ .filter((entry) => entry.length > 0);
145
145
  };
146
146
  exports.toDelimitedArray = toDelimitedArray;
147
147
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"parse.utility.js","sourceRoot":"","sources":["../../../src/utilities/parse.utility.ts"],"names":[],"mappings":";;;AAAA,2CAA2C;AAE3C;;;;;;;;GAQG;AACH,MAAM,KAAK,GAAG,CAAC,IAA2C,EAAU,EAAE;IACpE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,CAAC,EAAE,GAAG,IAAI,CAAC;IAEtC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,SAAS,KAAK,CAAC,EAAE,CAAC;QAC/C,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,MAAM,CAAC,QAAQ,EAAE,QAAQ,CAAC,GAAG,GAAG,KAAK,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,GAAG,SAAS,EAAE,CAAC,CAAC,CAAC;IAClF,MAAM,CAAC,eAAe,EAAE,eAAe,CAAC,GAAG,GAAG,OAAO,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAEpE,OAAO,MAAM,CAAC,GAAG,eAAe,IAAI,MAAM,C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S,CAAC,CAAC,CAAC,OAAO,CAAC;AAC7E,CAAC,CAAC;AAHW,QAAA,gBAAgB,oBAG3B;AAEF,+EAA+E;AACxE,MAAM,SAAS,GAAG,CAAC,KAAc,EAAU,EAAE;IAClD,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;QAClB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC;AAC9B,CAAC,CAAC;AANW,QAAA,SAAS,aAMpB","sourcesContent":["import { getError } from '@/modules/error';\n\n/**\n * Rounds at a decimal precision, shifting the exponent rather than multiplying: `1.005` at 2 is\n * `1.01` here, where `Math.round(1.005 * 100) / 100` gives `1`.\n *\n * Hand-written to keep lodash out of a browser bundle. One deliberate difference from `lodash/round`:\n * a result of negative zero is normalised to `0`. They compare equal, stringify the same and\n * serialise the same, so nothing downstream can tell - checked across 114 value/precision pairs, and\n * the sign of zero was the only disagreement.\n */\nconst round = (opts: { value: number; precision?: number }): number => {\n const { value, precision = 0 } = opts;\n\n if (!Number.isFinite(value) || precision === 0) {\n return Math.round(value) + 0;\n }\n\n const [mantissa, exponent] = `${value}e`.split('e');\n const shifted = Math.round(Number(`${mantissa}e${Number(exponent) + precision}`));\n const [shiftedMantissa, shiftedExponent] = `${shifted}e`.split('e');\n\n return Number(`${shiftedMantissa}e${Number(shiftedExponent) - precision}`) + 0;\n};\n\nexport const getUID = () => Math.random().toString(36).slice(2).toUpperCase();\n\nexport const toCamel = (s: string) => {\n return s.replace(/([-_][a-z])/gi, (sub: string) => {\n return sub.toUpperCase().replace('-', '').replace('_', '');\n });\n};\n\n/** Arrays stay arrays - mapping one through the object branch would turn it into an index-keyed object - but their object elements still need their keys camelized. Dates are opaque values. */\nconst camelizeValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map(element => camelizeValue(element));\n }\n\n if (!value || typeof value !== 'object' || value instanceof Date) {\n return value;\n }\n\n const camelized: any = {};\n const valueKeys = Object.keys(value);\n for (const key of valueKeys) {\n camelized[toCamel(key)] = camelizeValue((value as Record<string, unknown>)[key]);\n }\n\n return camelized;\n};\n\nexport const keysToCamel = (object: object) => {\n const n: any = {};\n const keys = Object.keys(object);\n\n for (const key of keys) {\n n[toCamel(key)] = camelizeValue((object as Record<string, unknown>)[key]);\n }\n\n return n;\n};\n\nexport const isInt = (n: any) => {\n if (isNaN(n)) {\n return false;\n }\n\n return Number.isInteger(n) || Math.floor(Number(n)) === n || Number(n) % 1 === 0;\n};\n\nexport const isFloat = (input: any) => {\n if (isNaN(input)) {\n return false;\n }\n\n return Number(input) === input || Number(input) % 1 !== 0;\n};\n\n/**\n * Parses an integer, TOTAL by design: it always answers a number, and answers `0` for anything it\n * cannot parse - `undefined`, `''`, `'abc'`.\n *\n * That makes `int(value) ?? fallback` dead code, because the left side is never nullish. The\n * fallback belongs INSIDE the call, and for an environment read it belongs in the read itself:\n *\n * ```ts\n * int(applicationEnvironment.get(KEY, { defaultValue: '6379' })) // correct\n * int(applicationEnvironment.get(KEY)) ?? 6379 // always 0 when KEY is unset\n * ```\n *\n * The second form is silent: a missing port reads `0` and a missing retry budget reads `0`, which\n * through `AbstractRedisHelper.buildRetryStrategy` means \"give up after the first failure\".\n */\nexport const int = (input: any) => {\n if (!input) {\n return 0;\n }\n\n const normalized = input?.toString()?.replace(/,/g, '');\n if (isNaN(normalized)) {\n return 0;\n }\n\n const parsed = Number.parseInt(normalized, 10);\n return Number.isNaN(parsed) ? 0 : parsed;\n};\n\nexport const float = (input: any, digit = 2) => {\n if (!input) {\n return 0;\n }\n\n const normalized = input?.toString()?.replace(/,/g, '');\n if (isNaN(normalized)) {\n return 0;\n }\n\n const parsed = round({ value: Number.parseFloat(normalized), precision: digit });\n return Number.isNaN(parsed) ? 0 : parsed;\n};\n\nexport const toBoolean = (input: any): boolean => {\n return (\n input !== '' &&\n input !== 'false' &&\n input !== '0' &&\n input !== false &&\n input !== 0 &&\n input !== null &&\n input !== undefined\n );\n};\n\n/** Converts an array to a Map keyed by `keyMap`. Last element wins on duplicate keys. */\nexport const parseArrayToMapWithKey = <T extends Record<K, PropertyKey>, K extends keyof T>(\n arr: T[],\n keyMap: K,\n): Map<T[K], T> => {\n const resultMap = new Map<T[K], T>();\n\n if (!arr.length) {\n return resultMap;\n }\n\n arr.forEach(element => {\n if (!(keyMap in element)) {\n throw getError({\n message: 'Invalid keyMap',\n });\n }\n resultMap.set(element[keyMap], element);\n });\n\n return resultMap;\n};\n\n/** Splits a delimited string into trimmed, non-empty entries - the transform for list-shaped env values (e.g. `applicationEnvironment.get(KEY, { transform: toDelimitedArray })`). */\nexport const toDelimitedArray = (input: unknown, separator = ','): string[] => {\n if (input == null) {\n return [];\n }\n\n return String(input)\n .split(separator)\n .map(entry => entry.trim())\n .filter(entry => entry.length > 0);\n};\n\n/**\n * A trimmed value, or `undefined` when the input is absent or carries nothing but whitespace.\n *\n * Written for environment reads. `KEY=` in a deployment file is a pipeline that forgot to export the\n * value, but `process.env.KEY` answers `''` for it, and `''` walks straight past `??`:\n *\n * ```ts\n * process.env.APP_ENV_LOGGER_FORMAT ?? 'text' // '' when the line is blank\n * blankToUndefined(process.env.APP_ENV_LOGGER_FORMAT) ?? 'text' // 'text'\n * ```\n *\n * Reach for this rather than `||`, which reads `'0'` as blank as well.\n */\nexport const blankToUndefined = (input: string | undefined): string | undefined => {\n const trimmed = input?.trim();\n return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;\n};\n\n/** Trims a possibly-undefined env value to a clean string ('' when absent). */\nexport const toTrimmed = (input: unknown): string => {\n if (input == null) {\n return '';\n }\n\n return String(input).trim();\n};\n"]}
1
+ {"version":3,"file":"parse.utility.js","sourceRoot":"","sources":["../../../src/utilities/parse.utility.ts"],"names":[],"mappings":";;;AAAA,2CAA2C;AAE3C;;;;;;;;GAQG;AACH,MAAM,KAAK,GAAG,CAAC,IAA2C,EAAU,EAAE;IACpE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,CAAC,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c,EAAE,SAAS,GAAG,GAAG,EAAY,EAAE;IAC5E,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;QAClB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,MAAM,CAAC,KAAK,CAAC;SACjB,KAAK,CAAC,SAAS,CAAC;SAChB,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;SAC5B,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACzC,CAAC,CAAC;AATW,QAAA,gBAAgB,oBAS3B;AAEF;;;;;;;;;;;;GAYG;AACI,MAAM,gBAAgB,GAAG,CAAC,KAAyB,EAAsB,EAAE;IAChF,MAAM,OAAO,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC;IAC9B,OAAO,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC;AAC7E,CAAC,CAAC;AAHW,QAAA,gBAAgB,oBAG3B;AAEF,+EAA+E;AACxE,MAAM,SAAS,GAAG,CAAC,KAAc,EAAU,EAAE;IAClD,IAAI,KAAK,IAAI,IAAI,EAAE,CAAC;QAClB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC;AAC9B,CAAC,CAAC;AANW,QAAA,SAAS,aAMpB","sourcesContent":["import { getError } from '@/modules/error';\n\n/**\n * Rounds at a decimal precision, shifting the exponent rather than multiplying: `1.005` at 2 is\n * `1.01` here, where `Math.round(1.005 * 100) / 100` gives `1`.\n *\n * Hand-written to keep lodash out of a browser bundle. One deliberate difference from `lodash/round`:\n * a result of negative zero is normalised to `0`. They compare equal, stringify the same and\n * serialise the same, so nothing downstream can tell - checked across 114 value/precision pairs, and\n * the sign of zero was the only disagreement.\n */\nconst round = (opts: { value: number; precision?: number }): number => {\n const { value, precision = 0 } = opts;\n\n if (!Number.isFinite(value) || precision === 0) {\n return Math.round(value) + 0;\n }\n\n const [mantissa, exponent] = `${value}e`.split('e');\n const shifted = Math.round(Number(`${mantissa}e${Number(exponent) + precision}`));\n const [shiftedMantissa, shiftedExponent] = `${shifted}e`.split('e');\n\n return Number(`${shiftedMantissa}e${Number(shiftedExponent) - precision}`) + 0;\n};\n\nexport const getUID = () => Math.random().toString(36).slice(2).toUpperCase();\n\nexport const toCamel = (s: string) => {\n return s.replace(/([-_][a-z])/gi, (sub: string) => {\n return sub.toUpperCase().replace('-', '').replace('_', '');\n });\n};\n\n/** Arrays stay arrays - mapping one through the object branch would turn it into an index-keyed object - but their object elements still need their keys camelized. Dates are opaque values. */\nconst camelizeValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((element) => camelizeValue(element));\n }\n\n if (!value || typeof value !== 'object' || value instanceof Date) {\n return value;\n }\n\n const camelized: any = {};\n const valueKeys = Object.keys(value);\n for (const key of valueKeys) {\n camelized[toCamel(key)] = camelizeValue((value as Record<string, unknown>)[key]);\n }\n\n return camelized;\n};\n\nexport const keysToCamel = (object: object) => {\n const n: any = {};\n const keys = Object.keys(object);\n\n for (const key of keys) {\n n[toCamel(key)] = camelizeValue((object as Record<string, unknown>)[key]);\n }\n\n return n;\n};\n\nexport const isInt = (n: any) => {\n if (isNaN(n)) {\n return false;\n }\n\n return Number.isInteger(n) || Math.floor(Number(n)) === n || Number(n) % 1 === 0;\n};\n\nexport const isFloat = (input: any) => {\n if (isNaN(input)) {\n return false;\n }\n\n return Number(input) === input || Number(input) % 1 !== 0;\n};\n\n/**\n * Parses an integer, TOTAL by design: it always answers a number, and answers `0` for anything it\n * cannot parse - `undefined`, `''`, `'abc'`.\n *\n * That makes `int(value) ?? fallback` dead code, because the left side is never nullish. The\n * fallback belongs INSIDE the call, and for an environment read it belongs in the read itself:\n *\n * ```ts\n * int(applicationEnvironment.get(KEY, { defaultValue: '6379' })) // correct\n * int(applicationEnvironment.get(KEY)) ?? 6379 // always 0 when KEY is unset\n * ```\n *\n * The second form is silent: a missing port reads `0` and a missing retry budget reads `0`, which\n * through `AbstractRedisHelper.buildRetryStrategy` means \"give up after the first failure\".\n */\nexport const int = (input: any) => {\n if (!input) {\n return 0;\n }\n\n const normalized = input?.toString()?.replace(/,/g, '');\n if (isNaN(normalized)) {\n return 0;\n }\n\n const parsed = Number.parseInt(normalized, 10);\n return Number.isNaN(parsed) ? 0 : parsed;\n};\n\nexport const float = (input: any, digit = 2) => {\n if (!input) {\n return 0;\n }\n\n const normalized = input?.toString()?.replace(/,/g, '');\n if (isNaN(normalized)) {\n return 0;\n }\n\n const parsed = round({ value: Number.parseFloat(normalized), precision: digit });\n return Number.isNaN(parsed) ? 0 : parsed;\n};\n\nexport const toBoolean = (input: any): boolean => {\n return (\n input !== '' &&\n input !== 'false' &&\n input !== '0' &&\n input !== false &&\n input !== 0 &&\n input !== null &&\n input !== undefined\n );\n};\n\n/** Converts an array to a Map keyed by `keyMap`. Last element wins on duplicate keys. */\nexport const parseArrayToMapWithKey = <T extends Record<K, PropertyKey>, K extends keyof T>(\n arr: T[],\n keyMap: K,\n): Map<T[K], T> => {\n const resultMap = new Map<T[K], T>();\n\n if (!arr.length) {\n return resultMap;\n }\n\n arr.forEach((element) => {\n if (!(keyMap in element)) {\n throw getError({\n message: 'Invalid keyMap',\n });\n }\n resultMap.set(element[keyMap], element);\n });\n\n return resultMap;\n};\n\n/** Splits a delimited string into trimmed, non-empty entries - the transform for list-shaped env values (e.g. `applicationEnvironment.get(KEY, { transform: toDelimitedArray })`). */\nexport const toDelimitedArray = (input: unknown, separator = ','): string[] => {\n if (input == null) {\n return [];\n }\n\n return String(input)\n .split(separator)\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n};\n\n/**\n * A trimmed value, or `undefined` when the input is absent or carries nothing but whitespace.\n *\n * Written for environment reads. `KEY=` in a deployment file is a pipeline that forgot to export the\n * value, but `process.env.KEY` answers `''` for it, and `''` walks straight past `??`:\n *\n * ```ts\n * process.env.APP_ENV_LOGGER_FORMAT ?? 'text' // '' when the line is blank\n * blankToUndefined(process.env.APP_ENV_LOGGER_FORMAT) ?? 'text' // 'text'\n * ```\n *\n * Reach for this rather than `||`, which reads `'0'` as blank as well.\n */\nexport const blankToUndefined = (input: string | undefined): string | undefined => {\n const trimmed = input?.trim();\n return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;\n};\n\n/** Trims a possibly-undefined env value to a clean string ('' when absent). */\nexport const toTrimmed = (input: unknown): string => {\n if (input == null) {\n return '';\n }\n\n return String(input).trim();\n};\n"]}
@@ -13,7 +13,7 @@ const executePromiseWithLimit = async (opts) => {
13
13
  const results = [];
14
14
  const executing = new Set();
15
15
  for (const task of tasks) {
16
- const promise = task().then(result => {
16
+ const promise = task().then((result) => {
17
17
  executing.delete(promise);
18
18
  return result;
19
19
  });
@@ -1 +1 @@
1
- {"version":3,"file":"promise.utility.js","sourceRoot":"","sources":["../../../src/utilities/promise.utility.ts"],"names":[],"mappings":";;;AACA,2CAA2C;AAK3C,oDAAoD;AAC7C,MAAM,uBAAuB,GAAG,KAAK,EAAK,IAIhD,EAAE,EAAE;IACH,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,GAAG,IAAI,CAAC;IAE1C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAA,gBAAQ,EAAC;YACb,OAAO,EAAE,0EAA0E,KAAK,EAAE;SAC3F,CAAC,CAAC;IACL,CAAC;IAED,MAAM,OAAO,GAAiB,EAAE,CAAC;IACjC,MAAM,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;IAE5B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,OAAO,GAAG,IAAI,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;YAC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,GAAG,CAAC,CAAC;IAC7B,IAAI,MAAM,GAAQ,GAAG,CAAC;IAEtB,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;YACnB,MAAM,IAAA,gBAAQ,EAAC,EAAE,OAAO,EAAE,yBAAyB,GAAG,QAAQ,MAAM,EAAE,EAAE,CAAC,CAAC;QAC5E,CAAC;QACD,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC;IAED,OAAO,MAAW,CAAC;AACrB,CAAC,CAAC;AAZW,QAAA,eAAe,mBAY1B;AAEF,sRAAsR;AAC/Q,MAAM,aAAa,GAAG,CAAC,IAI7B,EAAQ,EAAE;IACT,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IAE1C,IAAI,CAAC,IAAA,qBAAa,EAAC,SAAS,CAAC,EAAE,CAAC;QAC9B,OAAO;IACT,CAAC;IAED,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAClD,IAAI,MAAM,EAAE,CAAC;YACX,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,0DAA0D,EAAE,KAAK,CAAC,CAAC;YAC3F,OAAO;QACT,CAAC;QAED,OAAO,CAAC,KAAK,CAAC,mDAAmD,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IACnF,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAnBW,QAAA,aAAa,iBAmBxB","sourcesContent":["import { type ValueOrPromise } from '@/common';\nimport { getError } from '@/modules/error';\nimport type { ILogger } from '@/modules/logger';\n\nexport type TTask<T> = (...args: any[]) => Promise<T>;\n\n/** Execute async tasks with bounded concurrency. */\nexport const executePromiseWithLimit = async <T>(opts: {\n tasks: Array<TTask<T>>;\n limit: number;\n onTaskDone?: <R>(opts: { result: R }) => ValueOrPromise<void>;\n}) => {\n const { tasks, limit, onTaskDone } = opts;\n\n if (!Number.isInteger(limit) || limit < 1) {\n throw getError({\n message: `[executePromiseWithLimit] limit must be a positive integer | received: ${limit}`,\n });\n }\n\n const results: Promise<T>[] = [];\n const executing = new Set();\n\n for (const task of tasks) {\n const promise = task().then(result => {\n executing.delete(promise);\n return result;\n });\n\n executing.add(promise);\n results.push(promise);\n\n if (executing.size >= limit) {\n const done = await Promise.race(executing);\n await onTaskDone?.({ result: done });\n }\n }\n\n await Promise.all(executing);\n return Promise.all(results);\n};\n\n/** Normalize an unknown thrown value into an Error instance - an ApplicationError when it was not one. */\nexport const toError = (error: unknown): Error => {\n return error instanceof Error ? error : getError({ message: String(error) });\n};\n\n/** Check if a value is a promise. */\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> => {\n return (\n !!value &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as PromiseLike<T>).then === 'function'\n );\n};\n\n/** Traverse a dotted property path on an object. */\nexport const getDeepProperty = <T, V>(obj: T, path: string): V => {\n const keys = path.split('.');\n let result: any = obj;\n\n for (const key of keys) {\n if (result == null) {\n throw getError({ message: `Cannot read property '${key}' of ${result}` });\n }\n result = result[key];\n }\n\n return result as V;\n};\n\n/** Fire-and-forget: routes rejection to `logger` (or console.error), passes sync results through untouched. Standalone rather than a BaseHelper member - TS cannot emit protected members on an exported ANONYMOUS class (TS4094), which is what factory-built controllers return. */\nexport const voidExecution = (opts: {\n logger?: ILogger;\n scope: string;\n execution: ValueOrPromise<unknown>;\n}): void => {\n const { logger, scope, execution } = opts;\n\n if (!isPromiseLike(execution)) {\n return;\n }\n\n Promise.resolve(execution).catch((error: unknown) => {\n if (logger) {\n logger.for(scope).error('Unhandled error in fire-and-forget execution | Error: %s', error);\n return;\n }\n\n console.error('[%s] Unhandled error in fire-and-forget execution', scope, error);\n });\n};\n"]}
1
+ {"version":3,"file":"promise.utility.js","sourceRoot":"","sources":["../../../src/utilities/promise.utility.ts"],"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AAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAClD,IAAI,MAAM,EAAE,CAAC;YACX,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,0DAA0D,EAAE,KAAK,CAAC,CAAC;YAC3F,OAAO;QACT,CAAC;QAED,OAAO,CAAC,KAAK,CAAC,mDAAmD,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;IACnF,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AAnBW,QAAA,aAAa,iBAmBxB","sourcesContent":["import { type ValueOrPromise } from '@/common';\nimport { getError } from '@/modules/error';\nimport type { ILogger } from '@/modules/logger';\n\nexport type TTask<T> = (...args: any[]) => Promise<T>;\n\n/** Execute async tasks with bounded concurrency. */\nexport const executePromiseWithLimit = async <T>(opts: {\n tasks: Array<TTask<T>>;\n limit: number;\n onTaskDone?: <R>(opts: { result: R }) => ValueOrPromise<void>;\n}) => {\n const { tasks, limit, onTaskDone } = opts;\n\n if (!Number.isInteger(limit) || limit < 1) {\n throw getError({\n message: `[executePromiseWithLimit] limit must be a positive integer | received: ${limit}`,\n });\n }\n\n const results: Promise<T>[] = [];\n const executing = new Set();\n\n for (const task of tasks) {\n const promise = task().then((result) => {\n executing.delete(promise);\n return result;\n });\n\n executing.add(promise);\n results.push(promise);\n\n if (executing.size >= limit) {\n const done = await Promise.race(executing);\n await onTaskDone?.({ result: done });\n }\n }\n\n await Promise.all(executing);\n return Promise.all(results);\n};\n\n/** Normalize an unknown thrown value into an Error instance - an ApplicationError when it was not one. */\nexport const toError = (error: unknown): Error => {\n return error instanceof Error ? error : getError({ message: String(error) });\n};\n\n/** Check if a value is a promise. */\nexport const isPromiseLike = <T>(value: T | PromiseLike<T>): value is PromiseLike<T> => {\n return (\n !!value &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as PromiseLike<T>).then === 'function'\n );\n};\n\n/** Traverse a dotted property path on an object. */\nexport const getDeepProperty = <T, V>(obj: T, path: string): V => {\n const keys = path.split('.');\n let result: any = obj;\n\n for (const key of keys) {\n if (result == null) {\n throw getError({ message: `Cannot read property '${key}' of ${result}` });\n }\n result = result[key];\n }\n\n return result as V;\n};\n\n/** Fire-and-forget: routes rejection to `logger` (or console.error), passes sync results through untouched. Standalone rather than a BaseHelper member - TS cannot emit protected members on an exported ANONYMOUS class (TS4094), which is what factory-built controllers return. */\nexport const voidExecution = (opts: {\n logger?: ILogger;\n scope: string;\n execution: ValueOrPromise<unknown>;\n}): void => {\n const { logger, scope, execution } = opts;\n\n if (!isPromiseLike(execution)) {\n return;\n }\n\n Promise.resolve(execution).catch((error: unknown) => {\n if (logger) {\n logger.for(scope).error('Unhandled error in fire-and-forget execution | Error: %s', error);\n return;\n }\n\n console.error('[%s] Unhandled error in fire-and-forget execution', scope, error);\n });\n};\n"]}
@@ -76,7 +76,7 @@ const sanitizeFilename = (filename) => {
76
76
  exports.sanitizeFilename = sanitizeFilename;
77
77
  const encodeRFC5987 = (filename) => {
78
78
  return encodeURIComponent(filename)
79
- .replace(/['()]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())
79
+ .replace(/['()]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())
80
80
  .replace(/\*/g, '%2A');
81
81
  };
82
82
  exports.encodeRFC5987 = encodeRFC5987;
@@ -1 +1 @@
1
- {"version":3,"file":"request.utility.js","sourceRoot":"","sources":["../../../src/utilities/request.utility.ts"],"names":[],"mappings":";;;;;;AAAA,2CAA2C;AAC3C,2DAAmD;AACnD,sDAAyB;AACzB,0DAA6B;AAgCtB,MAAM,kBAAkB,GAAG,KAAK,EACrC,IAA+B,EACA,EAAE;IACjC,MAAM,EAAE,OAAO,GAAG,QAAQ,EAAE,SAAS,GAAG,WAAW,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAEtE,IAAI,OAAO,KAAK,MAAM,IAAI,CAAC,iBAAE,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QACpD,iBAAE,C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fs';\nimport path from 'node:path';\n\nexport interface IRequestedRemark {\n id: string;\n url: string;\n method: string;\n [extra: string | symbol]: any;\n}\n\ninterface IParseMultipartOptions<C extends { req: any } = { req: any }> {\n storage?: 'memory' | 'disk';\n uploadDir?: string;\n context: C;\n}\n\ninterface IParsedFile {\n fieldname: string;\n originalname: string;\n encoding: string;\n mimetype: string;\n size: number;\n buffer?: Buffer;\n filename?: string;\n path?: string;\n}\n\n/** Files and the text fields posted beside them - dropping the second silently loses what the client sent. */\nexport interface IParsedMultipartBody {\n files: IParsedFile[];\n fields: Record<string, string>;\n}\n\nexport const parseMultipartBody = async <C extends { req: any } = { req: any }>(\n opts: IParseMultipartOptions<C>,\n): Promise<IParsedMultipartBody> => {\n const { storage = 'memory', uploadDir = './uploads', context } = opts;\n\n if (storage === 'disk' && !fs.existsSync(uploadDir)) {\n fs.mkdirSync(uploadDir, { recursive: true });\n }\n\n const formData = await readFormBody({ req: context.req });\n const files: IParsedFile[] = [];\n const fields: Record<string, string> = {};\n\n const entries = formData.entries();\n for (const [fieldname, value] of entries) {\n if (typeof value === 'string') {\n // Last one wins, like a repeated query parameter.\n fields[fieldname] = value;\n continue;\n }\n\n const file = value as File;\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const parsedFile: IParsedFile = {\n fieldname,\n originalname: file.name,\n encoding: 'utf8',\n mimetype: file.type,\n size: file.size,\n };\n\n switch (storage) {\n case 'memory': {\n parsedFile.buffer = buffer;\n break;\n }\n case 'disk': {\n const timestamp = Date.now();\n const randomString = Math.random().toString(36).substring(7);\n // Sanitize filename to prevent path traversal\n const sanitizedName = path.basename(file.name).replace(/[^a-zA-Z0-9._-]/g, '_');\n const filename = `${timestamp}-${randomString}-${sanitizedName}`;\n const filepath = path.join(uploadDir, filename);\n\n fs.writeFileSync(filepath, buffer);\n\n parsedFile.filename = filename;\n parsedFile.path = filepath;\n break;\n }\n default: {\n throw getError({\n message: `[parseMultipartBody] storage: ${storage} | Invalid storage type | Valids: ['memory', 'disk']`,\n });\n }\n }\n\n files.push(parsedFile);\n }\n\n return { files, fields };\n};\n\n/** Sanitizes a filename by removing path components and dangerous characters. The result is printable ASCII. */\nexport const sanitizeFilename = (filename: string): string => {\n const basename = path.basename(filename);\n let sanitized = basename.replace(/[^\\w .-]/g, '_');\n sanitized = sanitized.replace(/^\\.+/, '');\n sanitized = sanitized.replace(/\\.{2,}/g, '.');\n sanitized = sanitized.replace(/\\.\\./g, '.');\n if (!sanitized || sanitized === '.' || sanitized.includes('..')) {\n sanitized = 'download';\n }\n return sanitized;\n};\n\nexport const encodeRFC5987 = (filename: string): string => {\n return encodeURIComponent(filename)\n .replace(/['()]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n .replace(/\\*/g, '%2A');\n};\n\n/** Control, format (bidi overrides, zero-width space) and lone surrogate characters: a format character reorders the name a client shows, a lone surrogate makes `encodeURIComponent` throw. The zero-width joiner and non-joiner stay: they build emoji sequences and Persian words, and reorder nothing. */\nconst UNENCODABLE_FILENAME_CHARACTERS = /(?![\\u200C\\u200D])[\\p{Cc}\\p{Cf}\\p{Cs}]/gu;\nconst LEADING_DOTS = /^\\.+/;\n\nexport const createContentDispositionHeader = (opts: {\n filename: string;\n type: 'attachment' | 'inline';\n}): string => {\n const { filename, type } = opts;\n const sanitized = sanitizeFilename(filename);\n const extendedName = path\n .basename(filename)\n .replace(UNENCODABLE_FILENAME_CHARACTERS, '_')\n .replace(LEADING_DOTS, '');\n const encoded = encodeRFC5987(extendedName || sanitized);\n\n // filename= is the ASCII fallback for old browsers, filename*= the UTF-8 form for modern ones.\n return `${type}; filename=\"${sanitized}\"; filename*=UTF-8''${encoded}`;\n};\n\n/**\n * Reads a filename out of a `Content-Disposition` value.\n *\n * Three forms, in the order the RFC gives them precedence: `filename*=UTF-8''...` (percent-encoded,\n * and the one hand-rolled parsers miss), a quoted `filename=\"...\"`, and a bare `filename=...`.\n * Splitting on `filename=` alone returns the percent-encoded bytes for any non-ASCII name, which in\n * a product with non-English filenames is most of them.\n *\n * The pair of {@link createContentDispositionHeader}: one writes the header, this one reads it.\n */\nexport const parseContentDisposition = (opts: {\n header: string | null | undefined;\n}): { type?: string; filename?: string } => {\n const { header } = opts;\n\n if (!header) {\n return {};\n }\n\n const type = header.split(';')[0]?.trim() || undefined;\n\n // `filename*` wins when both are present - it is the one that can carry a non-ASCII name.\n const extended = header.match(/filename\\*\\s*=\\s*([^;]+)/i);\n if (extended) {\n const value = extended[1].trim();\n // `UTF-8''name` or `UTF-8'lang'name`; anything before the last quote is charset and language.\n const encoded = value.slice(value.lastIndexOf(\"'\") + 1);\n\n try {\n return { type, filename: decodeURIComponent(encoded) };\n } catch {\n // A malformed sequence is not worth failing a download over - fall through to `filename`.\n }\n }\n\n const quoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i);\n if (quoted) {\n return { type, filename: quoted[1] };\n }\n\n const bare = header.match(/filename\\s*=\\s*([^;]+)/i);\n return { type, filename: bare ? bare[1].trim() : undefined };\n};\n"]}
1
+ {"version":3,"file":"request.utility.js","sourceRoot":"","sources":["../../../src/utilities/request.utility.ts"],"names":[],"mappings":";;;;;;AAAA,2CAA2C;AAC3C,2DAAmD;AACnD,sDAAyB;AACzB,0DAA6B;AAgCtB,MAAM,kBAAkB,GAAG,KAAK,EACrC,IAA+B,EACA,EAAE;IACjC,MAAM,EAAE,OAAO,GAAG,QAAQ,EAAE,SAAS,GAAG,WAAW,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAEtE,IAAI,OAAO,KAAK,MAAM,IAAI,CAAC,iBAAE,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QACpD,iBAAE,CAAC,SAAS,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,IAAA,gCAAY,EAAC,EAAE,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,CAA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AAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;IAEvD,0FAA0F;IAC1F,MAAM,QAAQ,GAAG,MAAM,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC3D,IAAI,QAAQ,EAAE,CAAC;QACb,MAAM,KAAK,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACjC,8FAA8F;QAC9F,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;QAExD,IAAI,CAAC;YACH,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;QACzD,CAAC;QAAC,MAAM,CAAC;YACP,0FAA0F;QAC5F,CAAC;IACH,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;IACzD,IAAI,MAAM,EAAE,CAAC;QACX,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;IACvC,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC;IACrD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;AAC/D,CAAC,CAAC;AAhCW,QAAA,uBAAuB,2BAgClC","sourcesContent":["import { getError } from '@/modules/error';\nimport { readFormBody } from './form-body.utility';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nexport interface IRequestedRemark {\n id: string;\n url: string;\n method: string;\n [extra: string | symbol]: any;\n}\n\ninterface IParseMultipartOptions<C extends { req: any } = { req: any }> {\n storage?: 'memory' | 'disk';\n uploadDir?: string;\n context: C;\n}\n\ninterface IParsedFile {\n fieldname: string;\n originalname: string;\n encoding: string;\n mimetype: string;\n size: number;\n buffer?: Buffer;\n filename?: string;\n path?: string;\n}\n\n/** Files and the text fields posted beside them - dropping the second silently loses what the client sent. */\nexport interface IParsedMultipartBody {\n files: IParsedFile[];\n fields: Record<string, string>;\n}\n\nexport const parseMultipartBody = async <C extends { req: any } = { req: any }>(\n opts: IParseMultipartOptions<C>,\n): Promise<IParsedMultipartBody> => {\n const { storage = 'memory', uploadDir = './uploads', context } = opts;\n\n if (storage === 'disk' && !fs.existsSync(uploadDir)) {\n fs.mkdirSync(uploadDir, { recursive: true });\n }\n\n const formData = await readFormBody({ req: context.req });\n const files: IParsedFile[] = [];\n const fields: Record<string, string> = {};\n\n const entries = formData.entries();\n for (const [fieldname, value] of entries) {\n if (typeof value === 'string') {\n // Last one wins, like a repeated query parameter.\n fields[fieldname] = value;\n continue;\n }\n\n const file = value as File;\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const parsedFile: IParsedFile = {\n fieldname,\n originalname: file.name,\n encoding: 'utf8',\n mimetype: file.type,\n size: file.size,\n };\n\n switch (storage) {\n case 'memory': {\n parsedFile.buffer = buffer;\n break;\n }\n case 'disk': {\n const timestamp = Date.now();\n const randomString = Math.random().toString(36).substring(7);\n // Sanitize filename to prevent path traversal\n const sanitizedName = path.basename(file.name).replace(/[^a-zA-Z0-9._-]/g, '_');\n const filename = `${timestamp}-${randomString}-${sanitizedName}`;\n const filepath = path.join(uploadDir, filename);\n\n fs.writeFileSync(filepath, buffer);\n\n parsedFile.filename = filename;\n parsedFile.path = filepath;\n break;\n }\n default: {\n throw getError({\n message: `[parseMultipartBody] storage: ${storage} | Invalid storage type | Valids: ['memory', 'disk']`,\n });\n }\n }\n\n files.push(parsedFile);\n }\n\n return { files, fields };\n};\n\n/** Sanitizes a filename by removing path components and dangerous characters. The result is printable ASCII. */\nexport const sanitizeFilename = (filename: string): string => {\n const basename = path.basename(filename);\n let sanitized = basename.replace(/[^\\w .-]/g, '_');\n sanitized = sanitized.replace(/^\\.+/, '');\n sanitized = sanitized.replace(/\\.{2,}/g, '.');\n sanitized = sanitized.replace(/\\.\\./g, '.');\n if (!sanitized || sanitized === '.' || sanitized.includes('..')) {\n sanitized = 'download';\n }\n return sanitized;\n};\n\nexport const encodeRFC5987 = (filename: string): string => {\n return encodeURIComponent(filename)\n .replace(/['()]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n .replace(/\\*/g, '%2A');\n};\n\n/** Control, format (bidi overrides, zero-width space) and lone surrogate characters: a format character reorders the name a client shows, a lone surrogate makes `encodeURIComponent` throw. The zero-width joiner and non-joiner stay: they build emoji sequences and Persian words, and reorder nothing. */\nconst UNENCODABLE_FILENAME_CHARACTERS = /(?![\\u200C\\u200D])[\\p{Cc}\\p{Cf}\\p{Cs}]/gu;\nconst LEADING_DOTS = /^\\.+/;\n\nexport const createContentDispositionHeader = (opts: {\n filename: string;\n type: 'attachment' | 'inline';\n}): string => {\n const { filename, type } = opts;\n const sanitized = sanitizeFilename(filename);\n const extendedName = path\n .basename(filename)\n .replace(UNENCODABLE_FILENAME_CHARACTERS, '_')\n .replace(LEADING_DOTS, '');\n const encoded = encodeRFC5987(extendedName || sanitized);\n\n // filename= is the ASCII fallback for old browsers, filename*= the UTF-8 form for modern ones.\n return `${type}; filename=\"${sanitized}\"; filename*=UTF-8''${encoded}`;\n};\n\n/**\n * Reads a filename out of a `Content-Disposition` value.\n *\n * Three forms, in the order the RFC gives them precedence: `filename*=UTF-8''...` (percent-encoded,\n * and the one hand-rolled parsers miss), a quoted `filename=\"...\"`, and a bare `filename=...`.\n * Splitting on `filename=` alone returns the percent-encoded bytes for any non-ASCII name, which in\n * a product with non-English filenames is most of them.\n *\n * The pair of {@link createContentDispositionHeader}: one writes the header, this one reads it.\n */\nexport const parseContentDisposition = (opts: {\n header: string | null | undefined;\n}): { type?: string; filename?: string } => {\n const { header } = opts;\n\n if (!header) {\n return {};\n }\n\n const type = header.split(';')[0]?.trim() || undefined;\n\n // `filename*` wins when both are present - it is the one that can carry a non-ASCII name.\n const extended = header.match(/filename\\*\\s*=\\s*([^;]+)/i);\n if (extended) {\n const value = extended[1].trim();\n // `UTF-8''name` or `UTF-8'lang'name`; anything before the last quote is charset and language.\n const encoded = value.slice(value.lastIndexOf(\"'\") + 1);\n\n try {\n return { type, filename: decodeURIComponent(encoded) };\n } catch {\n // A malformed sequence is not worth failing a download over - fall through to `filename`.\n }\n }\n\n const quoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i);\n if (quoted) {\n return { type, filename: quoted[1] };\n }\n\n const bare = header.match(/filename\\s*=\\s*([^;]+)/i);\n return { type, filename: bare ? bare[1].trim() : undefined };\n};\n"]}
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.sleep = void 0;
4
4
  const sleep = (ms) => {
5
- return new Promise(resolve => setTimeout(resolve, ms));
5
+ return new Promise((resolve) => setTimeout(resolve, ms));
6
6
  };
7
7
  exports.sleep = sleep;
8
8
  //# sourceMappingURL=sleep.utility.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sleep.utility.js","sourceRoot":"","sources":["../../../src/utilities/sleep.utility.ts"],"names":[],"mappings":";;;AAAO,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE;IAClC,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AACzD,CAAC,CAAC;AAFW,QAAA,KAAK,SAEhB","sourcesContent":["export const sleep = (ms: number) => {\n return new Promise(resolve => setTimeout(resolve, ms));\n};\n"]}
1
+ {"version":3,"file":"sleep.utility.js","sourceRoot":"","sources":["../../../src/utilities/sleep.utility.ts"],"names":[],"mappings":";;;AAAO,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE;IAClC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC,CAAC;AAFW,QAAA,KAAK,SAEhB","sourcesContent":["export const sleep = (ms: number) => {\n return new Promise((resolve) => setTimeout(resolve, ms));\n};\n"]}
@@ -74,11 +74,14 @@ export declare class DurationMultipliers {
74
74
  static readonly MONTH: number;
75
75
  static readonly YEAR: number;
76
76
  static readonly BY_UNIT: Record<string, number>;
77
+ /** The multiplier of a known unit, `null` for anything else - inherited property names included. */
78
+ private static multiplierOf;
77
79
  /**
78
80
  * `null` rather than a throw, so a caller that wants an error raises its own with its own context.
79
81
  * Every method here answers the same way.
80
82
  *
81
- * One map read, not a validity check followed by a read: an unknown unit is already `undefined`.
83
+ * The unit is checked against {@link DurationUnits.SCHEME_SET} first: a plain-object read alone
84
+ * would answer `'constructor'` or `'toString'` with a member of `Object.prototype`, not `undefined`.
82
85
  */
83
86
  static toMilliseconds(opts: IDuration | null): number | null;
84
87
  /** The inverse of {@link toMilliseconds}. Fractional on purpose - rounding here would silently lose a 36-hour window asked for in days. */
@@ -1 +1 @@
1
- {"version":3,"file":"duration.d.ts","sourceRoot":"","sources":["../../../../src/common/constants/duration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,UAAU,CAAC;AAE5C,qEAAqE;AACrE,qBAAa,aAAa;IACxB,MAAM,CAAC,QAAQ,CAAC,WAAW,iBAAiB;IAC5C,MAAM,CAAC,QAAQ,CAAC,MAAM,YAAY;IAClC,MAAM,CAAC,QAAQ,CAAC,MAAM,YAAY;IAClC,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;IAC9B,MAAM,CAAC,QAAQ,CAAC,GAAG,SAAS;IAC5B,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;IAC9B,MAAM,CAAC,QAAQ,CAAC,KAAK,WAAW;IAChC,MAAM,CAAC,QAAQ,CAAC,IAAI,UAAU;IAE9B,MAAM,CAAC,QAAQ,CA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;KAAE,GAAG,MAAM,GAAG,IAAI;IAW9F,2JAA2J;IAC3J,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;IAqB7C,qGAAqG;IACrG,MAAM,CAAC,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;CAGzD"}
@@ -114,35 +114,40 @@ export class DurationMultipliers {
114
114
  [DurationUnits.MONTH]: this.MONTH,
115
115
  [DurationUnits.YEAR]: this.YEAR,
116
116
  }; }
117
+ /** The multiplier of a known unit, `null` for anything else - inherited property names included. */
118
+ static multiplierOf(unit) {
119
+ return typeof unit === 'string' && DurationUnits.isValid(unit) ? this.BY_UNIT[unit] : null;
120
+ }
117
121
  /**
118
122
  * `null` rather than a throw, so a caller that wants an error raises its own with its own context.
119
123
  * Every method here answers the same way.
120
124
  *
121
- * One map read, not a validity check followed by a read: an unknown unit is already `undefined`.
125
+ * The unit is checked against {@link DurationUnits.SCHEME_SET} first: a plain-object read alone
126
+ * would answer `'constructor'` or `'toString'` with a member of `Object.prototype`, not `undefined`.
122
127
  */
123
128
  static toMilliseconds(opts) {
124
129
  if (!opts) {
125
130
  return null;
126
131
  }
127
- const multiplier = this.BY_UNIT[opts.unit];
128
- if (multiplier === undefined || !Number.isFinite(opts.value)) {
132
+ const multiplier = this.multiplierOf(opts.unit);
133
+ if (multiplier === null || !Number.isFinite(opts.value)) {
129
134
  return null;
130
135
  }
131
136
  return Math.round(opts.value * multiplier);
132
137
  }
133
138
  /** The inverse of {@link toMilliseconds}. Fractional on purpose - rounding here would silently lose a 36-hour window asked for in days. */
134
139
  static fromMilliseconds(opts) {
135
- const multiplier = this.BY_UNIT[opts?.unit];
136
- if (multiplier === undefined || !Number.isFinite(opts.milliseconds)) {
140
+ const multiplier = this.multiplierOf(opts?.unit);
141
+ if (multiplier === null || !Number.isFinite(opts.milliseconds)) {
137
142
  return null;
138
143
  }
139
144
  return opts.milliseconds / multiplier;
140
145
  }
141
146
  /** Unit to unit, through milliseconds. Fractional, for the reason {@link fromMilliseconds} gives. */
142
147
  static convert(opts) {
143
- const source = this.BY_UNIT[opts?.from];
144
- const target = this.BY_UNIT[opts?.to];
145
- if (source === undefined || target === undefined || !Number.isFinite(opts.value)) {
148
+ const source = this.multiplierOf(opts?.from);
149
+ const target = this.multiplierOf(opts?.to);
150
+ if (source === null || target === null || !Number.isFinite(opts.value)) {
146
151
  return null;
147
152
  }
148
153
  return (opts.value * source) / target;
@@ -1 +1 @@
1
- {"version":3,"file":"duration.js","sourceRoot":"","sources":["../../../../src/common/constants/duration.ts"],"names":[],"mappings":"AAEA,qEAAqE;AACrE,MAAM,OAAO,aAAa;aACR,gBAAW,GAAG,aAAa,CAAC;aAC5B,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,SAAI,GAAG,MAAM,CAAC;aACd,QAAG,GAAG,KAAK,CAAC;aACZ,SAAI,GAAG,MAAM,CAAC;aACd,UAAK,GAAG,OAAO,CAAC;aAChB,SAAI,GAAG,MAAM,CAAC;aAEd,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,GAAG;QACR,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,KAAK;QACV,IAAI,CAAC,IAAI;KACV,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAKH;;;;;;GAMG;AACH,MAAM,OAAO,eAAe;aACV,OAAE,GAAG,aAAa,CAAC,WAAW,CAAC;aAC/B,SAAI,GAAG,aAAa,CAAC,WAAW,CAAC;aACjC,gBAAW,GAAG,aAAa,CAAC,WAAW,CAAC;aACxC,iBAAY,GAAG,aAAa,CAAC,WAAW,C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CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAChD,CAAC","sourcesContent":["import { type TConstValue } from '../types';\n\n/** The time units a duration can be expressed in, smallest first. */\nexport class DurationUnits {\n static readonly MILLISECOND = 'millisecond';\n static readonly SECOND = 'second';\n static readonly MINUTE = 'minute';\n static readonly HOUR = 'hour';\n static readonly DAY = 'day';\n static readonly WEEK = 'week';\n static readonly MONTH = 'month';\n static readonly YEAR = 'year';\n\n static readonly SCHEME_SET = new Set([\n this.MILLISECOND,\n this.SECOND,\n this.MINUTE,\n this.HOUR,\n this.DAY,\n this.WEEK,\n this.MONTH,\n this.YEAR,\n ]);\n\n static isValid(input: string): input is TDurationUnit {\n return this.SCHEME_SET.has(input);\n }\n}\n\nexport type TDurationUnit = TConstValue<typeof DurationUnits>;\n\n/**\n * Written spellings that resolve to a unit. Member names are the spelling, upper-cased - so\n * {@link resolve} upper-cases its input and reads one property, with no second table to keep in step.\n *\n * `M` is MINUTE and `MO` is MONTH - the same choice every duration library makes, and the one\n * ambiguity a reader will trip on. There is no single-letter month.\n */\nexport class DurationAliases {\n static readonly MS = DurationUnits.MILLISECOND;\n static readonly MSEC = DurationUnits.MILLISECOND;\n static readonly MILLISECOND = DurationUnits.MILLISECOND;\n static readonly MILLISECONDS = DurationUnits.MILLISECOND;\n\n static readonly S = DurationUnits.SECOND;\n static readonly SEC = DurationUnits.SECOND;\n static readonly SECOND = DurationUnits.SECOND;\n static readonly SECONDS = DurationUnits.SECOND;\n\n static readonly M = DurationUnits.MINUTE;\n static readonly MIN = DurationUnits.MINUTE;\n static readonly MINUTE = DurationUnits.MINUTE;\n static readonly MINUTES = DurationUnits.MINUTE;\n\n static readonly H = DurationUnits.HOUR;\n static readonly HR = DurationUnits.HOUR;\n static readonly HOUR = DurationUnits.HOUR;\n static readonly HOURS = DurationUnits.HOUR;\n\n static readonly D = DurationUnits.DAY;\n static readonly DAY = DurationUnits.DAY;\n static readonly DAYS = DurationUnits.DAY;\n\n static readonly W = DurationUnits.WEEK;\n static readonly WK = DurationUnits.WEEK;\n static readonly WEEK = DurationUnits.WEEK;\n static readonly WEEKS = DurationUnits.WEEK;\n\n static readonly MO = DurationUnits.MONTH;\n static readonly MON = DurationUnits.MONTH;\n static readonly MONTH = DurationUnits.MONTH;\n static readonly MONTHS = DurationUnits.MONTH;\n\n static readonly Y = DurationUnits.YEAR;\n static readonly YR = DurationUnits.YEAR;\n static readonly YEAR = DurationUnits.YEAR;\n static readonly YEARS = DurationUnits.YEAR;\n\n /** Resolves a written unit - `'d'`, `'days'`, `'DAY'` - to its canonical name, or `null`. */\n static resolve(input: string): TDurationUnit | null {\n if (typeof input !== 'string') {\n return null;\n }\n\n // Try the input as given first. `trim().toUpperCase()` allocates two strings and costs ~55ns,\n // where the lookup itself is ~1ns - so the spellings callers actually pass (`'day'`, `'d'`,\n // `'DAYS'`) must not pay for it. Measured, both ways.\n //\n // The table is declared below because it is derived FROM this class; it is read at call time,\n // never at class-evaluation time.\n /* eslint-disable @typescript-eslint/no-use-before-define */\n return ALIAS_LOOKUP.get(input) ?? ALIAS_LOOKUP.get(input.trim().toUpperCase()) ?? null;\n /* eslint-enable @typescript-eslint/no-use-before-define */\n }\n}\n\n/**\n * Derived from the class once, never hand-listed, so the two cannot drift. Reading the class\n * directly is slower and would need `name`/`length`/`constructor` guarded out. Each spelling is\n * stored upper and lower so the common call allocates nothing.\n */\nconst ALIAS_LOOKUP: Map<string, TDurationUnit> = new Map(\n Object.entries(DurationAliases)\n .filter((entry): entry is [string, TDurationUnit] => DurationUnits.isValid(entry[1] as string))\n .flatMap(([spelling, unit]): Array<[string, TDurationUnit]> => [\n [spelling, unit],\n [spelling.toLowerCase(), unit],\n ]),\n);\n\nexport interface IDuration {\n unit: TDurationUnit;\n value: number;\n}\n\n/** `30d`, `1500 ms`, `-2 Hours`. One number, optional space, one unit. */\nconst DURATION_PATTERN = /^([+-]?\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/i;\n\n/**\n * A month is 30 days and a year 365, nominal. These size a WINDOW - a grace period, a cache TTL, a\n * near-expiry horizon - and must never compute a calendar date: adding `MONTH` to 31 January lands\n * on 2 March in a leap year and 3 March otherwise. Use a date library for calendar arithmetic.\n */\nexport class DurationMultipliers {\n static readonly MILLISECOND = 1;\n static readonly SECOND = 1000 * this.MILLISECOND;\n static readonly MINUTE = 60 * this.SECOND;\n static readonly HOUR = 60 * this.MINUTE;\n static readonly DAY = 24 * this.HOUR;\n static readonly WEEK = 7 * this.DAY;\n static readonly MONTH = 30 * this.DAY;\n static readonly YEAR = 365 * this.DAY;\n\n static readonly BY_UNIT: Record<string, number> = {\n [DurationUnits.MILLISECOND]: this.MILLISECOND,\n [DurationUnits.SECOND]: this.SECOND,\n [DurationUnits.MINUTE]: this.MINUTE,\n [DurationUnits.HOUR]: this.HOUR,\n [DurationUnits.DAY]: this.DAY,\n [DurationUnits.WEEK]: this.WEEK,\n [DurationUnits.MONTH]: this.MONTH,\n [DurationUnits.YEAR]: this.YEAR,\n };\n\n /**\n * `null` rather than a throw, so a caller that wants an error raises its own with its own context.\n * Every method here answers the same way.\n *\n * One map read, not a validity check followed by a read: an unknown unit is already `undefined`.\n */\n static toMilliseconds(opts: IDuration | null): number | null {\n if (!opts) {\n return null;\n }\n\n const multiplier = this.BY_UNIT[opts.unit];\n\n if (multiplier === undefined || !Number.isFinite(opts.value)) {\n return null;\n }\n\n return Math.round(opts.value * multiplier);\n }\n\n /** The inverse of {@link toMilliseconds}. Fractional on purpose - rounding here would silently lose a 36-hour window asked for in days. */\n static fromMilliseconds(opts: { milliseconds: number; unit: TDurationUnit }): number | null {\n const multiplier = this.BY_UNIT[opts?.unit];\n\n if (multiplier === undefined || !Number.isFinite(opts.milliseconds)) {\n return null;\n }\n\n return opts.milliseconds / multiplier;\n }\n\n /** Unit to unit, through milliseconds. Fractional, for the reason {@link fromMilliseconds} gives. */\n static convert(opts: { value: number; from: TDurationUnit; to: TDurationUnit }): number | null {\n const source = this.BY_UNIT[opts?.from];\n const target = this.BY_UNIT[opts?.to];\n\n if (source === undefined || target === undefined || !Number.isFinite(opts.value)) {\n return null;\n }\n\n return (opts.value * source) / target;\n }\n\n /** Reads a written duration - `'30d'`, `'1500 ms'`, `'2 hours'` - into {@link IDuration}. Aliases and the `M`/`MO` rule are on {@link DurationAliases}. */\n static parse(input: string): IDuration | null {\n if (typeof input !== 'string') {\n return null;\n }\n\n const matched = DURATION_PATTERN.exec(input.trim());\n\n if (!matched) {\n return null;\n }\n\n const unit = DurationAliases.resolve(matched[2]);\n const value = Number(matched[1]);\n\n if (!unit || !Number.isFinite(value)) {\n return null;\n }\n\n return { unit, value };\n }\n\n /** `'30d'` straight to milliseconds - the shape a TTL or a grace period is usually configured in. */\n static parseToMilliseconds(input: string): number | null {\n return this.toMilliseconds(this.parse(input));\n }\n}\n"]}
1
+ {"version":3,"file":"duration.js","sourceRoot":"","sources":["../../../../src/common/constants/duration.ts"],"names":[],"mappings":"AAEA,qEAAqE;AACrE,MAAM,OAAO,aAAa;aACR,gBAAW,GAAG,aAAa,CAAC;aAC5B,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,SAAI,GAAG,MAAM,CAAC;aACd,QAAG,GAAG,KAAK,CAAC;aACZ,SAAI,GAAG,MAAM,CAAC;aACd,UAAK,GAAG,OAAO,CAAC;aAChB,SAAI,GAAG,MAAM,CAAC;aAEd,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,GAAG;QACR,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,KAAK;QACV,IAAI,CAAC,IAAI;KACV,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;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AI,CAAC;QACd,CAAC;QAED,MAAM,IAAI,GAAG,eAAe,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QACjD,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QAEjC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACrC,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IACzB,CAAC;IAED,qGAAqG;IACrG,MAAM,CAAC,mBAAmB,CAAC,KAAa;QACtC,OAAO,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IAChD,CAAC","sourcesContent":["import { type TConstValue } from '../types';\n\n/** The time units a duration can be expressed in, smallest first. */\nexport class DurationUnits {\n static readonly MILLISECOND = 'millisecond';\n static readonly SECOND = 'second';\n static readonly MINUTE = 'minute';\n static readonly HOUR = 'hour';\n static readonly DAY = 'day';\n static readonly WEEK = 'week';\n static readonly MONTH = 'month';\n static readonly YEAR = 'year';\n\n static readonly SCHEME_SET = new Set([\n this.MILLISECOND,\n this.SECOND,\n this.MINUTE,\n this.HOUR,\n this.DAY,\n this.WEEK,\n this.MONTH,\n this.YEAR,\n ]);\n\n static isValid(input: string): input is TDurationUnit {\n return this.SCHEME_SET.has(input);\n }\n}\n\nexport type TDurationUnit = TConstValue<typeof DurationUnits>;\n\n/**\n * Written spellings that resolve to a unit. Member names are the spelling, upper-cased - so\n * {@link resolve} upper-cases its input and reads one property, with no second table to keep in step.\n *\n * `M` is MINUTE and `MO` is MONTH - the same choice every duration library makes, and the one\n * ambiguity a reader will trip on. There is no single-letter month.\n */\nexport class DurationAliases {\n static readonly MS = DurationUnits.MILLISECOND;\n static readonly MSEC = DurationUnits.MILLISECOND;\n static readonly MILLISECOND = DurationUnits.MILLISECOND;\n static readonly MILLISECONDS = DurationUnits.MILLISECOND;\n\n static readonly S = DurationUnits.SECOND;\n static readonly SEC = DurationUnits.SECOND;\n static readonly SECOND = DurationUnits.SECOND;\n static readonly SECONDS = DurationUnits.SECOND;\n\n static readonly M = DurationUnits.MINUTE;\n static readonly MIN = DurationUnits.MINUTE;\n static readonly MINUTE = DurationUnits.MINUTE;\n static readonly MINUTES = DurationUnits.MINUTE;\n\n static readonly H = DurationUnits.HOUR;\n static readonly HR = DurationUnits.HOUR;\n static readonly HOUR = DurationUnits.HOUR;\n static readonly HOURS = DurationUnits.HOUR;\n\n static readonly D = DurationUnits.DAY;\n static readonly DAY = DurationUnits.DAY;\n static readonly DAYS = DurationUnits.DAY;\n\n static readonly W = DurationUnits.WEEK;\n static readonly WK = DurationUnits.WEEK;\n static readonly WEEK = DurationUnits.WEEK;\n static readonly WEEKS = DurationUnits.WEEK;\n\n static readonly MO = DurationUnits.MONTH;\n static readonly MON = DurationUnits.MONTH;\n static readonly MONTH = DurationUnits.MONTH;\n static readonly MONTHS = DurationUnits.MONTH;\n\n static readonly Y = DurationUnits.YEAR;\n static readonly YR = DurationUnits.YEAR;\n static readonly YEAR = DurationUnits.YEAR;\n static readonly YEARS = DurationUnits.YEAR;\n\n /** Resolves a written unit - `'d'`, `'days'`, `'DAY'` - to its canonical name, or `null`. */\n static resolve(input: string): TDurationUnit | null {\n if (typeof input !== 'string') {\n return null;\n }\n\n // Try the input as given first. `trim().toUpperCase()` allocates two strings and costs ~55ns,\n // where the lookup itself is ~1ns - so the spellings callers actually pass (`'day'`, `'d'`,\n // `'DAYS'`) must not pay for it. Measured, both ways.\n //\n // The table is declared below because it is derived FROM this class; it is read at call time,\n // never at class-evaluation time.\n /* eslint-disable @typescript-eslint/no-use-before-define */\n return ALIAS_LOOKUP.get(input) ?? ALIAS_LOOKUP.get(input.trim().toUpperCase()) ?? null;\n /* eslint-enable @typescript-eslint/no-use-before-define */\n }\n}\n\n/**\n * Derived from the class once, never hand-listed, so the two cannot drift. Reading the class\n * directly is slower and would need `name`/`length`/`constructor` guarded out. Each spelling is\n * stored upper and lower so the common call allocates nothing.\n */\nconst ALIAS_LOOKUP: Map<string, TDurationUnit> = new Map(\n Object.entries(DurationAliases)\n .filter((entry): entry is [string, TDurationUnit] => DurationUnits.isValid(entry[1] as string))\n .flatMap(([spelling, unit]): Array<[string, TDurationUnit]> => [\n [spelling, unit],\n [spelling.toLowerCase(), unit],\n ]),\n);\n\nexport interface IDuration {\n unit: TDurationUnit;\n value: number;\n}\n\n/** `30d`, `1500 ms`, `-2 Hours`. One number, optional space, one unit. */\nconst DURATION_PATTERN = /^([+-]?\\d+(?:\\.\\d+)?)\\s*([a-z]+)$/i;\n\n/**\n * A month is 30 days and a year 365, nominal. These size a WINDOW - a grace period, a cache TTL, a\n * near-expiry horizon - and must never compute a calendar date: adding `MONTH` to 31 January lands\n * on 2 March in a leap year and 3 March otherwise. Use a date library for calendar arithmetic.\n */\nexport class DurationMultipliers {\n static readonly MILLISECOND = 1;\n static readonly SECOND = 1000 * this.MILLISECOND;\n static readonly MINUTE = 60 * this.SECOND;\n static readonly HOUR = 60 * this.MINUTE;\n static readonly DAY = 24 * this.HOUR;\n static readonly WEEK = 7 * this.DAY;\n static readonly MONTH = 30 * this.DAY;\n static readonly YEAR = 365 * this.DAY;\n\n static readonly BY_UNIT: Record<string, number> = {\n [DurationUnits.MILLISECOND]: this.MILLISECOND,\n [DurationUnits.SECOND]: this.SECOND,\n [DurationUnits.MINUTE]: this.MINUTE,\n [DurationUnits.HOUR]: this.HOUR,\n [DurationUnits.DAY]: this.DAY,\n [DurationUnits.WEEK]: this.WEEK,\n [DurationUnits.MONTH]: this.MONTH,\n [DurationUnits.YEAR]: this.YEAR,\n };\n\n /** The multiplier of a known unit, `null` for anything else - inherited property names included. */\n private static multiplierOf(unit: unknown): number | null {\n return typeof unit === 'string' && DurationUnits.isValid(unit) ? this.BY_UNIT[unit] : null;\n }\n\n /**\n * `null` rather than a throw, so a caller that wants an error raises its own with its own context.\n * Every method here answers the same way.\n *\n * The unit is checked against {@link DurationUnits.SCHEME_SET} first: a plain-object read alone\n * would answer `'constructor'` or `'toString'` with a member of `Object.prototype`, not `undefined`.\n */\n static toMilliseconds(opts: IDuration | null): number | null {\n if (!opts) {\n return null;\n }\n\n const multiplier = this.multiplierOf(opts.unit);\n\n if (multiplier === null || !Number.isFinite(opts.value)) {\n return null;\n }\n\n return Math.round(opts.value * multiplier);\n }\n\n /** The inverse of {@link toMilliseconds}. Fractional on purpose - rounding here would silently lose a 36-hour window asked for in days. */\n static fromMilliseconds(opts: { milliseconds: number; unit: TDurationUnit }): number | null {\n const multiplier = this.multiplierOf(opts?.unit);\n\n if (multiplier === null || !Number.isFinite(opts.milliseconds)) {\n return null;\n }\n\n return opts.milliseconds / multiplier;\n }\n\n /** Unit to unit, through milliseconds. Fractional, for the reason {@link fromMilliseconds} gives. */\n static convert(opts: { value: number; from: TDurationUnit; to: TDurationUnit }): number | null {\n const source = this.multiplierOf(opts?.from);\n const target = this.multiplierOf(opts?.to);\n\n if (source === null || target === null || !Number.isFinite(opts.value)) {\n return null;\n }\n\n return (opts.value * source) / target;\n }\n\n /** Reads a written duration - `'30d'`, `'1500 ms'`, `'2 hours'` - into {@link IDuration}. Aliases and the `M`/`MO` rule are on {@link DurationAliases}. */\n static parse(input: string): IDuration | null {\n if (typeof input !== 'string') {\n return null;\n }\n\n const matched = DURATION_PATTERN.exec(input.trim());\n\n if (!matched) {\n return null;\n }\n\n const unit = DurationAliases.resolve(matched[2]);\n const value = Number(matched[1]);\n\n if (!unit || !Number.isFinite(value)) {\n return null;\n }\n\n return { unit, value };\n }\n\n /** `'30d'` straight to milliseconds - the shape a TTL or a grace period is usually configured in. */\n static parseToMilliseconds(input: string): number | null {\n return this.toMilliseconds(this.parse(input));\n }\n}\n"]}
@@ -91,7 +91,7 @@ const deepSanitize = (value, context) => {
91
91
  return result;
92
92
  }
93
93
  if (Array.isArray(value)) {
94
- return value.map(entry => deepSanitize(entry, nested));
94
+ return value.map((entry) => deepSanitize(entry, nested));
95
95
  }
96
96
  const source = value;
97
97
  const result = {};
@@ -1 +1 @@
1
- {"version":3,"file":"redact.js","sourceRoot":"","sources":["../../../src/common/redact.ts"],"names":[],"mappings":"AAEA,gHAAgH;AAChH,MAAM,kBAAkB,GAAG,IAAI,MAAM,CACnC;IACE,qDAAqD;IACrD,6EAA6E;IAC7E,0EAA0E;IAC1E,oEAAoE;IAEpE,iKAAiK;IACjK,qCAAqC;IAErC,8MAA8M;IAC9M,yBAAyB;IAEzB,8RAA8R;IAC9R,2BAA2B;IAE3B,4JAA4J;IAC5J,qDAAqD;IAErD,yIAAyI;IACzI,+BAA+B;IAE/B,2MAA2M;IAC3M,gFAAgF;IAChF,6DAA6D;CAC9D,CAAC,IAAI,CAAC,EAAE,CAAC,EACV,GAAG,CACJ,CAAC;AAEF,MAAM,CAAC,MAAM,QAAQ,GAAG,YAAY,CAAC;AAErC,8KAA8K;AAC9K,MAAM,kBAAkB,GAAG,GAAY,EAAE,CACvC,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,wBAAwB,KAAK,OAAO,CAAC;AAEhE,uGAAuG;AACvG,MAAM,yBAAyB,GAAG,IAAI,CAAC;AAEvC,MAAM,sBAAsB,GAAG,GAAW,EAAE;IAC1C,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,EAAE,gCAAgC,CAAC,CAAC;IACrF,OAAO,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,UAAU,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,yBAAyB,CAAC;AACjG,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC,CAAC;AAEtE;;;;;;GAMG;AACH,MAAM,SAAS,GAAG,CAAC,IAAoD,EAAU,EAAE;IACjF,MAAM,EA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GAAG,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;QACrB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,OAAO,kBAAkB,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC/C,CAAC,CAAC","sourcesContent":["import { type AnyObject } from './types';\n\n/** Keys whose VALUES must never reach a log line - matched case-insensitively on the key name, at any depth. */\nconst SECRET_KEY_PATTERN = new RegExp(\n [\n // Options-object spellings (camelCase / snake_case).\n '^(pass|password|passphrase|secret|token|apiKey|api_key|accessKey|access_key',\n '|secretKey|secret_key|privateKey|private_key|key|cert|ca|pfx|credentials',\n '|authorization|auth|jwtSecret|applicationSecret|connectionString)$',\n\n // Vault wire spellings (snake_case): node-vault's AppRole login/response bodies carry these exact keys, and none are matched by the anchored options list above.\n '|^(client_token|secret_id|role_id)$',\n\n // Any `*_token` (snake_case) or `*Token` (camelCase) key; a preceding character is required so the bare word `token` (already covered above) is not the whole match, and so ordinary words are not swallowed.\n '|_token$|[a-z0-9]token$',\n\n // The `*Secret` counterpart the `*Token` rule always lacked. `clientSecret` / `client_secret` is the RFC 6749 parameter name and a live field on the search connector's model options, and `webhookSecret` is the standard spelling everywhere; none of them matched the anchored list above.\n '|_secret$|[a-z0-9]secret$',\n\n // Connection descriptors: `connectionString` was anchored above but its snake_case twin was not, and `dsn` is the third common spelling for the same thing.\n '|^(connection_string|dsn|database_url|databaseUrl)$',\n\n // Any `*_password` / `*Password` key - `dbPassword`, `admin_password`. The bare word is anchored above; this catches the prefixed forms.\n '|_password$|[a-z0-9]password$',\n\n // HTTP HEADER spellings: header names are kebab-case and often `x-`-prefixed, none of which the camelCase list above matches; `vault` is included so `X-Vault-Token` (node-vault's auth header) is caught.\n '|^(x-)?(api|auth|access|secret|session|csrf|xsrf|vault)-(key|token|secret|id)$',\n '|^(cookie|set-cookie|proxy-authorization|www-authenticate)$',\n ].join(''),\n 'i',\n);\n\nexport const REDACTED = '[REDACTED]';\n\n/** Kill-switch for local debugging: only the literal `false` disables redaction (fail-closed); read per call so it can be flipped at runtime. Never disable in production. */\nconst isRedactionEnabled = (): boolean =>\n globalThis.process?.env?.APP_ENV_LOGGER_DO_REDACT !== 'false';\n\n/** Longest string a log line carries whole. `APP_ENV_LOGGER_MAX_STRING_LENGTH=0` turns capping off. */\nconst DEFAULT_MAX_STRING_LENGTH = 2048;\n\nconst resolveMaxStringLength = (): number => {\n const configured = Number(globalThis.process?.env?.APP_ENV_LOGGER_MAX_STRING_LENGTH);\n return Number.isFinite(configured) && configured >= 0 ? configured : DEFAULT_MAX_STRING_LENGTH;\n};\n\n/**\n * Keys whose value is long BY NATURE and useless truncated. A stack trace is the whole reason you\n * are reading the line.\n */\nconst UNCAPPED_KEYS = new Set(['stack', 'stacktrace', 'stack_trace']);\n\n/**\n * Caps a long string, keeping the ORIGINAL LENGTH in the marker - that number is what tells you the\n * payload was a 300 KB image rather than a truncated sentence.\n *\n * A base64 body is the case this exists for: one `data:image/png;base64,...` field turns a request\n * log into hundreds of kilobytes, and nothing about it is readable.\n */\nconst capString = (opts: { value: string; key?: string; limit: number }): string => {\n const { value, key, limit } = opts;\n\n if (limit === 0 || value.length <= limit || (key && UNCAPPED_KEYS.has(key.toLowerCase()))) {\n return value;\n }\n\n return `${value.slice(0, limit)}... [truncated, ${value.length} chars total]`;\n};\n\ntype TSanitizeContext = {\n seen: WeakSet<object>;\n doRedact: boolean;\n /** Levels still allowed BELOW the current one; `Infinity` walks the whole graph. */\n depth: number;\n /** Longest string kept whole; 0 keeps every string. */\n maxStringLength: number;\n /** The key this value was found under, so a stack trace can be exempted from capping. */\n key?: string;\n};\n\nconst deepSanitize = (value: unknown, context: TSanitizeContext): unknown => {\n const { seen, doRedact, depth } = context;\n\n if (typeof value === 'string') {\n return capString({ value, key: context.key, limit: context.maxStringLength });\n }\n\n if (value === null || typeof value !== 'object') {\n return value;\n }\n\n // A Date holds its value in an internal slot, so the generic branch below - which reads Object.keys() - would flatten it to `{}`. Checked BEFORE `seen`: a Date cannot carry a cycle, and entering the set would make a second reference to the same instance read as `[Circular]`.\n if (value instanceof Date) {\n return value;\n }\n\n if (seen.has(value)) {\n return '[Circular]';\n }\n\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n return `[Binary ${(value as ArrayBufferView).byteLength ?? 0} bytes]`;\n }\n\n if (depth <= 0) {\n return Array.isArray(value) ? '[Array]' : '[Object]';\n }\n\n seen.add(value);\n const nested: TSanitizeContext = {\n seen,\n doRedact,\n depth: depth - 1,\n maxStringLength: context.maxStringLength,\n };\n\n // Error keeps name/message/stack NON-enumerable, so Object.keys() skips them and naive redaction would drop the message - reproject into a plain object carrying those fields plus its redacted enumerable own-props.\n if (value instanceof Error) {\n const source = value;\n const result: AnyObject = {\n name: value.name,\n message: value.message,\n stack: value.stack,\n };\n\n for (const [key, entry] of Object.entries(source)) {\n result[key] =\n doRedact && SECRET_KEY_PATTERN.test(key)\n ? REDACTED\n : deepSanitize(entry, { ...nested, key });\n }\n\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map(entry => deepSanitize(entry, nested));\n }\n\n const source = value;\n const result: AnyObject = {};\n\n for (const [key, entry] of Object.entries(source)) {\n if (doRedact && SECRET_KEY_PATTERN.test(key)) {\n result[key] = REDACTED;\n continue;\n }\n\n result[key] = deepSanitize(entry, { ...nested, key });\n }\n\n return result;\n};\n\n/**\n * Redacts every secret-looking KEY (not value shape - buffers/typed arrays are summarized, not\n * serialized). `APP_ENV_LOGGER_DO_REDACT=false` makes this the identity function.\n *\n * `depth` bounds the walk, exactly as {@link toJsonSafe} already does. It defaults to `Infinity` for\n * callers that really do want the whole graph, but the logger passes its own bound: rendering only\n * inspects a handful of levels, so walking to `Infinity` did work whose result was thrown away -\n * 12x on a deep graph, and a `RangeError` on a very deep chain.\n */\nexport const redactSecrets = (\n value: unknown,\n seen?: WeakSet<object>,\n depth: number = Infinity,\n): unknown => {\n if (!isRedactionEnabled()) {\n return value;\n }\n\n return deepSanitize(value, {\n seen: seen ?? new WeakSet<object>(),\n doRedact: true,\n depth,\n maxStringLength: resolveMaxStringLength(),\n });\n};\n\n/** Projects a value into something `JSON.stringify` can render: it answers `[Circular]` for the WHOLE payload when one cycle sits anywhere inside it, so cycles must be broken per-branch first. `depth` bounds the walk the way `util.inspect` does - a log argument may hold a live connector or request context, whose graph is effectively unbounded. The projection itself is unconditional: `APP_ENV_LOGGER_DO_REDACT=false` turns off the key masking, never the structural pass. */\nexport const toJsonSafe = (opts: { value: unknown; depth?: number }): unknown => {\n return deepSanitize(opts.value, {\n seen: new WeakSet<object>(),\n doRedact: isRedactionEnabled(),\n depth: opts.depth ?? Infinity,\n // Capping is STRUCTURAL, like the projection itself: turning redaction off is about key masking,\n // never about letting a 300 KB base64 field through.\n maxStringLength: resolveMaxStringLength(),\n });\n};\n\n/** Strips credentials from a connection URL's authority section (`user:hunter2@host` -> `user:[REDACTED]@host`) - {@link redactSecrets} matches on KEY names and can't see them there. A value that fails to parse as a URL is returned unchanged. */\nexport const redactUrlCredentials = (url: string): string => {\n if (!isRedactionEnabled()) {\n return url;\n }\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n } catch {\n return url;\n }\n\n if (!parsed.password) {\n return url;\n }\n\n parsed.password = REDACTED;\n return decodeURIComponent(parsed.toString());\n};\n"]}
1
+ {"version":3,"file":"redact.js","sourceRoot":"","sources":["../../../src/common/redact.ts"],"names":[],"mappings":"AAEA,gHAAgH;AAChH,MAAM,kBAAkB,GAAG,IAAI,MAAM,CACnC;IACE,qDAAqD;IACrD,6EAA6E;IAC7E,0EAA0E;IAC1E,oEAAoE;IAEpE,iKAAiK;IACjK,qCAAqC;IAErC,8MAA8M;IAC9M,yBAAyB;IAEzB,8RAA8R;IAC9R,2BAA2B;IAE3B,4JA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AAgB,QAAQ,EACf,EAAE;IACX,IAAI,CAAC,kBAAkB,EAAE,EAAE,CAAC;QAC1B,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,YAAY,CAAC,KAAK,EAAE;QACzB,IAAI,EAAE,IAAI,IAAI,IAAI,OAAO,EAAU;QACnC,QAAQ,EAAE,IAAI;QACd,KAAK;QACL,eAAe,EAAE,sBAAsB,EAAE;KAC1C,CAAC,CAAC;AACL,CAAC,CAAC;AAEF,4dAA4d;AAC5d,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,IAAwC,EAAW,EAAE;IAC9E,OAAO,YAAY,CAAC,IAAI,CAAC,KAAK,EAAE;QAC9B,IAAI,EAAE,IAAI,OAAO,EAAU;QAC3B,QAAQ,EAAE,kBAAkB,EAAE;QAC9B,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,QAAQ;QAC7B,iGAAiG;QACjG,qDAAqD;QACrD,eAAe,EAAE,sBAAsB,EAAE;KAC1C,CAAC,CAAC;AACL,CAAC,CAAC;AAEF,sPAAsP;AACtP,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GAAW,EAAU,EAAE;IAC1D,IAAI,CAAC,kBAAkB,EAAE,EAAE,CAAC;QAC1B,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,MAAW,CAAC;IAEhB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;QACrB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,OAAO,kBAAkB,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC,CAAC;AAC/C,CAAC,CAAC","sourcesContent":["import { type AnyObject } from './types';\n\n/** Keys whose VALUES must never reach a log line - matched case-insensitively on the key name, at any depth. */\nconst SECRET_KEY_PATTERN = new RegExp(\n [\n // Options-object spellings (camelCase / snake_case).\n '^(pass|password|passphrase|secret|token|apiKey|api_key|accessKey|access_key',\n '|secretKey|secret_key|privateKey|private_key|key|cert|ca|pfx|credentials',\n '|authorization|auth|jwtSecret|applicationSecret|connectionString)$',\n\n // Vault wire spellings (snake_case): node-vault's AppRole login/response bodies carry these exact keys, and none are matched by the anchored options list above.\n '|^(client_token|secret_id|role_id)$',\n\n // Any `*_token` (snake_case) or `*Token` (camelCase) key; a preceding character is required so the bare word `token` (already covered above) is not the whole match, and so ordinary words are not swallowed.\n '|_token$|[a-z0-9]token$',\n\n // The `*Secret` counterpart the `*Token` rule always lacked. `clientSecret` / `client_secret` is the RFC 6749 parameter name and a live field on the search connector's model options, and `webhookSecret` is the standard spelling everywhere; none of them matched the anchored list above.\n '|_secret$|[a-z0-9]secret$',\n\n // Connection descriptors: `connectionString` was anchored above but its snake_case twin was not, and `dsn` is the third common spelling for the same thing.\n '|^(connection_string|dsn|database_url|databaseUrl)$',\n\n // Any `*_password` / `*Password` key - `dbPassword`, `admin_password`. The bare word is anchored above; this catches the prefixed forms.\n '|_password$|[a-z0-9]password$',\n\n // HTTP HEADER spellings: header names are kebab-case and often `x-`-prefixed, none of which the camelCase list above matches; `vault` is included so `X-Vault-Token` (node-vault's auth header) is caught.\n '|^(x-)?(api|auth|access|secret|session|csrf|xsrf|vault)-(key|token|secret|id)$',\n '|^(cookie|set-cookie|proxy-authorization|www-authenticate)$',\n ].join(''),\n 'i',\n);\n\nexport const REDACTED = '[REDACTED]';\n\n/** Kill-switch for local debugging: only the literal `false` disables redaction (fail-closed); read per call so it can be flipped at runtime. Never disable in production. */\nconst isRedactionEnabled = (): boolean =>\n globalThis.process?.env?.APP_ENV_LOGGER_DO_REDACT !== 'false';\n\n/** Longest string a log line carries whole. `APP_ENV_LOGGER_MAX_STRING_LENGTH=0` turns capping off. */\nconst DEFAULT_MAX_STRING_LENGTH = 2048;\n\nconst resolveMaxStringLength = (): number => {\n const configured = Number(globalThis.process?.env?.APP_ENV_LOGGER_MAX_STRING_LENGTH);\n return Number.isFinite(configured) && configured >= 0 ? configured : DEFAULT_MAX_STRING_LENGTH;\n};\n\n/**\n * Keys whose value is long BY NATURE and useless truncated. A stack trace is the whole reason you\n * are reading the line.\n */\nconst UNCAPPED_KEYS = new Set(['stack', 'stacktrace', 'stack_trace']);\n\n/**\n * Caps a long string, keeping the ORIGINAL LENGTH in the marker - that number is what tells you the\n * payload was a 300 KB image rather than a truncated sentence.\n *\n * A base64 body is the case this exists for: one `data:image/png;base64,...` field turns a request\n * log into hundreds of kilobytes, and nothing about it is readable.\n */\nconst capString = (opts: { value: string; key?: string; limit: number }): string => {\n const { value, key, limit } = opts;\n\n if (limit === 0 || value.length <= limit || (key && UNCAPPED_KEYS.has(key.toLowerCase()))) {\n return value;\n }\n\n return `${value.slice(0, limit)}... [truncated, ${value.length} chars total]`;\n};\n\ntype TSanitizeContext = {\n seen: WeakSet<object>;\n doRedact: boolean;\n /** Levels still allowed BELOW the current one; `Infinity` walks the whole graph. */\n depth: number;\n /** Longest string kept whole; 0 keeps every string. */\n maxStringLength: number;\n /** The key this value was found under, so a stack trace can be exempted from capping. */\n key?: string;\n};\n\nconst deepSanitize = (value: unknown, context: TSanitizeContext): unknown => {\n const { seen, doRedact, depth } = context;\n\n if (typeof value === 'string') {\n return capString({ value, key: context.key, limit: context.maxStringLength });\n }\n\n if (value === null || typeof value !== 'object') {\n return value;\n }\n\n // A Date holds its value in an internal slot, so the generic branch below - which reads Object.keys() - would flatten it to `{}`. Checked BEFORE `seen`: a Date cannot carry a cycle, and entering the set would make a second reference to the same instance read as `[Circular]`.\n if (value instanceof Date) {\n return value;\n }\n\n if (seen.has(value)) {\n return '[Circular]';\n }\n\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n return `[Binary ${(value as ArrayBufferView).byteLength ?? 0} bytes]`;\n }\n\n if (depth <= 0) {\n return Array.isArray(value) ? '[Array]' : '[Object]';\n }\n\n seen.add(value);\n const nested: TSanitizeContext = {\n seen,\n doRedact,\n depth: depth - 1,\n maxStringLength: context.maxStringLength,\n };\n\n // Error keeps name/message/stack NON-enumerable, so Object.keys() skips them and naive redaction would drop the message - reproject into a plain object carrying those fields plus its redacted enumerable own-props.\n if (value instanceof Error) {\n const source = value;\n const result: AnyObject = {\n name: value.name,\n message: value.message,\n stack: value.stack,\n };\n\n for (const [key, entry] of Object.entries(source)) {\n result[key] =\n doRedact && SECRET_KEY_PATTERN.test(key)\n ? REDACTED\n : deepSanitize(entry, { ...nested, key });\n }\n\n return result;\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => deepSanitize(entry, nested));\n }\n\n const source = value;\n const result: AnyObject = {};\n\n for (const [key, entry] of Object.entries(source)) {\n if (doRedact && SECRET_KEY_PATTERN.test(key)) {\n result[key] = REDACTED;\n continue;\n }\n\n result[key] = deepSanitize(entry, { ...nested, key });\n }\n\n return result;\n};\n\n/**\n * Redacts every secret-looking KEY (not value shape - buffers/typed arrays are summarized, not\n * serialized). `APP_ENV_LOGGER_DO_REDACT=false` makes this the identity function.\n *\n * `depth` bounds the walk, exactly as {@link toJsonSafe} already does. It defaults to `Infinity` for\n * callers that really do want the whole graph, but the logger passes its own bound: rendering only\n * inspects a handful of levels, so walking to `Infinity` did work whose result was thrown away -\n * 12x on a deep graph, and a `RangeError` on a very deep chain.\n */\nexport const redactSecrets = (\n value: unknown,\n seen?: WeakSet<object>,\n depth: number = Infinity,\n): unknown => {\n if (!isRedactionEnabled()) {\n return value;\n }\n\n return deepSanitize(value, {\n seen: seen ?? new WeakSet<object>(),\n doRedact: true,\n depth,\n maxStringLength: resolveMaxStringLength(),\n });\n};\n\n/** Projects a value into something `JSON.stringify` can render: it answers `[Circular]` for the WHOLE payload when one cycle sits anywhere inside it, so cycles must be broken per-branch first. `depth` bounds the walk the way `util.inspect` does - a log argument may hold a live connector or request context, whose graph is effectively unbounded. The projection itself is unconditional: `APP_ENV_LOGGER_DO_REDACT=false` turns off the key masking, never the structural pass. */\nexport const toJsonSafe = (opts: { value: unknown; depth?: number }): unknown => {\n return deepSanitize(opts.value, {\n seen: new WeakSet<object>(),\n doRedact: isRedactionEnabled(),\n depth: opts.depth ?? Infinity,\n // Capping is STRUCTURAL, like the projection itself: turning redaction off is about key masking,\n // never about letting a 300 KB base64 field through.\n maxStringLength: resolveMaxStringLength(),\n });\n};\n\n/** Strips credentials from a connection URL's authority section (`user:hunter2@host` -> `user:[REDACTED]@host`) - {@link redactSecrets} matches on KEY names and can't see them there. A value that fails to parse as a URL is returned unchanged. */\nexport const redactUrlCredentials = (url: string): string => {\n if (!isRedactionEnabled()) {\n return url;\n }\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n } catch {\n return url;\n }\n\n if (!parsed.password) {\n return url;\n }\n\n parsed.password = REDACTED;\n return decodeURIComponent(parsed.toString());\n};\n"]}
@@ -6,7 +6,7 @@ export class BaseHelper {
6
6
  }
7
7
  /** The helper's logger, resolved on first read - a helper that never logs never builds one. */
8
8
  get logger() {
9
- const scopes = [this.scope, this.identifier].filter(scope => typeof scope === 'string' && scope.length > 0);
9
+ const scopes = [this.scope, this.identifier].filter((scope) => typeof scope === 'string' && scope.length > 0);
10
10
  const logger = resolveHelperLogger({ scopes });
11
11
  // Read off a prototype (reflection walks them), pinning would shadow this getter for every instance.
12
12
  if (Object.hasOwn(this, 'scope')) {
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/modules/base.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE7E,MAAM,OAAO,UAAU;IAIrB,YAAY,IAA4C;QACtD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,IAAI,EAAE,CAAC;IAC1C,CAAC;IAED,+FAA+F;IAC/F,IAAI,MAAM;QACR,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CACjD,KAAK,CAAC,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CACvD,CAAC;QACF,MAAM,MAAM,GAAG,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QAE/C,qGAAqG;QACrG,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,CAAC;YACjC,eAAe,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;QAC5C,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,iGAAiG;IACjG,IAAI,MAAM,CAAC,KAAc;QACvB,eAAe,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IACnD,CAAC;IAED,aAAa;QACX,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { type ILogger } from '@/modules/logger/common/types';\nimport { pinHelperLogger, resolveHelperLogger } from '@/modules/logger/slot';\n\nexport class BaseHelper {\n scope: string;\n identifier: string;\n\n constructor(opts: { scope: string; identifier?: string }) {\n this.scope = opts.scope ?? '';\n this.identifier = opts.identifier ?? '';\n }\n\n /** The helper's logger, resolved on first read - a helper that never logs never builds one. */\n get logger(): ILogger {\n const scopes = [this.scope, this.identifier].filter(\n scope => typeof scope === 'string' && scope.length > 0,\n );\n const logger = resolveHelperLogger({ scopes });\n\n // Read off a prototype (reflection walks them), pinning would shadow this getter for every instance.\n if (Object.hasOwn(this, 'scope')) {\n pinHelperLogger({ helper: this, logger });\n }\n return logger;\n }\n\n /** Installs one logger on this helper - a test spy, or a host overriding the global resolver. */\n set logger(value: ILogger) {\n pinHelperLogger({ helper: this, logger: value });\n }\n\n getIdentifier() {\n return this.identifier;\n }\n\n getLogger(): ILogger {\n return this.logger;\n }\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../src/modules/base.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE7E,MAAM,OAAO,UAAU;IAIrB,YAAY,IAA4C;QACtD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,IAAI,EAAE,CAAC;IAC1C,CAAC;IAED,+FAA+F;IAC/F,IAAI,MAAM;QACR,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,CACjD,CAAC,KAAK,EAAE,EAAE,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CACzD,CAAC;QACF,MAAM,MAAM,GAAG,mBAAmB,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QAE/C,qGAAqG;QACrG,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,CAAC;YACjC,eAAe,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;QAC5C,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,iGAAiG;IACjG,IAAI,MAAM,CAAC,KAAc;QACvB,eAAe,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;IACnD,CAAC;IAED,aAAa;QACX,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAED,SAAS;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF","sourcesContent":["import { type ILogger } from '@/modules/logger/common/types';\nimport { pinHelperLogger, resolveHelperLogger } from '@/modules/logger/slot';\n\nexport class BaseHelper {\n scope: string;\n identifier: string;\n\n constructor(opts: { scope: string; identifier?: string }) {\n this.scope = opts.scope ?? '';\n this.identifier = opts.identifier ?? '';\n }\n\n /** The helper's logger, resolved on first read - a helper that never logs never builds one. */\n get logger(): ILogger {\n const scopes = [this.scope, this.identifier].filter(\n (scope) => typeof scope === 'string' && scope.length > 0,\n );\n const logger = resolveHelperLogger({ scopes });\n\n // Read off a prototype (reflection walks them), pinning would shadow this getter for every instance.\n if (Object.hasOwn(this, 'scope')) {\n pinHelperLogger({ helper: this, logger });\n }\n return logger;\n }\n\n /** Installs one logger on this helper - a test spy, or a host overriding the global resolver. */\n set logger(value: ILogger) {\n pinHelperLogger({ helper: this, logger: value });\n }\n\n getIdentifier() {\n return this.identifier;\n }\n\n getLogger(): ILogger {\n return this.logger;\n }\n}\n"]}
@@ -33,7 +33,7 @@ export class AES extends BaseCryptoAlgorithm {
33
33
  if (!Array.isArray(secret)) {
34
34
  return this.normalizeSecretKey({ secret, length, kdfSalt, kdfIterations });
35
35
  }
36
- const entry = secret.find(e => e.id === id);
36
+ const entry = secret.find((e) => e.id === id);
37
37
  if (!entry) {
38
38
  throw getError({
39
39
  message: `[AES][resolveDecryptKey] No key in keyring matches ciphertext key id "${id}"`,