@venizia/ignis-helpers 0.4.8-9 → 0.4.8

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 (199) hide show
  1. package/README.md +2 -3
  2. package/dist/esm/common/constants/app.d.ts +1 -3
  3. package/dist/esm/common/constants/app.js +1 -11
  4. package/dist/esm/common/constants/app.js.map +1 -1
  5. package/dist/esm/common/constants/http.d.ts +2 -0
  6. package/dist/esm/common/constants/http.js +3 -0
  7. package/dist/esm/common/constants/http.js.map +1 -1
  8. package/dist/esm/common/constants/mime.d.ts +0 -2
  9. package/dist/esm/common/constants/mime.js +0 -4
  10. package/dist/esm/common/constants/mime.js.map +1 -1
  11. package/dist/esm/common/redact.js.map +1 -1
  12. package/dist/esm/common/types/class.d.ts +14 -12
  13. package/dist/esm/common/types/class.js.map +1 -1
  14. package/dist/esm/common/types/const-value.d.ts +3 -3
  15. package/dist/esm/common/types/const-value.js.map +1 -1
  16. package/dist/esm/common/types/field-mapping.d.ts +6 -8
  17. package/dist/esm/common/types/field-mapping.js +0 -10
  18. package/dist/esm/common/types/field-mapping.js.map +1 -1
  19. package/dist/esm/common/types/index.d.ts +1 -0
  20. package/dist/esm/common/types/index.js +1 -0
  21. package/dist/esm/common/types/index.js.map +1 -1
  22. package/dist/esm/common/types/injection.d.ts +1 -1
  23. package/dist/esm/common/types/injection.js.map +1 -1
  24. package/dist/esm/common/types/json.d.ts +14 -0
  25. package/dist/esm/common/types/json.js +2 -0
  26. package/dist/esm/common/types/json.js.map +1 -0
  27. package/dist/esm/common/types/utility.d.ts +0 -4
  28. package/dist/esm/common/types/utility.js.map +1 -1
  29. package/dist/esm/modules/env/app-env.d.ts +17 -8
  30. package/dist/esm/modules/env/app-env.js +18 -15
  31. package/dist/esm/modules/env/app-env.js.map +1 -1
  32. package/dist/esm/modules/env/common/types.d.ts +22 -6
  33. package/dist/esm/modules/env/common/types.js.map +1 -1
  34. package/dist/esm/modules/logger/base/abstract.d.ts +6 -7
  35. package/dist/esm/modules/logger/base/abstract.js.map +1 -1
  36. package/dist/esm/modules/logger/base/base.d.ts +7 -8
  37. package/dist/esm/modules/logger/base/base.js.map +1 -1
  38. package/dist/esm/modules/logger/base/console.d.ts +6 -7
  39. package/dist/esm/modules/logger/base/console.js.map +1 -1
  40. package/dist/esm/modules/logger/common/types.d.ts +7 -7
  41. package/dist/esm/modules/logger/common/types.js.map +1 -1
  42. package/dist/esm/modules/logger/factory.js.map +1 -1
  43. package/dist/esm/modules/logger/hf/flusher.js.map +1 -1
  44. package/dist/esm/modules/logger/hf/logger.d.ts +6 -7
  45. package/dist/esm/modules/logger/hf/logger.js.map +1 -1
  46. package/dist/esm/modules/logger/pino/backing.js.map +1 -1
  47. package/dist/esm/modules/logger/pino/destination.d.ts +1 -1
  48. package/dist/esm/modules/logger/pino/destination.js.map +1 -1
  49. package/dist/esm/modules/logger/pino/logger.d.ts +1 -2
  50. package/dist/esm/modules/logger/pino/logger.js.map +1 -1
  51. package/dist/esm/modules/logger/winston/formats.js +2 -2
  52. package/dist/esm/modules/logger/winston/formats.js.map +1 -1
  53. package/dist/esm/modules/logger/winston/logger.d.ts +1 -2
  54. package/dist/esm/modules/logger/winston/logger.js.map +1 -1
  55. package/dist/esm/modules/logger/winston/transports/dgram.transport.d.ts +1 -1
  56. package/dist/esm/modules/logger/winston/transports/dgram.transport.js +1 -1
  57. package/dist/esm/modules/logger/winston/transports/dgram.transport.js.map +1 -1
  58. package/dist/esm/modules/network/http-request/common/constants.d.ts +0 -2
  59. package/dist/esm/modules/network/http-request/common/constants.js +0 -4
  60. package/dist/esm/modules/network/http-request/common/constants.js.map +1 -1
  61. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +6 -6
  62. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  63. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +2 -3
  64. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  65. package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +1 -1
  66. package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
  67. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +1 -2
  68. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +5 -6
  69. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
  70. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.d.ts +4 -4
  71. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js +1 -1
  72. package/dist/esm/modules/network/tcp-socket/base-tcp-client.helper.js.map +1 -1
  73. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.d.ts +3 -5
  74. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js +0 -8
  75. package/dist/esm/modules/network/tcp-socket/base-tcp-server.helper.js.map +1 -1
  76. package/dist/esm/modules/network/utilities/query-string.d.ts +2 -2
  77. package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
  78. package/dist/esm/modules/network/utilities/url-safety/common/constants.d.ts +0 -2
  79. package/dist/esm/modules/network/utilities/url-safety/common/constants.js +0 -4
  80. package/dist/esm/modules/network/utilities/url-safety/common/constants.js.map +1 -1
  81. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +1 -1
  82. package/dist/esm/modules/queue/bullmq/helper.d.ts +23 -10
  83. package/dist/esm/modules/queue/bullmq/helper.js +57 -10
  84. package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
  85. package/dist/esm/modules/queue/common/constants.d.ts +6 -2
  86. package/dist/esm/modules/queue/common/constants.js +6 -4
  87. package/dist/esm/modules/queue/common/constants.js.map +1 -1
  88. package/dist/esm/modules/queue/internal/sequential/common/types.d.ts +2 -4
  89. package/dist/esm/modules/queue/internal/sequential/common/types.js +0 -4
  90. package/dist/esm/modules/queue/internal/sequential/common/types.js.map +1 -1
  91. package/dist/esm/modules/queue/kafka/base.d.ts +1 -1
  92. package/dist/esm/modules/queue/kafka/base.js +13 -2
  93. package/dist/esm/modules/queue/kafka/base.js.map +1 -1
  94. package/dist/esm/modules/queue/kafka/common/constants.d.ts +0 -4
  95. package/dist/esm/modules/queue/kafka/common/constants.js +0 -8
  96. package/dist/esm/modules/queue/kafka/common/constants.js.map +1 -1
  97. package/dist/esm/modules/redis/base/abstract.helper.d.ts +13 -2
  98. package/dist/esm/modules/redis/base/abstract.helper.js +53 -45
  99. package/dist/esm/modules/redis/base/abstract.helper.js.map +1 -1
  100. package/dist/esm/modules/redis/cluster/cluster.helper.d.ts +1 -2
  101. package/dist/esm/modules/redis/cluster/cluster.helper.js +21 -9
  102. package/dist/esm/modules/redis/cluster/cluster.helper.js.map +1 -1
  103. package/dist/esm/modules/redis/cluster/index.d.ts +1 -0
  104. package/dist/esm/modules/redis/cluster/index.js +1 -0
  105. package/dist/esm/modules/redis/cluster/index.js.map +1 -1
  106. package/dist/esm/modules/redis/cluster/types.d.ts +20 -0
  107. package/dist/esm/modules/redis/cluster/types.js +2 -0
  108. package/dist/esm/modules/redis/cluster/types.js.map +1 -0
  109. package/dist/esm/modules/redis/common/constants.d.ts +15 -19
  110. package/dist/esm/modules/redis/common/constants.js +16 -18
  111. package/dist/esm/modules/redis/common/constants.js.map +1 -1
  112. package/dist/esm/modules/redis/common/types.d.ts +10 -60
  113. package/dist/esm/modules/redis/common/types.js.map +1 -1
  114. package/dist/esm/modules/redis/factory.d.ts +7 -25
  115. package/dist/esm/modules/redis/factory.js +9 -18
  116. package/dist/esm/modules/redis/factory.js.map +1 -1
  117. package/dist/esm/modules/redis/sentinel/constants.d.ts +14 -0
  118. package/dist/esm/modules/redis/sentinel/constants.js +11 -0
  119. package/dist/esm/modules/redis/sentinel/constants.js.map +1 -0
  120. package/dist/esm/modules/redis/sentinel/index.d.ts +2 -0
  121. package/dist/esm/modules/redis/sentinel/index.js +2 -0
  122. package/dist/esm/modules/redis/sentinel/index.js.map +1 -1
  123. package/dist/esm/modules/redis/sentinel/sentinel.helper.d.ts +1 -2
  124. package/dist/esm/modules/redis/sentinel/sentinel.helper.js +25 -15
  125. package/dist/esm/modules/redis/sentinel/sentinel.helper.js.map +1 -1
  126. package/dist/esm/modules/redis/sentinel/types.d.ts +26 -0
  127. package/dist/esm/modules/redis/sentinel/types.js +2 -0
  128. package/dist/esm/modules/redis/sentinel/types.js.map +1 -0
  129. package/dist/esm/modules/redis/single/index.d.ts +1 -0
  130. package/dist/esm/modules/redis/single/index.js +1 -0
  131. package/dist/esm/modules/redis/single/index.js.map +1 -1
  132. package/dist/esm/modules/redis/single/single.helper.d.ts +1 -2
  133. package/dist/esm/modules/redis/single/single.helper.js +5 -6
  134. package/dist/esm/modules/redis/single/single.helper.js.map +1 -1
  135. package/dist/esm/modules/redis/single/types.d.ts +15 -0
  136. package/dist/esm/modules/redis/single/types.js +2 -0
  137. package/dist/esm/modules/redis/single/types.js.map +1 -0
  138. package/dist/esm/modules/secrets/base/abstract.helper.js +6 -1
  139. package/dist/esm/modules/secrets/base/abstract.helper.js.map +1 -1
  140. package/dist/esm/modules/secrets/common/types/registration.d.ts +25 -6
  141. package/dist/esm/modules/secrets/common/types/registration.js.map +1 -1
  142. package/dist/esm/modules/secrets/dotenv/dotenv.helper.js +1 -1
  143. package/dist/esm/modules/secrets/dotenv/dotenv.helper.js.map +1 -1
  144. package/dist/esm/modules/secrets/factory.js +7 -6
  145. package/dist/esm/modules/secrets/factory.js.map +1 -1
  146. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.d.ts +12 -10
  147. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js +50 -25
  148. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
  149. package/dist/esm/modules/socket/socket-io/client/browser-helper.js.map +1 -1
  150. package/dist/esm/modules/socket/socket-io/common/types/client.d.ts +2 -2
  151. package/dist/esm/modules/socket/socket-io/common/types/client.js.map +1 -1
  152. package/dist/esm/modules/socket/socket-io/common/types/server.d.ts +3 -1
  153. package/dist/esm/modules/socket/socket-io/common/types/server.js.map +1 -1
  154. package/dist/esm/modules/socket/socket-io/server/helper.d.ts +2 -2
  155. package/dist/esm/modules/socket/socket-io/server/helper.js.map +1 -1
  156. package/dist/esm/modules/storage/base.d.ts +24 -60
  157. package/dist/esm/modules/storage/base.js +66 -123
  158. package/dist/esm/modules/storage/base.js.map +1 -1
  159. package/dist/esm/modules/storage/bun-s3/helper.d.ts +21 -35
  160. package/dist/esm/modules/storage/bun-s3/helper.js +126 -128
  161. package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
  162. package/dist/esm/modules/storage/bun-s3/utility.d.ts +13 -7
  163. package/dist/esm/modules/storage/bun-s3/utility.js +63 -45
  164. package/dist/esm/modules/storage/bun-s3/utility.js.map +1 -1
  165. package/dist/esm/modules/storage/common/constants.d.ts +29 -2
  166. package/dist/esm/modules/storage/common/constants.js +29 -4
  167. package/dist/esm/modules/storage/common/constants.js.map +1 -1
  168. package/dist/esm/modules/storage/common/errors.d.ts +9 -0
  169. package/dist/esm/modules/storage/common/errors.js +9 -0
  170. package/dist/esm/modules/storage/common/errors.js.map +1 -1
  171. package/dist/esm/modules/storage/common/types.d.ts +90 -61
  172. package/dist/esm/modules/storage/common/types.js.map +1 -1
  173. package/dist/esm/modules/storage/common/utility.d.ts +8 -0
  174. package/dist/esm/modules/storage/common/utility.js +14 -2
  175. package/dist/esm/modules/storage/common/utility.js.map +1 -1
  176. package/dist/esm/modules/storage/disk/helper.d.ts +3 -8
  177. package/dist/esm/modules/storage/disk/helper.js +1 -0
  178. package/dist/esm/modules/storage/disk/helper.js.map +1 -1
  179. package/dist/esm/modules/storage/in-memory/helper.d.ts +2 -3
  180. package/dist/esm/modules/storage/in-memory/helper.js.map +1 -1
  181. package/dist/esm/modules/worker-thread/common/types.d.ts +2 -2
  182. package/dist/esm/modules/worker-thread/common/types.js.map +1 -1
  183. package/dist/esm/modules/worker-thread/thread/abstract.d.ts +2 -2
  184. package/dist/esm/modules/worker-thread/thread/abstract.js.map +1 -1
  185. package/dist/esm/modules/worker-thread/worker-pool.d.ts +1 -1
  186. package/dist/esm/modules/worker-thread/worker-pool.js.map +1 -1
  187. package/dist/esm/utilities/module.utility.d.ts +8 -5
  188. package/dist/esm/utilities/module.utility.js +5 -1
  189. package/dist/esm/utilities/module.utility.js.map +1 -1
  190. package/dist/esm/utilities/parse.utility.d.ts +34 -6
  191. package/dist/esm/utilities/parse.utility.js +82 -15
  192. package/dist/esm/utilities/parse.utility.js.map +1 -1
  193. package/dist/esm/utilities/performance.utility.d.ts +3 -3
  194. package/dist/esm/utilities/performance.utility.js.map +1 -1
  195. package/dist/esm/utilities/promise.utility.d.ts +1 -1
  196. package/dist/esm/utilities/promise.utility.js.map +1 -1
  197. package/dist/esm/utilities/request.utility.d.ts +9 -11
  198. package/dist/esm/utilities/request.utility.js.map +1 -1
  199. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"base-tcp-client.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-client.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAW5C,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAmC5B,oKAAoK;AACpK,MAAM,OAAO,oBAGX,SAAQ,UAAU;IAuBlB,YAAY,IAAmE;QAC7E,KAAK,CAAC;YACJ,KAAK,EAAE,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,UAAU,IAAI,oBAAoB,CAAC,IAAI;YACjE,UAAU,EAAE,IAAI,CAAC,UAAU;SAC5B,CAAC,CAAC;QAtBK,UAAK,GAAuD;YACpE,YAAY,EAAE,iBAAiB;YAC/B,gBAAgB,EAAE,CAAC;SACpB,CAAC;QAoBA,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5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AqB,EAAE,IAAI,EAAE,CAAC,CAAC;IAChD,CAAC;IAED,WAAW;QACT,OAAO,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,KAAK,QAAQ,CAAC;IAC5D,CAAC;IAED,IAAI,CAAC,IAAkC;QACrC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CAAC,wCAAwC,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAEnE,OAAO;QACT,CAAC;QAED,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEzB,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;YACrB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;iBACnB,IAAI,CAAC,8CAA8C,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YAEzE,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC7B,CAAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-inversion';\nimport { RedactUtility } from '@/common/redact';\nimport { BaseHelper } from '@/modules/base';\nimport { type ValueOrPromise } from '@/common';\nimport {\n type TcpSocketConnectOpts as PlainConnectionOptions,\n type Socket as PlainSocketClient,\n} from 'node:net';\nimport {\n type ConnectionOptions as TlsConnectionOptions,\n type TLSSocket as TlsSocketClient,\n} from 'node:tls';\n\nconst DEFAULT_MAX_RETRY = 5;\n\n/** Options of a TCP client. `createClientFn` opens the socket, so one client type serves plain and TLS. */\nexport interface INetworkTcpClientProps<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> {\n identifier: string;\n scope?: string;\n\n options: SocketClientOptions;\n /**\n * Retries after a close, up to `maxRetry` times.\n * @default false\n */\n reconnect?: boolean;\n /**\n * How many reconnects `reconnect` attempts.\n * @default 5\n */\n maxRetry?: number;\n /** When set, `onData` receives strings in this encoding instead of buffers. */\n encoding?: BufferEncoding;\n\n createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n onConnected?: (opts: { client: SocketClientType }) => ValueOrPromise<void>;\n onData?: (opts: { identifier: string; message: string | Buffer }) => ValueOrPromise<void>;\n onClosed?: (opts: { client: SocketClientType }) => void;\n onError?: (error: any) => void;\n}\n\n/** TCP or TLS client that opens its socket through `createClientFn`, reports connect, data, close and error to the `on*` callbacks, and reconnects when enabled. */\nexport class BaseNetworkTcpClient<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> extends BaseHelper {\n protected client?: SocketClientType | null;\n\n protected options: SocketClientOptions;\n protected reconnect?: boolean;\n protected retry: { maxReconnect: number; currentReconnect: number } = {\n maxReconnect: DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n protected reconnectTimeout: any;\n protected encoding?: BufferEncoding;\n\n protected createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n protected onConnected: (opts: { client: SocketClientType }) => void;\n protected onData: (opts: { identifier: string; message: string | Buffer }) => void;\n protected onClosed?: (opts: { client: SocketClientType }) => void;\n protected onError?: (error: any) => void;\n\n constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpClient.name,\n identifier: opts.identifier,\n });\n this.options = opts.options;\n\n this.retry = {\n maxReconnect: opts.maxRetry ?? DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n this.createClientFn = opts.createClientFn;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.reconnect = opts?.reconnect ?? false;\n this.encoding = opts?.encoding;\n }\n\n getClient() {\n return this.client;\n }\n\n /** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */\n protected getLoggableOptions(): unknown {\n return RedactUtility.redactSecrets({ value: this.options });\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info(\n '[%s] Connected to TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n this.retry.currentReconnect = 0;\n }\n\n handleData(_opts: { identifier: string; message: string | Buffer }) {}\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Closed connection TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n }\n\n handleError(error: any) {\n this.logger\n .for(this.handleError.name)\n .error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n this.getLoggableOptions(),\n error,\n );\n\n if (!this.reconnect || this.retry.currentReconnect >= this.retry.maxReconnect) {\n return;\n }\n\n const { currentReconnect, maxReconnect } = this.retry;\n\n if (maxReconnect > -1 && currentReconnect >= maxReconnect) {\n this.logger\n .for(this.handleData.name)\n .info(\n 'Exceeded max retry to reconnect! Max: %d | Current: %d',\n maxReconnect,\n currentReconnect,\n );\n\n return;\n }\n\n this.reconnectTimeout = setTimeout(() => {\n this.client?.destroy();\n this.client = null;\n\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Retrying to establish TCP Connection | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n this.connect({ resetReconnectCounter: false });\n this.retry.currentReconnect++;\n }, 5000);\n }\n\n connect(opts: { resetReconnectCounter: boolean }) {\n if (this.isConnected()) {\n this.logger\n .for(this.connect.name)\n .info('[%s] NetworkTcpClient is already initialized!', this.identifier);\n\n return;\n }\n\n if (ObjectUtility.isEmpty({ value: this.options })) {\n this.logger\n .for(this.connect.name)\n .info('[%s] Cannot init TCP Client with null options', this.identifier);\n\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network tcp client | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n if (opts?.resetReconnectCounter) {\n this.retry.currentReconnect = 0;\n }\n\n if (this.client !== null && this.client !== undefined) {\n this.client?.destroy();\n this.client = null;\n }\n\n // The listeners close over THIS socket: `this.client` is nulled by disconnect() and swapped by a reconnect, so reading it back would drop the close hook - or hand it the wrong socket.\n const client = this.createClientFn(this.options, () => {\n this.onConnected?.({ client });\n });\n\n this.client = client;\n\n if (this.encoding) {\n client.setEncoding(this.encoding);\n }\n\n client.on('data', (message: string | Buffer) => {\n this.onData({ identifier: this.identifier, message });\n });\n\n client.on('close', () => {\n this.onClosed?.({ client });\n });\n\n client.on('error', (error) => {\n this.onError?.(error);\n });\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is not initialized yet!', this.identifier);\n\n return;\n }\n\n this.client?.destroy();\n this.client = null;\n\n clearTimeout(this.reconnectTimeout);\n this.reconnectTimeout = null;\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is destroyed!', this.identifier);\n }\n\n forceReconnect() {\n this.disconnect();\n this.connect({ resetReconnectCounter: true });\n }\n\n isConnected() {\n return this.client && this.client.readyState !== 'closed';\n }\n\n emit(opts: { payload: Buffer | string }) {\n if (!this.client) {\n this.logger\n .for(this.emit.name)\n .info('[%s] TPC Client is not configured yet!', this.identifier);\n\n return;\n }\n\n const { payload } = opts;\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info('[%s] Invalid payload to write to TCP Socket!', this.identifier);\n\n return;\n }\n\n this.client.write(payload);\n }\n}\n"]}
1
+ {"version":3,"file":"base-tcp-client.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-client.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE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AAC;CACF","sourcesContent":["import { ObjectUtility } from '@venizia/ignis-inversion';\nimport { RedactUtility } from '@/common/redact';\nimport { BaseHelper } from '@/modules/base';\nimport { type ValueOrPromise } from '@/common';\nimport {\n type TcpSocketConnectOpts as PlainConnectionOptions,\n type Socket as PlainSocketClient,\n} from 'node:net';\nimport {\n type ConnectionOptions as TlsConnectionOptions,\n type TLSSocket as TlsSocketClient,\n} from 'node:tls';\n\nconst DEFAULT_MAX_RETRY = 5;\n\n/** Options of a TCP client. `createClientFn` opens the socket, so one client type serves plain and TLS. */\nexport interface INetworkTcpClientProps<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> {\n identifier: string;\n scope?: string;\n\n options: SocketClientOptions;\n /**\n * Retries after a close, up to `maxRetry` times.\n * @default false\n */\n reconnect?: boolean;\n /**\n * How many reconnects `reconnect` attempts.\n * @default 5\n */\n maxRetry?: number;\n /** When set, `onData` receives strings in this encoding instead of buffers. */\n encoding?: BufferEncoding;\n\n createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n onConnected?: (opts: { client: SocketClientType }) => ValueOrPromise<void>;\n onData?: (opts: { identifier: string; message: string | Buffer }) => ValueOrPromise<void>;\n onClosed?: (opts: { client: SocketClientType }) => void;\n onError?: (error: unknown) => void;\n}\n\n/** TCP or TLS client that opens its socket through `createClientFn`, reports connect, data, close and error to the `on*` callbacks, and reconnects when enabled. */\nexport class BaseNetworkTcpClient<\n SocketClientOptions extends PlainConnectionOptions | TlsConnectionOptions,\n SocketClientType extends PlainSocketClient | TlsSocketClient,\n> extends BaseHelper {\n protected client?: SocketClientType | null;\n\n protected options: SocketClientOptions;\n protected reconnect?: boolean;\n protected retry: { maxReconnect: number; currentReconnect: number } = {\n maxReconnect: DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n protected reconnectTimeout?: ReturnType<typeof setTimeout> | null;\n protected encoding?: BufferEncoding;\n\n protected createClientFn: (\n options: SocketClientOptions,\n connectionListener?: () => void,\n ) => SocketClientType;\n\n protected onConnected: (opts: { client: SocketClientType }) => void;\n protected onData: (opts: { identifier: string; message: string | Buffer }) => void;\n protected onClosed?: (opts: { client: SocketClientType }) => void;\n protected onError?: (error: unknown) => void;\n\n constructor(opts: INetworkTcpClientProps<SocketClientOptions, SocketClientType>) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpClient.name,\n identifier: opts.identifier,\n });\n this.options = opts.options;\n\n this.retry = {\n maxReconnect: opts.maxRetry ?? DEFAULT_MAX_RETRY,\n currentReconnect: 0,\n };\n\n this.createClientFn = opts.createClientFn;\n\n this.onConnected = opts?.onConnected ?? this.handleConnected;\n this.onData = opts?.onData ?? this.handleData;\n this.onClosed = opts?.onClosed ?? this.handleClosed;\n this.onError = opts?.onError ?? this.handleError;\n this.reconnect = opts?.reconnect ?? false;\n this.encoding = opts?.encoding;\n }\n\n getClient() {\n return this.client;\n }\n\n /** Redacts before logging - a TLS client's options ARE its private key (`key`/`cert`/`passphrase`). */\n protected getLoggableOptions(): unknown {\n return RedactUtility.redactSecrets({ value: this.options });\n }\n\n handleConnected() {\n this.logger\n .for(this.handleConnected.name)\n .info(\n '[%s] Connected to TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n this.retry.currentReconnect = 0;\n }\n\n handleData(_opts: { identifier: string; message: string | Buffer }) {}\n\n handleClosed() {\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Closed connection TCP Server | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n }\n\n handleError(error: unknown) {\n this.logger\n .for(this.handleError.name)\n .error(\n '[%s] Connection error | Options: %j | Error: %s',\n this.identifier,\n this.getLoggableOptions(),\n error,\n );\n\n if (!this.reconnect || this.retry.currentReconnect >= this.retry.maxReconnect) {\n return;\n }\n\n const { currentReconnect, maxReconnect } = this.retry;\n\n if (maxReconnect > -1 && currentReconnect >= maxReconnect) {\n this.logger\n .for(this.handleData.name)\n .info(\n 'Exceeded max retry to reconnect! Max: %d | Current: %d',\n maxReconnect,\n currentReconnect,\n );\n\n return;\n }\n\n this.reconnectTimeout = setTimeout(() => {\n this.client?.destroy();\n this.client = null;\n\n this.logger\n .for(this.handleClosed.name)\n .info(\n '[%s] Retrying to establish TCP Connection | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n this.connect({ resetReconnectCounter: false });\n this.retry.currentReconnect++;\n }, 5000);\n }\n\n connect(opts: { resetReconnectCounter: boolean }) {\n if (this.isConnected()) {\n this.logger\n .for(this.connect.name)\n .info('[%s] NetworkTcpClient is already initialized!', this.identifier);\n\n return;\n }\n\n if (ObjectUtility.isEmpty({ value: this.options })) {\n this.logger\n .for(this.connect.name)\n .info('[%s] Cannot init TCP Client with null options', this.identifier);\n\n return;\n }\n\n this.logger\n .for(this.connect.name)\n .info(\n '[%s] New network tcp client | Options: %j',\n this.identifier,\n this.getLoggableOptions(),\n );\n\n if (opts?.resetReconnectCounter) {\n this.retry.currentReconnect = 0;\n }\n\n if (this.client !== null && this.client !== undefined) {\n this.client?.destroy();\n this.client = null;\n }\n\n // The listeners close over THIS socket: `this.client` is nulled by disconnect() and swapped by a reconnect, so reading it back would drop the close hook - or hand it the wrong socket.\n const client = this.createClientFn(this.options, () => {\n this.onConnected?.({ client });\n });\n\n this.client = client;\n\n if (this.encoding) {\n client.setEncoding(this.encoding);\n }\n\n client.on('data', (message: string | Buffer) => {\n this.onData({ identifier: this.identifier, message });\n });\n\n client.on('close', () => {\n this.onClosed?.({ client });\n });\n\n client.on('error', (error) => {\n this.onError?.(error);\n });\n }\n\n disconnect() {\n if (!this.client) {\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is not initialized yet!', this.identifier);\n\n return;\n }\n\n this.client?.destroy();\n this.client = null;\n\n clearTimeout(this.reconnectTimeout ?? undefined);\n this.reconnectTimeout = null;\n this.logger\n .for(this.disconnect.name)\n .info('[%s] NetworkTcpClient is destroyed!', this.identifier);\n }\n\n forceReconnect() {\n this.disconnect();\n this.connect({ resetReconnectCounter: true });\n }\n\n isConnected() {\n return this.client && this.client.readyState !== 'closed';\n }\n\n emit(opts: { payload: Buffer | string }) {\n if (!this.client) {\n this.logger\n .for(this.emit.name)\n .info('[%s] TPC Client is not configured yet!', this.identifier);\n\n return;\n }\n\n const { payload } = opts;\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info('[%s] Invalid payload to write to TCP Socket!', this.identifier);\n\n return;\n }\n\n this.client.write(payload);\n }\n}\n"]}
@@ -7,8 +7,6 @@ export declare class TcpClientStates {
7
7
  static readonly UNAUTHORIZED = "unauthorized";
8
8
  static readonly AUTHENTICATING = "authenticating";
9
9
  static readonly AUTHENTICATED = "authenticated";
10
- static readonly SCHEME_SET: Set<string>;
11
- static isValid(value: string): boolean;
12
10
  }
13
11
  /** Valid TCP client state values. */
14
12
  export type TTcpClientState = TConstValue<typeof TcpClientStates>;
@@ -22,7 +20,7 @@ export interface ITcpSocketClient<SocketClientType> {
22
20
  connectedAt: Date;
23
21
  authenticatedAt: Date | null;
24
22
  authenticateTimeout?: ReturnType<typeof setTimeout> | null;
25
- [additionField: symbol | string]: any;
23
+ [additionField: symbol | string]: unknown;
26
24
  };
27
25
  }
28
26
  /** Options of `BaseNetworkTcpServer`. With `authenticateOptions.required`, `duration` (milliseconds, greater than 0) is how long a client has to authenticate before its socket is ended; the constructor throws without it. `createServerFn` builds the server, so one class serves plain and TLS. */
@@ -38,7 +36,7 @@ export interface ITcpSocketServerOptions<SocketServerOptions extends ServerOpts
38
36
  extraEvents?: Record<string, (opts: {
39
37
  id: string;
40
38
  socket: SocketClientType;
41
- args: any;
39
+ args: unknown;
42
40
  }) => ValueOrPromise<void>>;
43
41
  createServerFn: (options: Partial<SocketServerOptions>, connectionListener: (socket: SocketClientType) => void) => SocketServerType;
44
42
  onServerReady?: (opts: {
@@ -80,7 +78,7 @@ export declare class BaseNetworkTcpServer<SocketServerOptions extends ServerOpts
80
78
  protected extraEvents: Record<string, (opts: {
81
79
  id: string;
82
80
  socket: SocketClientType;
83
- args: any;
81
+ args: unknown;
84
82
  }) => ValueOrPromise<void>>;
85
83
  protected createServerFn: (options: Partial<SocketServerOptions>, connectionListener: (socket: SocketClientType) => void) => SocketServerType;
86
84
  protected onServerReady?: (opts: {
@@ -7,14 +7,6 @@ export class TcpClientStates {
7
7
  static { this.UNAUTHORIZED = 'unauthorized'; }
8
8
  static { this.AUTHENTICATING = 'authenticating'; }
9
9
  static { this.AUTHENTICATED = 'authenticated'; }
10
- static { this.SCHEME_SET = new Set([
11
- this.UNAUTHORIZED,
12
- this.AUTHENTICATING,
13
- this.AUTHENTICATED,
14
- ]); }
15
- static isValid(value) {
16
- return this.SCHEME_SET.has(value);
17
- }
18
10
  }
19
11
  /** TCP or TLS server that tracks connected clients by id, with an optional authentication window, and reports connection events to the `onClient*` and `onServer*` callbacks. */
20
12
  export class BaseNetworkTcpServer extends BaseHelper {
@@ -1 +1 @@
1
- {"version":3,"file":"base-tcp-server.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAQ7D,6DAA6D;AAC7D,MAAM,OAAO,eAAe;aACV,iBAAY,GAAG,cAAc,CAAC;aAC9B,mBAAc,GAAG,gBAAgB,CAAC;aAClC,kBAAa,GAAG,eAAe,CAAC;aAEhC,eAAU,GAAG,IAAI,GAAG,CAAS;QAC3C,IAAI,CAAC,YAAY;QACjB,IAAI,CAAC,cAAc;QACnB,IAAI,CAAC,aAAa;KACnB,CAAC,CAAC;IAEH,MAAM,CAAC,OA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I,CAAC;iBACnB,IAAI,CACH,0DAA0D,EAC1D,IAAI,CAAC,UAAU,EACf,QAAQ,CACT,CAAC;YAEJ,OAAO;QACT,CAAC;QAED,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { ParseUtility } from '@/utilities/parse.utility';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport {\n type ListenOptions,\n type ServerOpts,\n type Socket as SocketClient,\n type Server as SocketServer,\n} from 'node:net';\n\n/** Where a TCP client is in the authentication handshake. */\nexport class TcpClientStates {\n static readonly UNAUTHORIZED = 'unauthorized';\n static readonly AUTHENTICATING = 'authenticating';\n static readonly AUTHENTICATED = 'authenticated';\n\n static readonly SCHEME_SET = new Set<string>([\n this.UNAUTHORIZED,\n this.AUTHENTICATING,\n this.AUTHENTICATED,\n ]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid TCP client state values. */\nexport type TTcpClientState = TConstValue<typeof TcpClientStates>;\n\n/** A client connected to `BaseNetworkTcpServer`: its `id`, `socket`, authentication `state`, `subscriptions` and `storage` (connect and authenticate times, the pending authenticate timer). */\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: TTcpClientState;\n subscriptions: Set<string>;\n storage: {\n connectedAt: Date;\n authenticatedAt: Date | null;\n authenticateTimeout?: ReturnType<typeof setTimeout> | null;\n [additionField: symbol | string]: any;\n };\n}\n\n/** Options of `BaseNetworkTcpServer`. With `authenticateOptions.required`, `duration` (milliseconds, greater than 0) is how long a client has to authenticate before its socket is ended; the constructor throws without it. `createServerFn` builds the server, so one class serves plain and TLS. */\nexport interface ITcpSocketServerOptions<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> {\n scope?: string;\n identifier: string;\n\n serverOptions: Partial<SocketServerOptions>;\n listenOptions: Partial<ListenOptions>;\n authenticateOptions: { required: boolean; duration?: number };\n\n extraEvents?: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n onServerReady?: (opts: { server: SocketServerType }) => void;\n onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientData?: (opts: { id: string; socket: SocketClientType; data: Buffer | string }) => void;\n onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n}\n\n/** TCP or TLS server that tracks connected clients by id, with an optional authentication window, and reports connection events to the `onClient*` and `onServer*` callbacks. */\nexport class BaseNetworkTcpServer<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> extends BaseHelper {\n protected serverOptions: Partial<SocketServerOptions> = {};\n protected listenOptions: Partial<ListenOptions> = {};\n protected authenticateOptions: { required: boolean; duration?: number };\n\n protected clients: Record<string, ITcpSocketClient<SocketClientType>>;\n protected server: SocketServerType;\n\n protected extraEvents: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: any }) => ValueOrPromise<void>\n >;\n\n protected createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n protected onServerReady?: (opts: { server: SocketServerType }) => void;\n protected onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientData?: (opts: {\n id: string;\n socket: SocketClientType;\n data: Buffer | string;\n }) => void;\n\n protected onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n protected onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n\n constructor(\n opts: ITcpSocketServerOptions<SocketServerOptions, SocketServerType, SocketClientType>,\n ) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpServer.name,\n identifier: opts.identifier,\n });\n\n // No prototype: `getClient({ id: 'constructor' })` must find nothing, not `Object`.\n this.clients = Object.create(null);\n\n this.serverOptions = opts.serverOptions;\n this.listenOptions = opts.listenOptions;\n this.authenticateOptions = opts.authenticateOptions;\n\n if (\n this.authenticateOptions.required &&\n (!this.authenticateOptions.duration || this.authenticateOptions.duration < 0)\n ) {\n throw getError({\n message:\n 'TCP Server | Invalid authenticate duration | Required duration for authenticateOptions',\n });\n }\n\n this.extraEvents = opts.extraEvents ?? {};\n\n this.createServerFn = opts.createServerFn;\n\n this.onServerReady = opts.onServerReady;\n this.onClientConnected = opts.onClientConnected;\n this.onClientData = opts.onClientData;\n this.onClientClose = opts.onClientClose;\n this.onClientError = opts.onClientError;\n this.onServerError = opts.onServerError;\n\n this.configure();\n }\n\n // Hooks run inside socket event listeners: a synchronous throw there is an uncaught exception that kills the process and skips the client-registry cleanup that follows it.\n protected invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n configure() {\n this.server = this.createServerFn(this.serverOptions, (socket) => {\n this.onNewConnection({ socket });\n });\n\n // Without this listener a failed listen - a port already in use is the commonest boot failure there is - emits an unhandled 'error' event, which takes the whole process down with it.\n this.server.on('error', (error: Error) => {\n this.logger\n .for(this.configure.name)\n .error('TCP Socket Server error | Options: %j | Error: %s', this.listenOptions, error);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerError?.({ server: this.server, error });\n },\n });\n });\n\n this.server.listen(this.listenOptions, () => {\n this.logger\n .for(this.configure.name)\n .info('TCP Socket Server is now listening | Options: %j', this.listenOptions);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerReady?.({ server: this.server });\n },\n });\n });\n }\n\n onNewConnection(opts: { socket: SocketClientType }) {\n const { socket } = opts;\n\n const id = ParseUtility.getUID();\n\n socket.on('data', (data: Buffer | string) => {\n this.invokeHook({\n scope: 'onClientData',\n execution: () => {\n this.onClientData?.({ id, socket, data });\n },\n });\n });\n\n socket.on('error', (error: Error) => {\n this.logger.for('onClientConnect').error('Socket Error | ID: %s | Error: %s', id, error);\n\n this.invokeHook({\n scope: 'onClientError',\n execution: () => {\n this.onClientError?.({ id, socket, error });\n },\n });\n\n socket.end();\n });\n\n socket.on('close', (hasError: boolean) => {\n this.logger\n .for('onClientConnect')\n .info('Socket Closed | ID: %s | hasError: %s', id, hasError);\n\n this.invokeHook({\n scope: 'onClientClose',\n execution: () => {\n this.onClientClose?.({ id, socket });\n },\n });\n\n const authenticateTimeout = this.getClient({ id })?.storage?.authenticateTimeout;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n }\n\n // `delete`, not `omit`: omit rebuilds the WHOLE registry per disconnect, so a disconnect\n // storm is O(n^2) - measured at 5000 clients, 2.3s of drain with a 2.2s worst-case stall.\n delete this.clients[id];\n });\n\n for (const extraEvent in this.extraEvents) {\n socket.on(extraEvent, (args) => {\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: 'onClientConnect',\n // The async wrapper turns a SYNCHRONOUS throw from the handler into a rejection; calling it bare would throw out of this listener as an uncaught exception.\n execution: (async () => this.extraEvents[extraEvent]({ id, socket, args }))(),\n });\n });\n }\n\n this.clients[id] = {\n id,\n socket,\n state: this.authenticateOptions.required\n ? TcpClientStates.UNAUTHORIZED\n : TcpClientStates.AUTHENTICATED,\n subscriptions: new Set([]),\n storage: {\n connectedAt: new Date(),\n authenticatedAt: this.authenticateOptions.required ? null : new Date(),\n },\n };\n\n this.logger\n .for('onClientConnect')\n .info(\n 'New TCP SocketClient | Client: %s | authenticateOptions: %s %s',\n `${id} - ${socket.remoteAddress} - ${socket.remotePort} - ${socket.remoteFamily}`,\n this.authenticateOptions.required,\n this.authenticateOptions.duration,\n );\n\n this.invokeHook({\n scope: 'onClientConnected',\n execution: () => {\n this.onClientConnected?.({ id, socket });\n },\n });\n\n if (\n this.authenticateOptions.required &&\n this.authenticateOptions.duration &&\n this.authenticateOptions.duration > 0\n ) {\n const authenticateTimeout = setTimeout(() => {\n const client = this.getClient({ id });\n\n if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === TcpClientStates.AUTHENTICATED) {\n return;\n }\n\n this.emit({ clientId: id, payload: 'Unauthorized Client' });\n client.socket.end();\n }, this.authenticateOptions.duration);\n\n const client = this.getClient({ id });\n\n if (!client) {\n clearTimeout(authenticateTimeout);\n\n return;\n }\n\n client.storage.authenticateTimeout = authenticateTimeout;\n }\n }\n\n getClients() {\n return this.clients;\n }\n\n getClient(opts: { id: string }) {\n return this.clients?.[opts.id];\n }\n\n getServer() {\n return this.server;\n }\n\n /** Clears timers and destroys all client sockets before closing the listener - `server.close()` alone never settles while a socket stays attached. Idempotent; safe if never listened. */\n async shutdown(): Promise<void> {\n const clientsValues = Object.values(this.clients);\n\n for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n client.socket.destroy();\n }\n\n this.clients = Object.create(null);\n\n const server = this.server;\n\n if (!server) {\n return;\n }\n\n // Not guarded on `listening`: listen() is async (DNS lookup), so a shutdown() racing startup could skip close() and leave the server bound forever; close() on a never-listened server just logs ERR_SERVER_NOT_RUNNING below.\n\n await new Promise<void>((resolve) => {\n server.close((error) => {\n if (error) {\n this.logger.for(this.shutdown.name).error('Failed to close server | Error: %s', error);\n }\n\n resolve();\n });\n });\n\n this.logger.for(this.shutdown.name).info('Server closed | Identifier: %s', this.identifier);\n }\n\n doAuthenticate(opts: { id: string; state: TTcpClientState }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case TcpClientStates.UNAUTHORIZED:\n case TcpClientStates.AUTHENTICATING: {\n client.storage.authenticatedAt = null;\n break;\n }\n case TcpClientStates.AUTHENTICATED: {\n client.storage.authenticatedAt = new Date();\n\n if (client.storage.authenticateTimeout) {\n clearTimeout(client.storage.authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n break;\n }\n default: {\n break;\n }\n }\n }\n\n emit(opts: { clientId: string; payload: Buffer | string }) {\n const { clientId, payload } = opts;\n const client = this.getClient({ id: clientId });\n\n if (!client) {\n this.logger.for(this.emit.name).error('Client NOT FOUND | ID: %s', clientId);\n\n return;\n }\n\n const { socket } = client;\n\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\n\n return;\n }\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info(\n '[%s] Client %s | Invalid payload to write to TCP Socket!',\n this.identifier,\n clientId,\n );\n\n return;\n }\n\n socket.write(payload);\n }\n}\n"]}
1
+ {"version":3,"file":"base-tcp-server.helper.js","sourceRoot":"","sources":["../../../../../src/modules/network/tcp-socket/base-tcp-server.helper.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAQ7D,6DAA6D;AAC7D,MAAM,OAAO,eAAe;aACV,iBAAY,GAAG,cAAc,CAAC;aAC9B,mBAAc,GAAG,gBAAgB,CAAC;aAClC,kBAAa,GAAG,eAAe,CAAC;;AAmDlD,iLAAiL;AACjL,MAAM,OAAO,oBAIX,SAAQ,UAAU;IA8BlB,YACE,IA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CACF","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { ParseUtility } from '@/utilities/parse.utility';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport {\n type ListenOptions,\n type ServerOpts,\n type Socket as SocketClient,\n type Server as SocketServer,\n} from 'node:net';\n\n/** Where a TCP client is in the authentication handshake. */\nexport class TcpClientStates {\n static readonly UNAUTHORIZED = 'unauthorized';\n static readonly AUTHENTICATING = 'authenticating';\n static readonly AUTHENTICATED = 'authenticated';\n}\n\n/** Valid TCP client state values. */\nexport type TTcpClientState = TConstValue<typeof TcpClientStates>;\n\n/** A client connected to `BaseNetworkTcpServer`: its `id`, `socket`, authentication `state`, `subscriptions` and `storage` (connect and authenticate times, the pending authenticate timer). */\nexport interface ITcpSocketClient<SocketClientType> {\n id: string;\n socket: SocketClientType;\n state: TTcpClientState;\n subscriptions: Set<string>;\n storage: {\n connectedAt: Date;\n authenticatedAt: Date | null;\n authenticateTimeout?: ReturnType<typeof setTimeout> | null;\n [additionField: symbol | string]: unknown;\n };\n}\n\n/** Options of `BaseNetworkTcpServer`. With `authenticateOptions.required`, `duration` (milliseconds, greater than 0) is how long a client has to authenticate before its socket is ended; the constructor throws without it. `createServerFn` builds the server, so one class serves plain and TLS. */\nexport interface ITcpSocketServerOptions<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> {\n scope?: string;\n identifier: string;\n\n serverOptions: Partial<SocketServerOptions>;\n listenOptions: Partial<ListenOptions>;\n authenticateOptions: { required: boolean; duration?: number };\n\n extraEvents?: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: unknown }) => ValueOrPromise<void>\n >;\n\n createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n onServerReady?: (opts: { server: SocketServerType }) => void;\n onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientData?: (opts: { id: string; socket: SocketClientType; data: Buffer | string }) => void;\n onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n}\n\n/** TCP or TLS server that tracks connected clients by id, with an optional authentication window, and reports connection events to the `onClient*` and `onServer*` callbacks. */\nexport class BaseNetworkTcpServer<\n SocketServerOptions extends ServerOpts = ServerOpts,\n SocketServerType extends SocketServer = SocketServer,\n SocketClientType extends SocketClient = SocketClient,\n> extends BaseHelper {\n protected serverOptions: Partial<SocketServerOptions> = {};\n protected listenOptions: Partial<ListenOptions> = {};\n protected authenticateOptions: { required: boolean; duration?: number };\n\n protected clients: Record<string, ITcpSocketClient<SocketClientType>>;\n protected server: SocketServerType;\n\n protected extraEvents: Record<\n string,\n (opts: { id: string; socket: SocketClientType; args: unknown }) => ValueOrPromise<void>\n >;\n\n protected createServerFn: (\n options: Partial<SocketServerOptions>,\n connectionListener: (socket: SocketClientType) => void,\n ) => SocketServerType;\n\n protected onServerReady?: (opts: { server: SocketServerType }) => void;\n protected onClientConnected?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientData?: (opts: {\n id: string;\n socket: SocketClientType;\n data: Buffer | string;\n }) => void;\n\n protected onClientClose?: (opts: { id: string; socket: SocketClientType }) => void;\n protected onClientError?: (opts: { id: string; socket: SocketClientType; error: Error }) => void;\n protected onServerError?: (opts: { server: SocketServerType; error: Error }) => void;\n\n constructor(\n opts: ITcpSocketServerOptions<SocketServerOptions, SocketServerType, SocketClientType>,\n ) {\n super({\n scope: opts.scope ?? opts.identifier ?? BaseNetworkTcpServer.name,\n identifier: opts.identifier,\n });\n\n // No prototype: `getClient({ id: 'constructor' })` must find nothing, not `Object`.\n this.clients = Object.create(null);\n\n this.serverOptions = opts.serverOptions;\n this.listenOptions = opts.listenOptions;\n this.authenticateOptions = opts.authenticateOptions;\n\n if (\n this.authenticateOptions.required &&\n (!this.authenticateOptions.duration || this.authenticateOptions.duration < 0)\n ) {\n throw getError({\n message:\n 'TCP Server | Invalid authenticate duration | Required duration for authenticateOptions',\n });\n }\n\n this.extraEvents = opts.extraEvents ?? {};\n\n this.createServerFn = opts.createServerFn;\n\n this.onServerReady = opts.onServerReady;\n this.onClientConnected = opts.onClientConnected;\n this.onClientData = opts.onClientData;\n this.onClientClose = opts.onClientClose;\n this.onClientError = opts.onClientError;\n this.onServerError = opts.onServerError;\n\n this.configure();\n }\n\n // Hooks run inside socket event listeners: a synchronous throw there is an uncaught exception that kills the process and skips the client-registry cleanup that follows it.\n protected invokeHook(opts: { scope: string; execution: () => void }) {\n const { scope, execution } = opts;\n\n try {\n execution();\n } catch (error) {\n this.logger.for(scope).error('Hook execution FAILED | Error: %s', error);\n }\n }\n\n configure() {\n this.server = this.createServerFn(this.serverOptions, (socket) => {\n this.onNewConnection({ socket });\n });\n\n // Without this listener a failed listen - a port already in use is the commonest boot failure there is - emits an unhandled 'error' event, which takes the whole process down with it.\n this.server.on('error', (error: Error) => {\n this.logger\n .for(this.configure.name)\n .error('TCP Socket Server error | Options: %j | Error: %s', this.listenOptions, error);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerError?.({ server: this.server, error });\n },\n });\n });\n\n this.server.listen(this.listenOptions, () => {\n this.logger\n .for(this.configure.name)\n .info('TCP Socket Server is now listening | Options: %j', this.listenOptions);\n\n this.invokeHook({\n scope: this.configure.name,\n execution: () => {\n this.onServerReady?.({ server: this.server });\n },\n });\n });\n }\n\n onNewConnection(opts: { socket: SocketClientType }) {\n const { socket } = opts;\n\n const id = ParseUtility.getUID();\n\n socket.on('data', (data: Buffer | string) => {\n this.invokeHook({\n scope: 'onClientData',\n execution: () => {\n this.onClientData?.({ id, socket, data });\n },\n });\n });\n\n socket.on('error', (error: Error) => {\n this.logger.for('onClientConnect').error('Socket Error | ID: %s | Error: %s', id, error);\n\n this.invokeHook({\n scope: 'onClientError',\n execution: () => {\n this.onClientError?.({ id, socket, error });\n },\n });\n\n socket.end();\n });\n\n socket.on('close', (hasError: boolean) => {\n this.logger\n .for('onClientConnect')\n .info('Socket Closed | ID: %s | hasError: %s', id, hasError);\n\n this.invokeHook({\n scope: 'onClientClose',\n execution: () => {\n this.onClientClose?.({ id, socket });\n },\n });\n\n const authenticateTimeout = this.getClient({ id })?.storage?.authenticateTimeout;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n }\n\n // `delete`, not `omit`: omit rebuilds the WHOLE registry per disconnect, so a disconnect\n // storm is O(n^2) - measured at 5000 clients, 2.3s of drain with a 2.2s worst-case stall.\n delete this.clients[id];\n });\n\n for (const extraEvent in this.extraEvents) {\n socket.on(extraEvent, (args) => {\n PromiseUtility.voidExecution({\n logger: this.logger,\n scope: 'onClientConnect',\n // The async wrapper turns a SYNCHRONOUS throw from the handler into a rejection; calling it bare would throw out of this listener as an uncaught exception.\n execution: (async () => this.extraEvents[extraEvent]({ id, socket, args }))(),\n });\n });\n }\n\n this.clients[id] = {\n id,\n socket,\n state: this.authenticateOptions.required\n ? TcpClientStates.UNAUTHORIZED\n : TcpClientStates.AUTHENTICATED,\n subscriptions: new Set([]),\n storage: {\n connectedAt: new Date(),\n authenticatedAt: this.authenticateOptions.required ? null : new Date(),\n },\n };\n\n this.logger\n .for('onClientConnect')\n .info(\n 'New TCP SocketClient | Client: %s | authenticateOptions: %s %s',\n `${id} - ${socket.remoteAddress} - ${socket.remotePort} - ${socket.remoteFamily}`,\n this.authenticateOptions.required,\n this.authenticateOptions.duration,\n );\n\n this.invokeHook({\n scope: 'onClientConnected',\n execution: () => {\n this.onClientConnected?.({ id, socket });\n },\n });\n\n if (\n this.authenticateOptions.required &&\n this.authenticateOptions.duration &&\n this.authenticateOptions.duration > 0\n ) {\n const authenticateTimeout = setTimeout(() => {\n const client = this.getClient({ id });\n\n if (!client) {\n return;\n }\n\n client.storage.authenticateTimeout = null;\n\n if (client.state === TcpClientStates.AUTHENTICATED) {\n return;\n }\n\n this.emit({ clientId: id, payload: 'Unauthorized Client' });\n client.socket.end();\n }, this.authenticateOptions.duration);\n\n const client = this.getClient({ id });\n\n if (!client) {\n clearTimeout(authenticateTimeout);\n\n return;\n }\n\n client.storage.authenticateTimeout = authenticateTimeout;\n }\n }\n\n getClients() {\n return this.clients;\n }\n\n getClient(opts: { id: string }) {\n return this.clients?.[opts.id];\n }\n\n getServer() {\n return this.server;\n }\n\n /** Clears timers and destroys all client sockets before closing the listener - `server.close()` alone never settles while a socket stays attached. Idempotent; safe if never listened. */\n async shutdown(): Promise<void> {\n const clientsValues = Object.values(this.clients);\n\n for (const client of clientsValues) {\n const { authenticateTimeout } = client.storage;\n\n if (authenticateTimeout) {\n clearTimeout(authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n client.socket.destroy();\n }\n\n this.clients = Object.create(null);\n\n const server = this.server;\n\n if (!server) {\n return;\n }\n\n // Not guarded on `listening`: listen() is async (DNS lookup), so a shutdown() racing startup could skip close() and leave the server bound forever; close() on a never-listened server just logs ERR_SERVER_NOT_RUNNING below.\n\n await new Promise<void>((resolve) => {\n server.close((error) => {\n if (error) {\n this.logger.for(this.shutdown.name).error('Failed to close server | Error: %s', error);\n }\n\n resolve();\n });\n });\n\n this.logger.for(this.shutdown.name).info('Server closed | Identifier: %s', this.identifier);\n }\n\n doAuthenticate(opts: { id: string; state: TTcpClientState }) {\n const { id, state } = opts;\n\n const client = this.getClient({ id });\n\n if (!client) {\n this.logger.for('authenticateClient').error('Client NOT FOUND | ID: %s', id);\n\n return;\n }\n\n client.state = state;\n\n switch (state) {\n case TcpClientStates.UNAUTHORIZED:\n case TcpClientStates.AUTHENTICATING: {\n client.storage.authenticatedAt = null;\n break;\n }\n case TcpClientStates.AUTHENTICATED: {\n client.storage.authenticatedAt = new Date();\n\n if (client.storage.authenticateTimeout) {\n clearTimeout(client.storage.authenticateTimeout);\n client.storage.authenticateTimeout = null;\n }\n\n break;\n }\n default: {\n break;\n }\n }\n }\n\n emit(opts: { clientId: string; payload: Buffer | string }) {\n const { clientId, payload } = opts;\n const client = this.getClient({ id: clientId });\n\n if (!client) {\n this.logger.for(this.emit.name).error('Client NOT FOUND | ID: %s', clientId);\n\n return;\n }\n\n const { socket } = client;\n\n if (!socket.writable) {\n this.logger.for(this.emit.name).error('Client NOT WRITABLE | ID: %s', clientId);\n\n return;\n }\n\n if (!payload?.length) {\n this.logger\n .for(this.emit.name)\n .info(\n '[%s] Client %s | Invalid payload to write to TCP Socket!',\n this.identifier,\n clientId,\n );\n\n return;\n }\n\n socket.write(payload);\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type AnyObject, type TConstValue } from '../../../common/types/index.js';
1
+ import { type TConstValue } from '../../../common/types/index.js';
2
2
  /** The punctuation of a query string, named so a reader sees the role rather than the character. */
3
3
  export declare class QueryStringSeparators {
4
4
  /** Between the path and the first pair. */
@@ -58,7 +58,7 @@ export declare class QueryStringUtility {
58
58
  * the trip. Without them the behavior is the one above.
59
59
  */
60
60
  static toQueryString(opts: {
61
- params: AnyObject;
61
+ params: Record<string, unknown>;
62
62
  } & IQueryStringOptions): string;
63
63
  }
64
64
  //# sourceMappingURL=query-string.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"query-string.js","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/query-string.ts"],"names":[],"mappings":"AAEA,oGAAoG;AACpG,MAAM,OAAO,qBAAqB;IAChC,2CAA2C;aAC3B,UAAK,GAAG,GAAG,CAAC;IAC5B,yBAAyB;aACT,SAAI,GAAG,GAAG,CAAC;IAC3B,oCAAoC;aACpB,WAAM,GAAG,GAAG,CAAC;;AAG/B,kDAAkD;AAClD,MAAM,OAAO,uBAAuB;IAClC,2DAA2D;aAC3C,UAAK,GAAG,OAAO,CAAC;IAChC,4BAA4B;aACZ,SAAI,GAAG,MAAM,CAAC;;AAKhC,gDAAgD;AAChD,MAAM,OAA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AI,GAAG,qBAAqB,CAAC,MAAM,GAAG,kBAAkB,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CACrF,CAAC;gBACF,SAAS;YACX,CAAC;YAED,2EAA2E;YAC3E,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;gBACzB,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE,CAAC;oBAC1B,IAAI,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;wBACrB,SAAS;oBACX,CAAC;oBAED,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,qBAAqB,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACvE,CAAC;gBAED,SAAS;YACX,CAAC;YAED,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,qBAAqB,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACvE,CAAC;QAED,OAAO,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;IAChD,CAAC;CACF","sourcesContent":["import { type AnyObject, type TConstValue } from '@/common/types';\n\n/** The punctuation of a query string, named so a reader sees the role rather than the character. */\nexport class QueryStringSeparators {\n /** Between the path and the first pair. */\n static readonly START = '?';\n /** Between two pairs. */\n static readonly PAIR = '&';\n /** Between a name and its value. */\n static readonly ASSIGN = '=';\n}\n\n/** What a `null` or `undefined` value becomes. */\nexport class QueryStringNullishModes {\n /** An empty value (`a=`): what `node:querystring` does. */\n static readonly EMPTY = 'empty';\n /** The pair is left out. */\n static readonly SKIP = 'skip';\n}\n/** What {@link QueryStringNullishModes} selects: `empty` or `skip`. */\nexport type TQueryStringNullishMode = TConstValue<typeof QueryStringNullishModes>;\n\n/** What an object or an array value becomes. */\nexport class QueryStringNestedModes {\n /** An empty value (an array repeats its key instead): what `node:querystring` does. */\n static readonly DROP = 'drop';\n /** One JSON-encoded parameter (`ids=[1,2]`, `filter={\"where\":{}}`), the shape a JSON filter travels in. */\n static readonly JSON = 'json';\n}\n/** What {@link QueryStringNestedModes} selects: `drop` or `json`. */\nexport type TQueryStringNestedMode = TConstValue<typeof QueryStringNestedModes>;\n\n/** How {@link QueryStringUtility.toQueryString} treats the values `node:querystring` has no answer for. */\nexport interface IQueryStringOptions {\n /**\n * What a `null` or `undefined` value becomes.\n * @default QueryStringNullishModes.EMPTY\n */\n nullish?: TQueryStringNullishMode;\n /**\n * What an object or an array value becomes.\n * @default QueryStringNestedModes.DROP\n */\n nested?: TQueryStringNestedMode;\n}\n\n/** Builds a query string without a node builtin, so the network layer stays browser-safe. */\nexport class QueryStringUtility {\n /**\n * `node:querystring`'s `stringify`, written out so nothing on the HTTP path carries a node builtin -\n * that one import is what kept the whole network layer out of a browser bundle.\n *\n * Not `new URLSearchParams(params).toString()`, which differs on four counts measured against the\n * original: an array becomes `a=1%2C2` instead of `a=1&a=2`, `undefined` and `null` become the\n * STRINGS \"undefined\" and \"null\" instead of an empty value, and a space encodes as `+` rather than\n * `%20`. The first changes what a server parses; the second is the same coercion that sends a header\n * reading \"undefined\".\n *\n * Diffed against `node:querystring` across 22 shapes with zero mismatches.\n *\n * `nullish: 'skip'` leaves a null or undefined pair out. `nested: 'json'` sends an object or an\n * array as ONE JSON parameter instead (an array does not repeat its key), so a filter object survives\n * the trip. Without them the behavior is the one above.\n */\n static toQueryString(opts: { params: AnyObject } & IQueryStringOptions): string {\n const {\n params,\n nullish = QueryStringNullishModes.EMPTY,\n nested = QueryStringNestedModes.DROP,\n } = opts;\n const parts: string[] = [];\n const isSkipped = (value: unknown) =>\n nullish === QueryStringNullishModes.SKIP && (value === null || value === undefined);\n const isJson = nested === QueryStringNestedModes.JSON;\n\n // A primitive only. `querystring` drops an object or a nested array to an empty value rather than\n // stringifying it, and a caller that passed one meant something this format cannot carry anyway.\n const encode = (value: unknown) =>\n value === null || value === undefined || typeof value === 'object'\n ? ''\n : encodeURIComponent(String(value));\n\n const entries = Object.entries(params);\n\n for (const [key, value] of entries) {\n const name = encodeURIComponent(key);\n\n if (isSkipped(value)) {\n continue;\n }\n\n if (isJson && typeof value === 'object' && value !== null) {\n parts.push(\n `${name}${QueryStringSeparators.ASSIGN}${encodeURIComponent(JSON.stringify(value))}`,\n );\n continue;\n }\n\n // An array repeats the key, which is what a server reading a list expects.\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (isSkipped(entry)) {\n continue;\n }\n\n parts.push(`${name}${QueryStringSeparators.ASSIGN}${encode(entry)}`);\n }\n\n continue;\n }\n\n parts.push(`${name}${QueryStringSeparators.ASSIGN}${encode(value)}`);\n }\n\n return parts.join(QueryStringSeparators.PAIR);\n }\n}\n"]}
1
+ {"version":3,"file":"query-string.js","sourceRoot":"","sources":["../../../../../src/modules/network/utilities/query-string.ts"],"names":[],"mappings":"AAEA,oGAAoG;AACpG,MAAM,OAAO,qBAAqB;IAChC,2CAA2C;aAC3B,UAAK,GAAG,GAAG,CAAC;IAC5B,yBAAyB;aACT,SAAI,GAAG,GAAG,CAAC;IAC3B,oCAAoC;aACpB,WAAM,GAAG,GAAG,CAAC;;AAG/B,kDAAkD;AAClD,MAAM,OAAO,uBAAuB;IAClC,2DAA2D;aAC3C,UAAK,GAAG,OAAO,CAAC;IAChC,4BAA4B;aACZ,SAAI,GAAG,MAAM,CAAC;;AAKhC,gDAAgD;AAChD,MAAM,OAAO,sBAAsB;IACjC,uFAAuF;aACvE,SAAI,GAAG,MAAM,CAAC;IAC9B,2GAA2G;aAC3F,SAAI,GAAG,MAAM,CAAC;;AAmBhC,6FAA6F;AAC7F,MAAM,OAAO,kBAAkB;IAC7B;;;;;;;;;;;;;;;OAeG;IACH,MAAM,CAAC,aAAa,CAAC,IAA+D;QAClF,MAAM,EACJ,MAAM,EACN,OAAO,GAAG,uBAAuB,CAAC,KAAK,EACvC,MAAM,GAAG,sBAAsB,CAAC,IAAI,GACrC,GAAG,IAAI,CAAC;QACT,MAAM,KAAK,GAAa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AC,GAAG,IAAI,GAAG,qBAAqB,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACvE,CAAC;gBAED,SAAS;YACX,CAAC;YAED,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,qBAAqB,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACvE,CAAC;QAED,OAAO,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;IAChD,CAAC;CACF","sourcesContent":["import { type TConstValue } from '@/common/types';\n\n/** The punctuation of a query string, named so a reader sees the role rather than the character. */\nexport class QueryStringSeparators {\n /** Between the path and the first pair. */\n static readonly START = '?';\n /** Between two pairs. */\n static readonly PAIR = '&';\n /** Between a name and its value. */\n static readonly ASSIGN = '=';\n}\n\n/** What a `null` or `undefined` value becomes. */\nexport class QueryStringNullishModes {\n /** An empty value (`a=`): what `node:querystring` does. */\n static readonly EMPTY = 'empty';\n /** The pair is left out. */\n static readonly SKIP = 'skip';\n}\n/** What {@link QueryStringNullishModes} selects: `empty` or `skip`. */\nexport type TQueryStringNullishMode = TConstValue<typeof QueryStringNullishModes>;\n\n/** What an object or an array value becomes. */\nexport class QueryStringNestedModes {\n /** An empty value (an array repeats its key instead): what `node:querystring` does. */\n static readonly DROP = 'drop';\n /** One JSON-encoded parameter (`ids=[1,2]`, `filter={\"where\":{}}`), the shape a JSON filter travels in. */\n static readonly JSON = 'json';\n}\n/** What {@link QueryStringNestedModes} selects: `drop` or `json`. */\nexport type TQueryStringNestedMode = TConstValue<typeof QueryStringNestedModes>;\n\n/** How {@link QueryStringUtility.toQueryString} treats the values `node:querystring` has no answer for. */\nexport interface IQueryStringOptions {\n /**\n * What a `null` or `undefined` value becomes.\n * @default QueryStringNullishModes.EMPTY\n */\n nullish?: TQueryStringNullishMode;\n /**\n * What an object or an array value becomes.\n * @default QueryStringNestedModes.DROP\n */\n nested?: TQueryStringNestedMode;\n}\n\n/** Builds a query string without a node builtin, so the network layer stays browser-safe. */\nexport class QueryStringUtility {\n /**\n * `node:querystring`'s `stringify`, written out so nothing on the HTTP path carries a node builtin -\n * that one import is what kept the whole network layer out of a browser bundle.\n *\n * Not `new URLSearchParams(params).toString()`, which differs on four counts measured against the\n * original: an array becomes `a=1%2C2` instead of `a=1&a=2`, `undefined` and `null` become the\n * STRINGS \"undefined\" and \"null\" instead of an empty value, and a space encodes as `+` rather than\n * `%20`. The first changes what a server parses; the second is the same coercion that sends a header\n * reading \"undefined\".\n *\n * Diffed against `node:querystring` across 22 shapes with zero mismatches.\n *\n * `nullish: 'skip'` leaves a null or undefined pair out. `nested: 'json'` sends an object or an\n * array as ONE JSON parameter instead (an array does not repeat its key), so a filter object survives\n * the trip. Without them the behavior is the one above.\n */\n static toQueryString(opts: { params: Record<string, unknown> } & IQueryStringOptions): string {\n const {\n params,\n nullish = QueryStringNullishModes.EMPTY,\n nested = QueryStringNestedModes.DROP,\n } = opts;\n const parts: string[] = [];\n const isSkipped = (value: unknown) =>\n nullish === QueryStringNullishModes.SKIP && (value === null || value === undefined);\n const isJson = nested === QueryStringNestedModes.JSON;\n\n // A primitive only. `querystring` drops an object or a nested array to an empty value rather than\n // stringifying it, and a caller that passed one meant something this format cannot carry anyway.\n const encode = (value: unknown) =>\n value === null || value === undefined || typeof value === 'object'\n ? ''\n : encodeURIComponent(String(value));\n\n const entries = Object.entries(params);\n\n for (const [key, value] of entries) {\n const name = encodeURIComponent(key);\n\n if (isSkipped(value)) {\n continue;\n }\n\n if (isJson && typeof value === 'object' && value !== null) {\n parts.push(\n `${name}${QueryStringSeparators.ASSIGN}${encodeURIComponent(JSON.stringify(value))}`,\n );\n continue;\n }\n\n // An array repeats the key, which is what a server reading a list expects.\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (isSkipped(entry)) {\n continue;\n }\n\n parts.push(`${name}${QueryStringSeparators.ASSIGN}${encode(entry)}`);\n }\n\n continue;\n }\n\n parts.push(`${name}${QueryStringSeparators.ASSIGN}${encode(value)}`);\n }\n\n return parts.join(QueryStringSeparators.PAIR);\n }\n}\n"]}
@@ -3,8 +3,6 @@ import { type TConstValue } from '../../../../../common/types/index.js';
3
3
  export declare class UrlSchemes {
4
4
  static readonly HTTP = "http:";
5
5
  static readonly HTTPS = "https:";
6
- static readonly SCHEME_SET: Set<string>;
7
- static isValid(value: string): boolean;
8
6
  }
9
7
  /** A scheme a guarded fetch accepts: `http:` or `https:`. */
10
8
  export type TUrlScheme = TConstValue<typeof UrlSchemes>;
@@ -2,10 +2,6 @@
2
2
  export class UrlSchemes {
3
3
  static { this.HTTP = 'http:'; }
4
4
  static { this.HTTPS = 'https:'; }
5
- static { this.SCHEME_SET = new Set([this.HTTP, this.HTTPS]); }
6
- static isValid(value) {
7
- return this.SCHEME_SET.has(value);
8
- }
9
5
  }
10
6
  /** The values `IUrlSafetyPolicy` uses for a field the caller leaves unset; each is the safe choice. */
11
7
  export class UrlSafetyDefaults {
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/utilities/url-safety/common/constants.ts"],"names":[],"mappings":"AAEA,sGAAsG;AACtG,MAAM,OAAO,UAAU;aACL,SAAI,GAAG,OAAO,CAAC;aACf,UAAK,GAAG,QAAQ,CAAC;aAEjB,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IAEtE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAKH,uGAAuG;AACvG,MAAM,OAAO,iBAAiB;aACZ,oBAAe,GAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;aAC/C,0BAAqB,GAAG,KAAK,CAAC;aAC9B,kBAAa,GAAG,CAAC,CAAC;aAClB,yBAAoB,GAAG,MAAM,CAAC;aAC9B,cAAS,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC","sourcesContent":["import { type TConstValue } from '@/common/types';\n\n/** The only schemes a guarded fetch will speak. `file:` and `gopher:` are the classic SSRF pivots. */\nexport class UrlSchemes {\n static readonly HTTP = 'http:';\n static readonly HTTPS = 'https:';\n\n static readonly SCHEME_SET = new Set<string>([this.HTTP, this.HTTPS]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n/** A scheme a guarded fetch accepts: `http:` or `https:`. */\nexport type TUrlScheme = TConstValue<typeof UrlSchemes>;\n\n/** The values `IUrlSafetyPolicy` uses for a field the caller leaves unset; each is the safe choice. */\nexport class UrlSafetyDefaults {\n static readonly ALLOWED_SCHEMES: string[] = [UrlSchemes.HTTPS];\n static readonly ALLOW_PRIVATE_ADDRESS = false;\n static readonly MAX_REDIRECTS = 3;\n static readonly TIMEOUT_MILLISECONDS = 10_000;\n static readonly MAX_BYTES = 10 * 1024 * 1024;\n}\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../../../src/modules/network/utilities/url-safety/common/constants.ts"],"names":[],"mappings":"AAEA,sGAAsG;AACtG,MAAM,OAAO,UAAU;aACL,SAAI,GAAG,OAAO,CAAC;aACf,UAAK,GAAG,QAAQ,CAAC;;AAKnC,uGAAuG;AACvG,MAAM,OAAO,iBAAiB;aACZ,oBAAe,GAAa,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;aAC/C,0BAAqB,GAAG,KAAK,CAAC;aAC9B,kBAAa,GAAG,CAAC,CAAC;aAClB,yBAAoB,GAAG,MAAM,CAAC;aAC9B,cAAS,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC","sourcesContent":["import { type TConstValue } from '@/common/types';\n\n/** The only schemes a guarded fetch will speak. `file:` and `gopher:` are the classic SSRF pivots. */\nexport class UrlSchemes {\n static readonly HTTP = 'http:';\n static readonly HTTPS = 'https:';\n}\n/** A scheme a guarded fetch accepts: `http:` or `https:`. */\nexport type TUrlScheme = TConstValue<typeof UrlSchemes>;\n\n/** The values `IUrlSafetyPolicy` uses for a field the caller leaves unset; each is the safe choice. */\nexport class UrlSafetyDefaults {\n static readonly ALLOWED_SCHEMES: string[] = [UrlSchemes.HTTPS];\n static readonly ALLOW_PRIVATE_ADDRESS = false;\n static readonly MAX_REDIRECTS = 3;\n static readonly TIMEOUT_MILLISECONDS = 10_000;\n static readonly MAX_BYTES = 10 * 1024 * 1024;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ingest.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/ingest.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,yCAAyC;AAEzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,6EAA6E;AAC7E,MAAM,OAAO,SAAS;IACpB;;;;OAIG;IACH,MAAM,CAAC,KAAK,CAAC,sBAAsB,CAAC,IAInC;QACC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAE1C,IAAI,MAAM,EAAE,mBAAmB,IAAI,iBAAiB,CAAC,qBAAqB,EAAE,CAAC;YAC3E,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,+FAA+F;QAC/F,gGAAgG;QAChG,MAAM,OAAO,GAAG,SAAS,CAAC,eAAe,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QACxD,MAAM,SAAS,GAAG,MAAM,SAAS,CAAC,YAAY,CAAC;YAC7C,IAAI,EAAE,MAAM,CAAC,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AAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC/B,CAAC","sourcesContent":["// The half `policy.ts` cannot do: resolving a hostname needs `node:dns`, so nothing here may be\n// re-exported from the `./core` subpath.\n\nimport { DurationMultipliers } from '@/common/constants/duration';\nimport { getError } from '@/modules/error';\nimport { lookup } from 'node:dns/promises';\nimport { UrlSafetyDefaults } from './common/constants';\nimport { UrlSafetyErrors } from './common/errors';\nimport type { IUrlSafetyPolicy } from './common/types';\nimport { UrlPolicy } from './policy';\n\n/** Fetching an untrusted url without letting it reach inside the network. */\nexport class UrlIngest {\n /**\n * Resolves `hostname` once and returns every address it answered, refusing the host when ANY of them is non-public.\n * Checking only the first walks straight into a host that publishes one public A record beside an internal one.\n * An IP literal answers itself. `allowPrivateAddress` skips the check and returns an empty list: nothing to pin to.\n */\n static async resolvePublicAddresses(opts: {\n hostname: string;\n policy?: IUrlSafetyPolicy;\n signal?: AbortSignal;\n }): Promise<string[]> {\n const { hostname, policy, signal } = opts;\n\n if (policy?.allowPrivateAddress ?? UrlSafetyDefaults.ALLOW_PRIVATE_ADDRESS) {\n return [];\n }\n\n // `URL.hostname` keeps the brackets on an IPv6 literal; `lookup` does not accept them, and the\n // ENOTFOUND that follows reads as a transient DNS failure rather than the refusal it should be.\n const address = UrlPolicy.readHostAddress({ hostname });\n const addresses = await UrlIngest.withDeadline({\n work: lookup(address, { all: true }),\n signal,\n });\n\n if (!addresses.length) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to nothing | host: ${hostname}`,\n });\n }\n\n const offender = addresses.find((entry) =>\n UrlPolicy.isNonPublicAddress({ address: entry.address }),\n );\n\n if (offender) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to a non-public address | host: ${hostname} | address: ${offender.address}`,\n });\n }\n\n return addresses.map((entry) => entry.address);\n }\n\n /**\n * Rejects when ANY resolved address is non-public.\n *\n * A rebinding window remains when this is called on its own: the address can change between this check and a\n * later connect. {@link UrlIngest.fetchGuarded} closes it by connecting to the address it vetted.\n */\n static async assertPublicHost(opts: {\n hostname: string;\n policy?: IUrlSafetyPolicy;\n }): Promise<void> {\n await UrlIngest.resolvePublicAddresses(opts);\n }\n\n /** Both halves, in the order they must run: shape first, then the network. */\n static async assertReachableUrl(opts: { url: string; policy?: IUrlSafetyPolicy }): Promise<URL> {\n const parsed = UrlPolicy.assertSafeUrl(opts);\n await UrlIngest.assertPublicHost({ hostname: parsed.hostname, policy: opts.policy });\n\n return parsed;\n }\n\n private static readTimeoutMilliseconds(opts: { policy?: IUrlSafetyPolicy }): number {\n const { timeout } = opts.policy ?? {};\n const milliseconds = timeout ? DurationMultipliers.toMilliseconds(timeout) : null;\n\n return milliseconds ?? UrlSafetyDefaults.TIMEOUT_MILLISECONDS;\n }\n\n /** Settles with `work`, or rejects with the signal's reason when the deadline passes first: a slow resolver must not outlive it. */\n private static async withDeadline<T>(opts: {\n work: Promise<T>;\n signal?: AbortSignal;\n }): Promise<T> {\n const { work, signal } = opts;\n\n if (!signal) {\n return work;\n }\n\n signal.throwIfAborted();\n\n let onAbort: (() => void) | undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\n try {\n const settled = await Promise.race([work, aborted]);\n\n return settled;\n } finally {\n signal.removeEventListener('abort', onAbort as () => void);\n // The lookup that lost keeps running; its late answer or error must not surface as an unhandled rejection. Nothing\n // is left to report: the caller already got the deadline's error.\n // eslint-disable-next-line venizia/no-silent-catch -- the work lost the race; its outcome is irrelevant by now\n work.catch(() => undefined);\n }\n }\n\n /** Request headers that name the body; they go when a redirect turns the request into a GET. */\n private static readonly BODY_HEADERS = ['content-type', 'content-length', 'content-encoding'];\n\n /**\n * The only caller headers a cross-origin redirect keeps. Every other one is dropped: a tenant's webhook secret\n * (`x-api-key`, a signature) must not follow a redirect to a host that tenant did not name.\n */\n private static readonly CROSS_ORIGIN_HEADERS = ['accept', 'accept-language', 'user-agent'];\n\n /** The statuses that name a new location; a 304 or a 300 is an answer, not a redirect. */\n private static readonly REDIRECT_STATUSES = [301, 302, 303, 307, 308];\n\n /** Connect-phase errors: nothing was sent, so trying the next vetted address cannot deliver a request twice. */\n private static readonly CONNECT_ERROR_CODES = [\n 'ECONNREFUSED',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n 'EADDRNOTAVAIL',\n ];\n\n private static onlyHeaders(opts: {\n headers: Record<string, string>;\n names: string[];\n }): Record<string, string> {\n const { headers, names } = opts;\n\n return Object.fromEntries(\n Object.entries(headers).filter(([name]) => names.includes(name.toLowerCase())),\n );\n }\n\n private static withoutHeaders(opts: {\n headers: Record<string, string>;\n names: string[];\n }): Record<string, string> {\n const { headers, names } = opts;\n\n return Object.fromEntries(\n Object.entries(headers).filter(([name]) => !names.includes(name.toLowerCase())),\n );\n }\n\n /**\n * One request to `target`. With `addresses` it connects to those vetted addresses and nowhere else, in order, and\n * moves to the next one only when the connection itself fails: the url's host is set as the `Host` header, and for\n * https as the TLS server name, so the certificate is still checked against the name the caller asked for.\n */\n private static async send(opts: {\n target: URL;\n addresses: string[];\n init: RequestInit;\n }): Promise<Response> {\n const { target, addresses, init } = opts;\n\n if (!addresses.length) {\n return fetch(target, init);\n }\n\n // `proxy: false` is Bun's way to ignore HTTP_PROXY / HTTPS_PROXY for this call (an empty string or undefined keeps\n // the environment's proxy, which would resolve the name itself and undo the pin). A test pins it.\n const noProxy = { proxy: false } as unknown as RequestInit;\n const isHttps = target.protocol === 'https:';\n const hasNameToVerify =\n isHttps &&\n !UrlPolicy.readHostAddress({ hostname: target.hostname }).includes(':') &&\n !/^[\\d.]+$/.test(target.hostname);\n const headers = {\n ...UrlIngest.withoutHeaders({\n headers: (init.headers as Record<string, string> | undefined) ?? {},\n names: ['host'],\n }),\n Host: target.host,\n };\n let lastError: unknown;\n\n for (const address of addresses) {\n const pinned = new URL(target);\n pinned.hostname = address.includes(':') ? `[${address}]` : address;\n\n try {\n const result = await fetch(pinned, {\n ...init,\n ...noProxy,\n headers,\n ...(hasNameToVerify ? { tls: { serverName: target.hostname } } : {}),\n });\n\n return result;\n } catch (error) {\n const name = (error as Error | undefined)?.name;\n\n // The deadline is not a reason to try another address: it is spent.\n if (name === 'AbortError' || name === 'TimeoutError') {\n throw error;\n }\n\n // A request that may have reached the server (a reset after the body went out) is not repeated on another\n // address unless it is safe to repeat: a webhook must not be delivered twice.\n const code = (error as { code?: string } | undefined)?.code ?? '';\n const method = (init.method ?? 'GET').toUpperCase();\n\n if (\n method !== 'GET' &&\n method !== 'HEAD' &&\n !UrlIngest.CONNECT_ERROR_CODES.includes(code)\n ) {\n throw error;\n }\n\n lastError = error;\n }\n }\n\n throw lastError;\n }\n\n /**\n * A request that an untrusted url cannot steer inside the network. GET by default; `method`, `headers` and `body`\n * (text or bytes, so a redirect can replay it) make it a signed webhook dispatch.\n *\n * The host is resolved ONCE per hop, every answer is checked, and the request connects to those addresses and to no\n * other, so a DNS answer that changes after the check (DNS rebinding) is never looked up again. The `Host` header and,\n * for https, the TLS server name stay the url's own, so the certificate is verified for that name. A `Host` in\n * `headers` is ignored. The environment's `HTTP_PROXY` / `HTTPS_PROXY` is ignored on a pinned\n * connection, because a proxy would resolve the name itself and undo the pin. `policy.proxy` sends the request through a\n * proxy on purpose; that connection is not pinned (see `IUrlSafetyPolicy.proxy`). `allowPrivateAddress` turns the guard,\n * and so the pin, off.\n *\n * Redirects are followed by hand so every hop is re-checked and re-pinned - `redirect: 'follow'` would land on an\n * internal host with no second look. 301, 302 (for a POST) and 303 turn the request into a GET without a body. A 307 or\n * 308 repeats the request; with a body it is refused when it leaves the origin, so a signed payload is never replayed to\n * a host a redirect chose. When a hop changes origin every caller header is dropped except `accept`, `accept-language` and `user-agent`.\n *\n * The body is returned unread: the caller decides whether to stream it onward or cap it with\n * {@link UrlIngest.readCappedBody}. Nothing is buffered here.\n */\n static async fetchGuarded(opts: {\n url: string;\n policy?: IUrlSafetyPolicy;\n method?: string;\n headers?: Record<string, string>;\n body?: string | Uint8Array;\n }): Promise<Response> {\n const { url, policy } = opts;\n const maxRedirects = policy?.maxRedirects ?? UrlSafetyDefaults.MAX_REDIRECTS;\n const timeoutMilliseconds = UrlIngest.readTimeoutMilliseconds({ policy });\n\n let method = (opts.method ?? 'GET').toUpperCase();\n let headers = opts.headers ?? {};\n let body = opts.body;\n\n if (body !== undefined && (method === 'GET' || method === 'HEAD')) {\n throw getError({\n message: `[fetchGuarded] A ${method} request cannot carry a body | url: ${url}`,\n });\n }\n\n let target = UrlPolicy.assertSafeUrl({ url, policy });\n // ONE deadline for the whole call, every lookup and every hop included, not one per hop.\n const signal = AbortSignal.timeout(timeoutMilliseconds);\n\n for (let hop = 0; hop <= maxRedirects; hop += 1) {\n const addresses = await UrlIngest.resolvePublicAddresses({\n hostname: target.hostname,\n policy,\n signal,\n });\n\n const response = await UrlIngest.send({\n target,\n // A proxy resolves the name itself, so there is nothing to pin: the caller chose it (`policy.proxy`).\n addresses: policy?.proxy ? [] : addresses,\n init: {\n method,\n ...(policy?.proxy ? ({ proxy: policy.proxy } as unknown as RequestInit) : {}),\n redirect: 'manual',\n signal,\n ...(Object.keys(headers).length ? { headers } : {}),\n ...(body === undefined ? {} : { body }),\n },\n });\n\n if (!UrlIngest.REDIRECT_STATUSES.includes(response.status)) {\n if (!response.ok) {\n // Cancelled, or the socket stays open on every 4xx and 5xx.\n await response.body?.cancel();\n throw getError({\n message: `[fetchGuarded] Request failed | status: ${response.status} | url: ${url}`,\n });\n }\n\n return response;\n }\n\n const location = response.headers.get('location');\n await response.body?.cancel();\n\n if (!location) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Redirect carried no location | url: ${url}`,\n });\n }\n\n const next = UrlPolicy.assertSafeUrl({ url: new URL(location, target).toString(), policy });\n const isSameOrigin = next.origin === target.origin;\n const becomesGet =\n response.status === 303 ||\n ((response.status === 301 || response.status === 302) && method === 'POST');\n\n if (becomesGet) {\n method = 'GET';\n body = undefined;\n headers = UrlIngest.withoutHeaders({ headers, names: UrlIngest.BODY_HEADERS });\n } else if (body !== undefined && !isSameOrigin) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Redirect would replay the request body to another origin | from: ${target.origin} | to: ${next.origin}`,\n });\n }\n\n if (!isSameOrigin) {\n headers = UrlIngest.onlyHeaders({ headers, names: UrlIngest.CROSS_ORIGIN_HEADERS });\n }\n\n target = next;\n }\n\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Too many redirects | max: ${maxRedirects} | url: ${url}`,\n });\n }\n\n /**\n * Enforces `maxBytes` on a stream nothing reads into this process - the shape a caller wants when\n * the body is piped onward rather than held. Without it a `maxBytes` policy is inert on that path.\n */\n static capStream(opts: {\n source: ReadableStream<Uint8Array>;\n policy?: IUrlSafetyPolicy;\n }): ReadableStream<Uint8Array> {\n const { source } = opts;\n const maxBytes = opts.policy?.maxBytes ?? UrlSafetyDefaults.MAX_BYTES;\n let received = 0;\n\n return source.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n received += chunk.byteLength;\n\n if (received > maxBytes) {\n controller.error(\n getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[capStream] Body exceeds the cap | received: ${received} | max: ${maxBytes}`,\n }),\n );\n\n return;\n }\n\n controller.enqueue(chunk);\n },\n }),\n );\n }\n\n /**\n * Reads a body that must not exceed `maxBytes`, cancelling the moment it does. `content-length` is\n * checked first because it is free, and counted anyway because it may be absent or lie.\n */\n static async readCappedBody(opts: {\n response: Response;\n policy?: IUrlSafetyPolicy;\n }): Promise<Buffer> {\n const { response, policy } = opts;\n const maxBytes = policy?.maxBytes ?? UrlSafetyDefaults.MAX_BYTES;\n\n const declaredLength = Number(response.headers.get('content-length') ?? 0);\n\n if (declaredLength > maxBytes) {\n await response.body?.cancel();\n // The same fact as the streaming branch below, so the same verdict: a caller must not retry an\n // oversized body when the server sends `content-length` and drop it when the server omits one.\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[readCappedBody] Body exceeds the cap | declared: ${declaredLength} | max: ${maxBytes}`,\n });\n }\n\n const reader = response.body?.getReader();\n\n if (!reader) {\n throw getError({ message: '[readCappedBody] Response carried no body' });\n }\n\n const chunks: Uint8Array[] = [];\n let received = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n received += value.length;\n\n if (received > maxBytes) {\n await reader.cancel();\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[readCappedBody] Body exceeds the cap | received: ${received} | max: ${maxBytes}`,\n });\n }\n\n chunks.push(value);\n }\n\n return Buffer.concat(chunks);\n }\n}\n"]}
1
+ {"version":3,"file":"ingest.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/ingest.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,yCAAyC;AAEzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAOrC,6EAA6E;AAC7E,MAAM,OAAO,SAAS;IACpB;;;;OAIG;IACH,MAAM,CAAC,KAAK,CAAC,sBAAsB,CAAC,IAInC;QACC,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAE1C,IAAI,MAAM,EAAE,mBAAmB,IAAI,iBAAiB,CAAC,qBAAqB,EAAE,CAAC;YAC3E,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,+FAA+F;QAC/F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e,CAAC,WAAW;oBAClC,OAAO,EAAE,qDAAqD,QAAQ,WAAW,QAAQ,EAAE;iBAC5F,CAAC,CAAC;YACL,CAAC;YAED,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;QAED,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC/B,CAAC","sourcesContent":["// The half `policy.ts` cannot do: resolving a hostname needs `node:dns`, so nothing here may be\n// re-exported from the `./core` subpath.\n\nimport { DurationMultipliers } from '@/common/constants/duration';\nimport { getError } from '@/modules/error';\nimport { lookup } from 'node:dns/promises';\nimport { UrlSafetyDefaults } from './common/constants';\nimport { UrlSafetyErrors } from './common/errors';\nimport type { IUrlSafetyPolicy } from './common/types';\nimport { UrlPolicy } from './policy';\n\n/** The options Bun's `fetch` takes beyond the standard ones; the standard `RequestInit` does not declare `proxy`. */\ninterface IBunFetchInit extends RequestInit {\n proxy?: string | false;\n}\n\n/** Fetching an untrusted url without letting it reach inside the network. */\nexport class UrlIngest {\n /**\n * Resolves `hostname` once and returns every address it answered, refusing the host when ANY of them is non-public.\n * Checking only the first walks straight into a host that publishes one public A record beside an internal one.\n * An IP literal answers itself. `allowPrivateAddress` skips the check and returns an empty list: nothing to pin to.\n */\n static async resolvePublicAddresses(opts: {\n hostname: string;\n policy?: IUrlSafetyPolicy;\n signal?: AbortSignal;\n }): Promise<string[]> {\n const { hostname, policy, signal } = opts;\n\n if (policy?.allowPrivateAddress ?? UrlSafetyDefaults.ALLOW_PRIVATE_ADDRESS) {\n return [];\n }\n\n // `URL.hostname` keeps the brackets on an IPv6 literal; `lookup` does not accept them, and the\n // ENOTFOUND that follows reads as a transient DNS failure rather than the refusal it should be.\n const address = UrlPolicy.readHostAddress({ hostname });\n const addresses = await UrlIngest.withDeadline({\n work: lookup(address, { all: true }),\n signal,\n });\n\n if (!addresses.length) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to nothing | host: ${hostname}`,\n });\n }\n\n const offender = addresses.find((entry) =>\n UrlPolicy.isNonPublicAddress({ address: entry.address }),\n );\n\n if (offender) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[assertPublicHost] Host resolves to a non-public address | host: ${hostname} | address: ${offender.address}`,\n });\n }\n\n return addresses.map((entry) => entry.address);\n }\n\n /**\n * Rejects when ANY resolved address is non-public.\n *\n * A rebinding window remains when this is called on its own: the address can change between this check and a\n * later connect. {@link UrlIngest.fetchGuarded} closes it by connecting to the address it vetted.\n */\n static async assertPublicHost(opts: {\n hostname: string;\n policy?: IUrlSafetyPolicy;\n }): Promise<void> {\n await UrlIngest.resolvePublicAddresses(opts);\n }\n\n /** Both halves, in the order they must run: shape first, then the network. */\n static async assertReachableUrl(opts: { url: string; policy?: IUrlSafetyPolicy }): Promise<URL> {\n const parsed = UrlPolicy.assertSafeUrl(opts);\n await UrlIngest.assertPublicHost({ hostname: parsed.hostname, policy: opts.policy });\n\n return parsed;\n }\n\n private static readTimeoutMilliseconds(opts: { policy?: IUrlSafetyPolicy }): number {\n const { timeout } = opts.policy ?? {};\n const milliseconds = timeout ? DurationMultipliers.toMilliseconds(timeout) : null;\n\n return milliseconds ?? UrlSafetyDefaults.TIMEOUT_MILLISECONDS;\n }\n\n /** Settles with `work`, or rejects with the signal's reason when the deadline passes first: a slow resolver must not outlive it. */\n private static async withDeadline<T>(opts: {\n work: Promise<T>;\n signal?: AbortSignal;\n }): Promise<T> {\n const { work, signal } = opts;\n\n if (!signal) {\n return work;\n }\n\n signal.throwIfAborted();\n\n let onAbort: (() => void) | undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\n try {\n const settled = await Promise.race([work, aborted]);\n\n return settled;\n } finally {\n signal.removeEventListener('abort', onAbort as () => void);\n // The lookup that lost keeps running; its late answer or error must not surface as an unhandled rejection. Nothing\n // is left to report: the caller already got the deadline's error.\n // eslint-disable-next-line venizia/no-silent-catch -- the work lost the race; its outcome is irrelevant by now\n work.catch(() => undefined);\n }\n }\n\n /** Request headers that name the body; they go when a redirect turns the request into a GET. */\n private static readonly BODY_HEADERS = ['content-type', 'content-length', 'content-encoding'];\n\n /**\n * The only caller headers a cross-origin redirect keeps. Every other one is dropped: a tenant's webhook secret\n * (`x-api-key`, a signature) must not follow a redirect to a host that tenant did not name.\n */\n private static readonly CROSS_ORIGIN_HEADERS = ['accept', 'accept-language', 'user-agent'];\n\n /** The statuses that name a new location; a 304 or a 300 is an answer, not a redirect. */\n private static readonly REDIRECT_STATUSES = [301, 302, 303, 307, 308];\n\n /** Connect-phase errors: nothing was sent, so trying the next vetted address cannot deliver a request twice. */\n private static readonly CONNECT_ERROR_CODES = [\n 'ECONNREFUSED',\n 'ENETUNREACH',\n 'EHOSTUNREACH',\n 'EADDRNOTAVAIL',\n ];\n\n private static onlyHeaders(opts: {\n headers: Record<string, string>;\n names: string[];\n }): Record<string, string> {\n const { headers, names } = opts;\n\n return Object.fromEntries(\n Object.entries(headers).filter(([name]) => names.includes(name.toLowerCase())),\n );\n }\n\n private static withoutHeaders(opts: {\n headers: Record<string, string>;\n names: string[];\n }): Record<string, string> {\n const { headers, names } = opts;\n\n return Object.fromEntries(\n Object.entries(headers).filter(([name]) => !names.includes(name.toLowerCase())),\n );\n }\n\n /**\n * One request to `target`. With `addresses` it connects to those vetted addresses and nowhere else, in order, and\n * moves to the next one only when the connection itself fails: the url's host is set as the `Host` header, and for\n * https as the TLS server name, so the certificate is still checked against the name the caller asked for.\n */\n private static async send(opts: {\n target: URL;\n addresses: string[];\n init: IBunFetchInit;\n }): Promise<Response> {\n const { target, addresses, init } = opts;\n\n if (!addresses.length) {\n return fetch(target, init);\n }\n\n // `proxy: false` is Bun's way to ignore HTTP_PROXY / HTTPS_PROXY for this call (an empty string or undefined keeps\n // the environment's proxy, which would resolve the name itself and undo the pin). A test pins it.\n const noProxy: IBunFetchInit = { proxy: false };\n const isHttps = target.protocol === 'https:';\n const hasNameToVerify =\n isHttps &&\n !UrlPolicy.readHostAddress({ hostname: target.hostname }).includes(':') &&\n !/^[\\d.]+$/.test(target.hostname);\n const headers = {\n ...UrlIngest.withoutHeaders({\n headers: (init.headers as Record<string, string> | undefined) ?? {},\n names: ['host'],\n }),\n Host: target.host,\n };\n let lastError: unknown;\n\n for (const address of addresses) {\n const pinned = new URL(target);\n pinned.hostname = address.includes(':') ? `[${address}]` : address;\n\n try {\n const result = await fetch(pinned, {\n ...init,\n ...noProxy,\n headers,\n ...(hasNameToVerify ? { tls: { serverName: target.hostname } } : {}),\n });\n\n return result;\n } catch (error) {\n const name = (error as Error | undefined)?.name;\n\n // The deadline is not a reason to try another address: it is spent.\n if (name === 'AbortError' || name === 'TimeoutError') {\n throw error;\n }\n\n // A request that may have reached the server (a reset after the body went out) is not repeated on another\n // address unless it is safe to repeat: a webhook must not be delivered twice.\n const code = (error as { code?: string } | undefined)?.code ?? '';\n const method = (init.method ?? 'GET').toUpperCase();\n\n if (\n method !== 'GET' &&\n method !== 'HEAD' &&\n !UrlIngest.CONNECT_ERROR_CODES.includes(code)\n ) {\n throw error;\n }\n\n lastError = error;\n }\n }\n\n throw lastError;\n }\n\n /**\n * A request that an untrusted url cannot steer inside the network. GET by default; `method`, `headers` and `body`\n * (text or bytes, so a redirect can replay it) make it a signed webhook dispatch.\n *\n * The host is resolved ONCE per hop, every answer is checked, and the request connects to those addresses and to no\n * other, so a DNS answer that changes after the check (DNS rebinding) is never looked up again. The `Host` header and,\n * for https, the TLS server name stay the url's own, so the certificate is verified for that name. A `Host` in\n * `headers` is ignored. The environment's `HTTP_PROXY` / `HTTPS_PROXY` is ignored on a pinned\n * connection, because a proxy would resolve the name itself and undo the pin. `policy.proxy` sends the request through a\n * proxy on purpose; that connection is not pinned (see `IUrlSafetyPolicy.proxy`). `allowPrivateAddress` turns the guard,\n * and so the pin, off.\n *\n * Redirects are followed by hand so every hop is re-checked and re-pinned - `redirect: 'follow'` would land on an\n * internal host with no second look. 301, 302 (for a POST) and 303 turn the request into a GET without a body. A 307 or\n * 308 repeats the request; with a body it is refused when it leaves the origin, so a signed payload is never replayed to\n * a host a redirect chose. When a hop changes origin every caller header is dropped except `accept`, `accept-language` and `user-agent`.\n *\n * The body is returned unread: the caller decides whether to stream it onward or cap it with\n * {@link UrlIngest.readCappedBody}. Nothing is buffered here.\n */\n static async fetchGuarded(opts: {\n url: string;\n policy?: IUrlSafetyPolicy;\n method?: string;\n headers?: Record<string, string>;\n body?: string | Uint8Array;\n }): Promise<Response> {\n const { url, policy } = opts;\n const maxRedirects = policy?.maxRedirects ?? UrlSafetyDefaults.MAX_REDIRECTS;\n const timeoutMilliseconds = UrlIngest.readTimeoutMilliseconds({ policy });\n\n let method = (opts.method ?? 'GET').toUpperCase();\n let headers = opts.headers ?? {};\n let body = opts.body;\n\n if (body !== undefined && (method === 'GET' || method === 'HEAD')) {\n throw getError({\n message: `[fetchGuarded] A ${method} request cannot carry a body | url: ${url}`,\n });\n }\n\n let target = UrlPolicy.assertSafeUrl({ url, policy });\n // ONE deadline for the whole call, every lookup and every hop included, not one per hop.\n const signal = AbortSignal.timeout(timeoutMilliseconds);\n\n for (let hop = 0; hop <= maxRedirects; hop += 1) {\n const addresses = await UrlIngest.resolvePublicAddresses({\n hostname: target.hostname,\n policy,\n signal,\n });\n\n const response = await UrlIngest.send({\n target,\n // A proxy resolves the name itself, so there is nothing to pin: the caller chose it (`policy.proxy`).\n addresses: policy?.proxy ? [] : addresses,\n init: {\n method,\n ...(policy?.proxy ? { proxy: policy.proxy } : {}),\n redirect: 'manual',\n signal,\n ...(Object.keys(headers).length ? { headers } : {}),\n ...(body === undefined ? {} : { body }),\n },\n });\n\n if (!UrlIngest.REDIRECT_STATUSES.includes(response.status)) {\n if (!response.ok) {\n // Cancelled, or the socket stays open on every 4xx and 5xx.\n await response.body?.cancel();\n throw getError({\n message: `[fetchGuarded] Request failed | status: ${response.status} | url: ${url}`,\n });\n }\n\n return response;\n }\n\n const location = response.headers.get('location');\n await response.body?.cancel();\n\n if (!location) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Redirect carried no location | url: ${url}`,\n });\n }\n\n const next = UrlPolicy.assertSafeUrl({ url: new URL(location, target).toString(), policy });\n const isSameOrigin = next.origin === target.origin;\n const becomesGet =\n response.status === 303 ||\n ((response.status === 301 || response.status === 302) && method === 'POST');\n\n if (becomesGet) {\n method = 'GET';\n body = undefined;\n headers = UrlIngest.withoutHeaders({ headers, names: UrlIngest.BODY_HEADERS });\n } else if (body !== undefined && !isSameOrigin) {\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Redirect would replay the request body to another origin | from: ${target.origin} | to: ${next.origin}`,\n });\n }\n\n if (!isSameOrigin) {\n headers = UrlIngest.onlyHeaders({ headers, names: UrlIngest.CROSS_ORIGIN_HEADERS });\n }\n\n target = next;\n }\n\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[fetchGuarded] Too many redirects | max: ${maxRedirects} | url: ${url}`,\n });\n }\n\n /**\n * Enforces `maxBytes` on a stream nothing reads into this process - the shape a caller wants when\n * the body is piped onward rather than held. Without it a `maxBytes` policy is inert on that path.\n */\n static capStream(opts: {\n source: ReadableStream<Uint8Array>;\n policy?: IUrlSafetyPolicy;\n }): ReadableStream<Uint8Array> {\n const { source } = opts;\n const maxBytes = opts.policy?.maxBytes ?? UrlSafetyDefaults.MAX_BYTES;\n let received = 0;\n\n return source.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n received += chunk.byteLength;\n\n if (received > maxBytes) {\n controller.error(\n getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[capStream] Body exceeds the cap | received: ${received} | max: ${maxBytes}`,\n }),\n );\n\n return;\n }\n\n controller.enqueue(chunk);\n },\n }),\n );\n }\n\n /**\n * Reads a body that must not exceed `maxBytes`, cancelling the moment it does. `content-length` is\n * checked first because it is free, and counted anyway because it may be absent or lie.\n */\n static async readCappedBody(opts: {\n response: Response;\n policy?: IUrlSafetyPolicy;\n }): Promise<Buffer> {\n const { response, policy } = opts;\n const maxBytes = policy?.maxBytes ?? UrlSafetyDefaults.MAX_BYTES;\n\n const declaredLength = Number(response.headers.get('content-length') ?? 0);\n\n if (declaredLength > maxBytes) {\n await response.body?.cancel();\n // The same fact as the streaming branch below, so the same verdict: a caller must not retry an\n // oversized body when the server sends `content-length` and drop it when the server omits one.\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[readCappedBody] Body exceeds the cap | declared: ${declaredLength} | max: ${maxBytes}`,\n });\n }\n\n const reader = response.body?.getReader();\n\n if (!reader) {\n throw getError({ message: '[readCappedBody] Response carried no body' });\n }\n\n const chunks: Uint8Array[] = [];\n let received = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n received += value.length;\n\n if (received > maxBytes) {\n await reader.cancel();\n throw getError({\n error: UrlSafetyErrors.URL_REFUSED,\n message: `[readCappedBody] Body exceeds the cap | received: ${received} | max: ${maxBytes}`,\n });\n }\n\n chunks.push(value);\n }\n\n return Buffer.concat(chunks);\n }\n}\n"]}
@@ -1,9 +1,9 @@
1
1
  import { BaseHelper } from '../../base.js';
2
- import { type IRedisHelper } from '../../redis/index.js';
2
+ import { type IRedisHelper, type TRedisClient } from '../../redis/index.js';
3
3
  import type { Job, Processor, Queue, QueueOptions, Worker, WorkerOptions } from 'bullmq';
4
4
  import { type TBullQueueRole } from '../common/index.js';
5
5
  /** Options for {@link BullMQHelper}. `role` decides whether a `Queue` or a `Worker` is built. */
6
- export interface IBullMQOptions<TQueueElement = any, TQueueResult = any> {
6
+ export interface IBullMQOptions<TQueueElement = unknown, TQueueResult = unknown> {
7
7
  queueName: string;
8
8
  identifier: string;
9
9
  role: TBullQueueRole;
@@ -12,27 +12,27 @@ export interface IBullMQOptions<TQueueElement = any, TQueueResult = any> {
12
12
  module?: typeof import('bullmq');
13
13
  /**
14
14
  * Worker concurrency.
15
- * @default 1
15
+ * @default BullMQDefaults.NUMBER_OF_WORKER
16
16
  */
17
17
  numberOfWorker?: number;
18
18
  /**
19
19
  * How long a worker holds a job's lock, in milliseconds.
20
- * @default 90 * 60 * 1000
20
+ * @default BullMQDefaults.LOCK_DURATION_MS
21
21
  */
22
22
  lockDuration?: number;
23
23
  /** Merged over the framework defaults, under the fields the helper owns (`connection`) - see `queueOptionsFor`. */
24
24
  queueOptions?: Omit<QueueOptions, 'connection'>;
25
25
  /** Merged under the fields the helper owns (`connection`, `concurrency`, `lockDuration`) - see `workerOptionsFor`. */
26
26
  workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'lockDuration'>;
27
- onWorkerData?: (job: Job<TQueueElement, TQueueResult>) => Promise<any>;
28
- onWorkerDataCompleted?: (job: Job<TQueueElement, TQueueResult>, result: any) => Promise<void>;
27
+ onWorkerData?: (job: Job<TQueueElement, TQueueResult>) => Promise<TQueueResult>;
28
+ onWorkerDataCompleted?: (job: Job<TQueueElement, TQueueResult>, result: TQueueResult) => Promise<void>;
29
29
  onWorkerDataFail?: (job: Job<TQueueElement, TQueueResult> | undefined, error: Error) => Promise<void>;
30
30
  }
31
31
  /**
32
32
  * Wraps a BullMQ `Queue` or `Worker` (per `role`) on one Redis connection.
33
33
  * Worker concurrency is `numberOfWorker`; `lockDuration` is in milliseconds.
34
34
  */
35
- export declare class BullMQHelper<TQueueElement = any, TQueueResult = any> extends BaseHelper {
35
+ export declare class BullMQHelper<TQueueElement = unknown, TQueueResult = unknown> extends BaseHelper {
36
36
  protected queueName: string;
37
37
  protected role: TBullQueueRole;
38
38
  protected redisConnection: IRedisHelper;
@@ -42,12 +42,17 @@ export declare class BullMQHelper<TQueueElement = any, TQueueResult = any> exten
42
42
  protected lockDuration: number;
43
43
  protected queueOptions?: Omit<QueueOptions, 'connection'>;
44
44
  protected workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'lockDuration'>;
45
- protected onWorkerData?: (job: Job<TQueueElement, TQueueResult>) => Promise<any>;
46
- protected onWorkerDataCompleted?: (job: Job<TQueueElement, TQueueResult>, result: any) => Promise<void>;
45
+ protected onWorkerData?: (job: Job<TQueueElement, TQueueResult>) => Promise<TQueueResult>;
46
+ protected onWorkerDataCompleted?: (job: Job<TQueueElement, TQueueResult>, result: TQueueResult) => Promise<void>;
47
47
  protected onWorkerDataFail?: (job: Job<TQueueElement, TQueueResult> | undefined, error: Error) => Promise<void>;
48
48
  private readonly bullmqModule?;
49
+ private isClosing;
50
+ /** Every duplicate this helper handed to BullMQ: BullMQ never quits a client it is given, so `close()` does. */
51
+ private readonly duplicates;
49
52
  constructor(options: IBullMQOptions<TQueueElement, TQueueResult>);
50
- static newInstance<T = any, R = any>(opts: IBullMQOptions<T, R>): BullMQHelper<T, R>;
53
+ /** BullMQ never reconnects a client: once ioredis stops reconnecting (`maxRetry` attempts used up) it is `end` for good, no job moves, and nothing else says so. */
54
+ protected reportClientEnded(): void;
55
+ static newInstance<T = unknown, R = unknown>(opts: IBullMQOptions<T, R>): BullMQHelper<T, R>;
51
56
  /** Structural, never `instanceof`: ioredis is an optional peer, and a second copy fails `instanceof` anyway. */
52
57
  protected isClusterClient(): boolean;
53
58
  protected resolveQueueName(): string;
@@ -56,6 +61,12 @@ export declare class BullMQHelper<TQueueElement = any, TQueueResult = any> exten
56
61
  protected queueOptionsFor(opts: {
57
62
  queueName: string;
58
63
  }): QueueOptions;
64
+ /**
65
+ * The connection BullMQ owns: a duplicate of the helper's client, so the queue or worker connects it by itself
66
+ * whatever state the shared client is in. BullMQ treats a client it is handed as shared and never quits it, so the
67
+ * helper keeps the duplicate and quits it in `close()`.
68
+ */
69
+ protected createConnection(): TRedisClient;
59
70
  /** Full `Worker` options: `this.workerOptions`, then the connection/concurrency/lock fields the helper owns - in that precedence order. */
60
71
  protected workerOptionsFor(opts: {
61
72
  queueName: string;
@@ -74,6 +85,8 @@ export declare class BullMQHelper<TQueueElement = any, TQueueResult = any> exten
74
85
  }): Worker<TQueueElement, TQueueResult>;
75
86
  configureWorker(): void;
76
87
  configure(): void;
88
+ /** `quit()` waits for the replies in flight; a client BullMQ already closed is left alone. */
89
+ private static release;
77
90
  close(): Promise<void>;
78
91
  }
79
92
  //# sourceMappingURL=helper.d.ts.map