@venizia/ignis-helpers 0.4.8-13 → 0.4.8-14

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 (120) hide show
  1. package/dist/esm/common/redact.js.map +1 -1
  2. package/dist/esm/common/types/class.d.ts +14 -12
  3. package/dist/esm/common/types/class.js.map +1 -1
  4. package/dist/esm/common/types/const-value.d.ts +3 -3
  5. package/dist/esm/common/types/const-value.js.map +1 -1
  6. package/dist/esm/common/types/injection.d.ts +1 -1
  7. package/dist/esm/common/types/injection.js.map +1 -1
  8. package/dist/esm/common/types/utility.d.ts +0 -4
  9. package/dist/esm/common/types/utility.js.map +1 -1
  10. package/dist/esm/modules/env/app-env.d.ts +17 -8
  11. package/dist/esm/modules/env/app-env.js +18 -15
  12. package/dist/esm/modules/env/app-env.js.map +1 -1
  13. package/dist/esm/modules/env/common/types.d.ts +22 -6
  14. package/dist/esm/modules/env/common/types.js.map +1 -1
  15. package/dist/esm/modules/logger/base/abstract.d.ts +6 -7
  16. package/dist/esm/modules/logger/base/abstract.js.map +1 -1
  17. package/dist/esm/modules/logger/base/base.d.ts +7 -8
  18. package/dist/esm/modules/logger/base/base.js.map +1 -1
  19. package/dist/esm/modules/logger/base/console.d.ts +6 -7
  20. package/dist/esm/modules/logger/base/console.js.map +1 -1
  21. package/dist/esm/modules/logger/common/types.d.ts +7 -7
  22. package/dist/esm/modules/logger/common/types.js.map +1 -1
  23. package/dist/esm/modules/logger/factory.js.map +1 -1
  24. package/dist/esm/modules/logger/hf/flusher.js.map +1 -1
  25. package/dist/esm/modules/logger/hf/logger.d.ts +6 -7
  26. package/dist/esm/modules/logger/hf/logger.js.map +1 -1
  27. package/dist/esm/modules/logger/pino/backing.js.map +1 -1
  28. package/dist/esm/modules/logger/pino/destination.d.ts +1 -1
  29. package/dist/esm/modules/logger/pino/destination.js.map +1 -1
  30. package/dist/esm/modules/logger/pino/logger.d.ts +1 -2
  31. package/dist/esm/modules/logger/pino/logger.js.map +1 -1
  32. package/dist/esm/modules/logger/winston/formats.js +2 -2
  33. package/dist/esm/modules/logger/winston/formats.js.map +1 -1
  34. package/dist/esm/modules/logger/winston/logger.d.ts +1 -2
  35. package/dist/esm/modules/logger/winston/logger.js.map +1 -1
  36. package/dist/esm/modules/logger/winston/transports/dgram.transport.d.ts +1 -1
  37. package/dist/esm/modules/logger/winston/transports/dgram.transport.js +1 -1
  38. package/dist/esm/modules/logger/winston/transports/dgram.transport.js.map +1 -1
  39. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +5 -5
  40. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  41. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +1 -2
  42. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  43. package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +1 -1
  44. package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
  45. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +1 -2
  46. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +5 -6
  47. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
  48. package/dist/esm/modules/network/utilities/query-string.d.ts +2 -2
  49. package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
  50. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +1 -1
  51. package/dist/esm/modules/queue/kafka/base.d.ts +1 -1
  52. package/dist/esm/modules/queue/kafka/base.js +13 -2
  53. package/dist/esm/modules/queue/kafka/base.js.map +1 -1
  54. package/dist/esm/modules/redis/cluster/cluster.helper.d.ts +1 -1
  55. package/dist/esm/modules/redis/cluster/cluster.helper.js +10 -3
  56. package/dist/esm/modules/redis/cluster/cluster.helper.js.map +1 -1
  57. package/dist/esm/modules/redis/cluster/index.d.ts +1 -0
  58. package/dist/esm/modules/redis/cluster/index.js +1 -0
  59. package/dist/esm/modules/redis/cluster/index.js.map +1 -1
  60. package/dist/esm/modules/redis/cluster/types.d.ts +20 -0
  61. package/dist/esm/modules/redis/cluster/types.js +2 -0
  62. package/dist/esm/modules/redis/cluster/types.js.map +1 -0
  63. package/dist/esm/modules/redis/common/constants.d.ts +2 -8
  64. package/dist/esm/modules/redis/common/constants.js +2 -5
  65. package/dist/esm/modules/redis/common/constants.js.map +1 -1
  66. package/dist/esm/modules/redis/common/types.d.ts +9 -62
  67. package/dist/esm/modules/redis/common/types.js.map +1 -1
  68. package/dist/esm/modules/redis/factory.d.ts +3 -4
  69. package/dist/esm/modules/redis/factory.js.map +1 -1
  70. package/dist/esm/modules/redis/sentinel/constants.d.ts +14 -0
  71. package/dist/esm/modules/redis/sentinel/constants.js +11 -0
  72. package/dist/esm/modules/redis/sentinel/constants.js.map +1 -0
  73. package/dist/esm/modules/redis/sentinel/index.d.ts +2 -0
  74. package/dist/esm/modules/redis/sentinel/index.js +2 -0
  75. package/dist/esm/modules/redis/sentinel/index.js.map +1 -1
  76. package/dist/esm/modules/redis/sentinel/sentinel.helper.d.ts +1 -1
  77. package/dist/esm/modules/redis/sentinel/sentinel.helper.js +18 -9
  78. package/dist/esm/modules/redis/sentinel/sentinel.helper.js.map +1 -1
  79. package/dist/esm/modules/redis/sentinel/types.d.ts +26 -0
  80. package/dist/esm/modules/redis/sentinel/types.js +2 -0
  81. package/dist/esm/modules/redis/sentinel/types.js.map +1 -0
  82. package/dist/esm/modules/redis/single/index.d.ts +1 -0
  83. package/dist/esm/modules/redis/single/index.js +1 -0
  84. package/dist/esm/modules/redis/single/index.js.map +1 -1
  85. package/dist/esm/modules/redis/single/single.helper.d.ts +1 -1
  86. package/dist/esm/modules/redis/single/single.helper.js +1 -1
  87. package/dist/esm/modules/redis/single/single.helper.js.map +1 -1
  88. package/dist/esm/modules/redis/single/types.d.ts +15 -0
  89. package/dist/esm/modules/redis/single/types.js +2 -0
  90. package/dist/esm/modules/redis/single/types.js.map +1 -0
  91. package/dist/esm/modules/secrets/base/abstract.helper.js +6 -1
  92. package/dist/esm/modules/secrets/base/abstract.helper.js.map +1 -1
  93. package/dist/esm/modules/secrets/common/types/registration.d.ts +25 -6
  94. package/dist/esm/modules/secrets/common/types/registration.js.map +1 -1
  95. package/dist/esm/modules/secrets/dotenv/dotenv.helper.js +1 -1
  96. package/dist/esm/modules/secrets/dotenv/dotenv.helper.js.map +1 -1
  97. package/dist/esm/modules/secrets/factory.js +7 -6
  98. package/dist/esm/modules/secrets/factory.js.map +1 -1
  99. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.d.ts +12 -10
  100. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js +50 -25
  101. package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
  102. package/dist/esm/modules/storage/in-memory/helper.d.ts +2 -3
  103. package/dist/esm/modules/storage/in-memory/helper.js.map +1 -1
  104. package/dist/esm/modules/worker-thread/common/types.d.ts +2 -2
  105. package/dist/esm/modules/worker-thread/common/types.js.map +1 -1
  106. package/dist/esm/modules/worker-thread/thread/abstract.d.ts +2 -2
  107. package/dist/esm/modules/worker-thread/thread/abstract.js.map +1 -1
  108. package/dist/esm/modules/worker-thread/worker-pool.d.ts +1 -1
  109. package/dist/esm/modules/worker-thread/worker-pool.js.map +1 -1
  110. package/dist/esm/utilities/module.utility.d.ts +8 -5
  111. package/dist/esm/utilities/module.utility.js +5 -1
  112. package/dist/esm/utilities/module.utility.js.map +1 -1
  113. package/dist/esm/utilities/parse.utility.d.ts +34 -6
  114. package/dist/esm/utilities/parse.utility.js +82 -15
  115. package/dist/esm/utilities/parse.utility.js.map +1 -1
  116. package/dist/esm/utilities/performance.utility.d.ts +3 -3
  117. package/dist/esm/utilities/performance.utility.js.map +1 -1
  118. package/dist/esm/utilities/promise.utility.d.ts +1 -1
  119. package/dist/esm/utilities/promise.utility.js.map +1 -1
  120. package/package.json +3 -3
@@ -1,5 +1,4 @@
1
1
  import { type THttpMethod } from '../../../../common/constants/http.js';
2
- import { type AnyObject } from '../../../../common/types/index.js';
3
2
  import { type IQueryStringOptions } from '../../utilities/query-string.js';
4
3
  import { BaseNetworkRequest } from '../base-network-request.helper.js';
5
4
  import { AbstractNetworkFetchableHelper, type IRequestOptions, type TFetcherLogger } from './base-fetcher.js';
@@ -7,7 +6,7 @@ import { AbstractNetworkFetchableHelper, type IRequestOptions, type TFetcherLogg
7
6
  export interface INodeFetchRequestOptions extends RequestInit, IRequestOptions {
8
7
  url: string;
9
8
  method?: THttpMethod;
10
- params?: AnyObject;
9
+ params?: Record<string, unknown>;
11
10
  }
12
11
  /** Fetcher over the global `fetch` (`getWorker()`). `timeout` (milliseconds) aborts the request and is combined with a `signal` the caller passes. */
13
12
  export declare class NodeFetcher extends AbstractNetworkFetchableHelper<'node-fetch', INodeFetchRequestOptions, Awaited<ReturnType<typeof fetch>>, typeof fetch> {
@@ -93,14 +93,13 @@ export class NodeFetchNetworkRequest extends BaseNetworkRequest {
93
93
  constructor(opts) {
94
94
  const { name, networkOptions } = opts;
95
95
  const { headers, baseUrl, queryString, ...rest } = networkOptions;
96
- const userHeaders = headers instanceof Headers ? Object.fromEntries(headers.entries()) : headers;
97
- const mergedHeaders = {
98
- ['content-type']: 'application/json; charset=utf-8',
99
- ...userHeaders,
100
- };
96
+ // Case-insensitive, like the wire: a caller's `Content-Type` replaces the default one.
97
+ const mergedHeaders = new Headers({ 'content-type': 'application/json; charset=utf-8' });
98
+ new Headers(headers).forEach((value, key) => mergedHeaders.set(key, value));
101
99
  const defaultConfigs = {
102
100
  ...rest,
103
- headers: mergedHeaders,
101
+ // A plain object, so the request log (which redacts by key) can read it; a `Headers` instance has no own entries.
102
+ headers: Object.fromEntries(mergedHeaders),
104
103
  };
105
104
  super({
106
105
  name,
@@ -1 +1 @@
1
- {"version":3,"file":"node-fetcher.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/node-fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CA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gBACd,YAAY,CAAC,SAAS,CAAC,CAAC;YAC1B,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAYD,+HAA+H;AAC/H,MAAM,OAAO,uBAAwB,SAAQ,kBAAgC;IAC3E,YAAY,IAAqC;QAC/C,MAAM,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;QACtC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,IAAI,EAAE,GAAG,cAAc,CAAC;QAElE,MAAM,WAAW,GACf,OAAO,YAAY,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QAC/E,MAAM,aAAa,GAAc;YAC/B,CAAC,cAAc,CAAC,EAAE,iCAAiC;YACnD,GAAG,WAAW;SACf,CAAC;QAEF,MAAM,cAAc,GAAyB;YAC3C,GAAG,IAAI;YACP,OAAO,EAAE,aAAa;SACvB,CAAC;QAEF,KAAK,CAAC;YACJ,IAAI;YACJ,OAAO;YACP,OAAO,EAAE,IAAI,WAAW,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,WAAW,EAAE,CAAC;SAChE,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { RedactUtility } from '@/common/redact';\nimport { HTTP, type THttpMethod } from '@/common/constants/http';\nimport { type AnyObject } from '@/common/types';\nimport {\n type IQueryStringOptions,\n QueryStringSeparators,\n QueryStringUtility,\n} from '../../utilities/query-string';\n\nimport { BaseNetworkRequest } from '../base-network-request.helper';\nimport {\n AbstractNetworkFetchableHelper,\n type IRequestOptions,\n type TFetcherLogger,\n} from './base-fetcher';\n\n/** Request accepted by `NodeFetcher`: `RequestInit` plus `url`; `params` are written into the url query. */\nexport interface INodeFetchRequestOptions extends RequestInit, IRequestOptions {\n url: string;\n method?: THttpMethod;\n params?: AnyObject;\n}\n\n/** What `fetch` takes as a body as it is: encoding any of these again would change the bytes sent. A constructor is looked up on `globalThis` so a runtime without one (no `FormData`) just never matches it. */\nconst isRawBody = (body: unknown): boolean => {\n if (typeof body === 'string' || ArrayBuffer.isView(body) || body instanceof ArrayBuffer) {\n return true;\n }\n\n return ['Blob', 'FormData', 'URLSearchParams', 'ReadableStream'].some((name) => {\n const ctor = Reflect.get(globalThis, name);\n\n return typeof ctor === 'function' && body instanceof ctor;\n });\n};\n\n/** Fetcher over the global `fetch` (`getWorker()`). `timeout` (milliseconds) aborts the request and is combined with a `signal` the caller passes. */\nexport class NodeFetcher extends AbstractNetworkFetchableHelper<\n 'node-fetch',\n INodeFetchRequestOptions,\n Awaited<ReturnType<typeof fetch>>,\n typeof fetch\n> {\n private defaultConfigs: RequestInit;\n private queryString: IQueryStringOptions;\n\n constructor(opts: {\n name: string;\n defaultConfigs: RequestInit;\n /** How `params` are written into the url; unset fields behave as `node:querystring` does. */\n queryString?: IQueryStringOptions;\n logger?: TFetcherLogger;\n }) {\n super({ name: opts.name, variant: 'node-fetch', worker: fetch });\n const { name, defaultConfigs } = opts;\n this.name = name;\n opts?.logger?.info('Creating new network request worker instance! Name: %s', this.name);\n\n this.defaultConfigs = defaultConfigs;\n this.queryString = opts.queryString ?? {};\n }\n\n /** A raw body passes through; a plain object or an array is JSON-encoded; no body stays no body. */\n protected serializeBody(opts: { body: unknown }): RequestInit['body'] | undefined {\n const { body } = opts;\n\n if (body === undefined || body === null) {\n return undefined;\n }\n\n return isRawBody(body) ? (body as RequestInit['body']) : JSON.stringify(body);\n }\n\n override async send(opts: INodeFetchRequestOptions, logger?: TFetcherLogger) {\n const {\n url,\n method = HTTP.Methods.GET,\n params,\n body,\n headers,\n timeout,\n signal,\n ...rest\n } = opts;\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let timeoutController: AbortController | undefined;\n let effectiveSignal = signal;\n\n if (timeout) {\n timeoutController = new AbortController();\n timeoutId = setTimeout(() => {\n timeoutController?.abort();\n }, timeout);\n\n // Composed, never substituted: a timeout must not silently swallow the caller's own signal, or the caller would believe it cancelled a request that is in fact still running. Either source - and a signal already aborted before the call - aborts the request.\n effectiveSignal = signal\n ? AbortSignal.any([signal, timeoutController.signal])\n : timeoutController.signal;\n }\n\n const requestConfigs: RequestInit = {\n ...this.defaultConfigs,\n ...rest,\n method: method.toUpperCase(),\n body: this.serializeBody({ body }),\n // The call's headers REPLACE the defaults (a caller that sends a multipart body leaves the content type out so `fetch` can write the boundary); a call with none keeps them. Spreading an absent `headers` over the config used to erase the defaults.\n headers: headers ?? this.defaultConfigs.headers,\n signal: effectiveSignal,\n };\n\n // `?` only when the url carries no query string of its own - a second `?` is not a separator, so the server would read the previous parameter's value as `1?extra=2`.\n const serializedParams = params\n ? QueryStringUtility.toQueryString({ params, ...this.queryString })\n : '';\n const requestUrl = serializedParams\n ? `${url}${url.includes(QueryStringSeparators.START) ? QueryStringSeparators.PAIR : QueryStringSeparators.START}${serializedParams}`\n : url;\n\n // The body is NEVER logged, only its size. `fetch` bodies are strings, and `redactSecrets` walks\n // object keys - so a JSON credential payload passed straight through as a string was printed in\n // full, with no key for the redactor to match on. Headers are normalised through `Headers` first\n // because the `string[][]` form is a list of tuples, which key matching cannot see either.\n const loggableConfigs = {\n ...requestConfigs,\n body:\n typeof requestConfigs.body === 'string'\n ? `[body ${requestConfigs.body.length} chars]`\n : requestConfigs.body\n ? '[body]'\n : undefined,\n headers: requestConfigs.headers,\n };\n\n // Straight on the logger it was handed, never `logger.for(...)`: a host logger may carry only `debug` and `info`. With none handed, nothing is logged - no default logger is built, so a browser never reaches the node-only provider.\n logger?.debug(\n '[%s] URL: %s | Props: %s | Timeout: %s',\n this.send.name,\n url,\n RedactUtility.redactSecrets({ value: loggableConfigs }),\n timeout,\n );\n\n try {\n const rs = await fetch(requestUrl, requestConfigs);\n\n return rs;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n }\n}\n\n/** Options of `NodeFetchNetworkRequest`: `RequestInit` plus `baseUrl` and `queryString`, which sets how `params` are written into every url. */\nexport interface INodeFetchNetworkRequestOptions {\n name: string;\n networkOptions: RequestInit & {\n baseUrl?: string;\n /** How `params` are written into every url this request sends; see {@link IQueryStringOptions}. */\n queryString?: IQueryStringOptions;\n };\n}\n\n/** `BaseNetworkRequest` over a `NodeFetcher`. Request headers default to a JSON content type, and the caller's headers win. */\nexport class NodeFetchNetworkRequest extends BaseNetworkRequest<'node-fetch'> {\n constructor(opts: INodeFetchNetworkRequestOptions) {\n const { name, networkOptions } = opts;\n const { headers, baseUrl, queryString, ...rest } = networkOptions;\n\n const userHeaders =\n headers instanceof Headers ? Object.fromEntries(headers.entries()) : headers;\n const mergedHeaders: AnyObject = {\n ['content-type']: 'application/json; charset=utf-8',\n ...userHeaders,\n };\n\n const defaultConfigs: Partial<RequestInit> = {\n ...rest,\n headers: mergedHeaders,\n };\n\n super({\n name,\n baseUrl,\n fetcher: new NodeFetcher({ name, defaultConfigs, queryString }),\n });\n }\n}\n"]}
1
+ {"version":3,"file":"node-fetcher.js","sourceRoot":"","sources":["../../../../../../src/modules/network/http-request/fetcher/node-fetcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,IAAI,EAAoB,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAEL,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EACL,8BAA8B,GAG/B,MAAM,gBAAgB,CAAC;AASxB,iNAAiN;AACjN,MAAM,SAAS,GAAG,CAAC,IAAa,EAAW,EAAE;IAC3C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,IAAI,YAAY,WAAW,EAAE,CAAC;QACxF,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,CAAC,MAAM,EAAE,UAAU,EAAE,iBAAiB,EAAE,g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C,aAAa,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;QAE5E,MAAM,cAAc,GAAyB;YAC3C,GAAG,IAAI;YACP,kHAAkH;YAClH,OAAO,EAAE,MAAM,CAAC,WAAW,CAAC,aAAa,CAAC;SAC3C,CAAC;QAEF,KAAK,CAAC;YACJ,IAAI;YACJ,OAAO;YACP,OAAO,EAAE,IAAI,WAAW,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,WAAW,EAAE,CAAC;SAChE,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { RedactUtility } from '@/common/redact';\nimport { HTTP, type THttpMethod } from '@/common/constants/http';\nimport {\n type IQueryStringOptions,\n QueryStringSeparators,\n QueryStringUtility,\n} from '../../utilities/query-string';\n\nimport { BaseNetworkRequest } from '../base-network-request.helper';\nimport {\n AbstractNetworkFetchableHelper,\n type IRequestOptions,\n type TFetcherLogger,\n} from './base-fetcher';\n\n/** Request accepted by `NodeFetcher`: `RequestInit` plus `url`; `params` are written into the url query. */\nexport interface INodeFetchRequestOptions extends RequestInit, IRequestOptions {\n url: string;\n method?: THttpMethod;\n params?: Record<string, unknown>;\n}\n\n/** What `fetch` takes as a body as it is: encoding any of these again would change the bytes sent. A constructor is looked up on `globalThis` so a runtime without one (no `FormData`) just never matches it. */\nconst isRawBody = (body: unknown): boolean => {\n if (typeof body === 'string' || ArrayBuffer.isView(body) || body instanceof ArrayBuffer) {\n return true;\n }\n\n return ['Blob', 'FormData', 'URLSearchParams', 'ReadableStream'].some((name) => {\n const ctor = Reflect.get(globalThis, name);\n\n return typeof ctor === 'function' && body instanceof ctor;\n });\n};\n\n/** Fetcher over the global `fetch` (`getWorker()`). `timeout` (milliseconds) aborts the request and is combined with a `signal` the caller passes. */\nexport class NodeFetcher extends AbstractNetworkFetchableHelper<\n 'node-fetch',\n INodeFetchRequestOptions,\n Awaited<ReturnType<typeof fetch>>,\n typeof fetch\n> {\n private defaultConfigs: RequestInit;\n private queryString: IQueryStringOptions;\n\n constructor(opts: {\n name: string;\n defaultConfigs: RequestInit;\n /** How `params` are written into the url; unset fields behave as `node:querystring` does. */\n queryString?: IQueryStringOptions;\n logger?: TFetcherLogger;\n }) {\n super({ name: opts.name, variant: 'node-fetch', worker: fetch });\n const { name, defaultConfigs } = opts;\n this.name = name;\n opts?.logger?.info('Creating new network request worker instance! Name: %s', this.name);\n\n this.defaultConfigs = defaultConfigs;\n this.queryString = opts.queryString ?? {};\n }\n\n /** A raw body passes through; a plain object or an array is JSON-encoded; no body stays no body. */\n protected serializeBody(opts: { body: unknown }): RequestInit['body'] | undefined {\n const { body } = opts;\n\n if (body === undefined || body === null) {\n return undefined;\n }\n\n return isRawBody(body) ? (body as RequestInit['body']) : JSON.stringify(body);\n }\n\n override async send(opts: INodeFetchRequestOptions, logger?: TFetcherLogger) {\n const {\n url,\n method = HTTP.Methods.GET,\n params,\n body,\n headers,\n timeout,\n signal,\n ...rest\n } = opts;\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let timeoutController: AbortController | undefined;\n let effectiveSignal = signal;\n\n if (timeout) {\n timeoutController = new AbortController();\n timeoutId = setTimeout(() => {\n timeoutController?.abort();\n }, timeout);\n\n // Composed, never substituted: a timeout must not silently swallow the caller's own signal, or the caller would believe it cancelled a request that is in fact still running. Either source - and a signal already aborted before the call - aborts the request.\n effectiveSignal = signal\n ? AbortSignal.any([signal, timeoutController.signal])\n : timeoutController.signal;\n }\n\n const requestConfigs: RequestInit = {\n ...this.defaultConfigs,\n ...rest,\n method: method.toUpperCase(),\n body: this.serializeBody({ body }),\n // The call's headers REPLACE the defaults (a caller that sends a multipart body leaves the content type out so `fetch` can write the boundary); a call with none keeps them. Spreading an absent `headers` over the config used to erase the defaults.\n headers: headers ?? this.defaultConfigs.headers,\n signal: effectiveSignal,\n };\n\n // `?` only when the url carries no query string of its own - a second `?` is not a separator, so the server would read the previous parameter's value as `1?extra=2`.\n const serializedParams = params\n ? QueryStringUtility.toQueryString({ params, ...this.queryString })\n : '';\n const requestUrl = serializedParams\n ? `${url}${url.includes(QueryStringSeparators.START) ? QueryStringSeparators.PAIR : QueryStringSeparators.START}${serializedParams}`\n : url;\n\n // The body is NEVER logged, only its size. `fetch` bodies are strings, and `redactSecrets` walks\n // object keys - so a JSON credential payload passed straight through as a string was printed in\n // full, with no key for the redactor to match on. Headers are normalised through `Headers` first\n // because the `string[][]` form is a list of tuples, which key matching cannot see either.\n const loggableConfigs = {\n ...requestConfigs,\n body:\n typeof requestConfigs.body === 'string'\n ? `[body ${requestConfigs.body.length} chars]`\n : requestConfigs.body\n ? '[body]'\n : undefined,\n headers: requestConfigs.headers,\n };\n\n // Straight on the logger it was handed, never `logger.for(...)`: a host logger may carry only `debug` and `info`. With none handed, nothing is logged - no default logger is built, so a browser never reaches the node-only provider.\n logger?.debug(\n '[%s] URL: %s | Props: %s | Timeout: %s',\n this.send.name,\n url,\n RedactUtility.redactSecrets({ value: loggableConfigs }),\n timeout,\n );\n\n try {\n const rs = await fetch(requestUrl, requestConfigs);\n\n return rs;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n }\n}\n\n/** Options of `NodeFetchNetworkRequest`: `RequestInit` plus `baseUrl` and `queryString`, which sets how `params` are written into every url. */\nexport interface INodeFetchNetworkRequestOptions {\n name: string;\n networkOptions: RequestInit & {\n baseUrl?: string;\n /** How `params` are written into every url this request sends; see {@link IQueryStringOptions}. */\n queryString?: IQueryStringOptions;\n };\n}\n\n/** `BaseNetworkRequest` over a `NodeFetcher`. Request headers default to a JSON content type, and the caller's headers win. */\nexport class NodeFetchNetworkRequest extends BaseNetworkRequest<'node-fetch'> {\n constructor(opts: INodeFetchNetworkRequestOptions) {\n const { name, networkOptions } = opts;\n const { headers, baseUrl, queryString, ...rest } = networkOptions;\n\n // Case-insensitive, like the wire: a caller's `Content-Type` replaces the default one.\n const mergedHeaders = new Headers({ 'content-type': 'application/json; charset=utf-8' });\n\n new Headers(headers).forEach((value, key) => mergedHeaders.set(key, value));\n\n const defaultConfigs: Partial<RequestInit> = {\n ...rest,\n // A plain object, so the request log (which redacts by key) can read it; a `Headers` instance has no own entries.\n headers: Object.fromEntries(mergedHeaders),\n };\n\n super({\n name,\n baseUrl,\n fetcher: new NodeFetcher({ name, defaultConfigs, queryString }),\n });\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,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,IAAiD;QAC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AAK,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,EAAE,CAAC;QAC3B,MAAM,SAAS,GAAG,CAAC,KAAc,EAAE,EAAE,CACnC,OAAO,KAAK,uBAAuB,CAAC,IAAI,IAAI,CAAC,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,CAAC,CAAC;QACtF,MAAM,MAAM,GAAG,MAAM,KAAK,sBAAsB,CAAC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,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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ingest.js","sourceRoot":"","sources":["../../../../../../src/modules/network/utilities/url-safety/ingest.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,yCAAyC;A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G,CAAC,CAAC;QACL,CAAC;QAED,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC;QAE1C,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,QAAQ,CAAC,EAAE,OAAO,EAAE,2CAA2C,EAAE,CAAC,CAAC;QAC3E,CAAC;QAED,MAAM,MAAM,GAAiB,EAAE,CAAC;QAChC,IAAI,QAAQ,GAAG,CAAC,CAAC;QAEjB,SAAS,CAAC;YACR,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAE5C,IAAI,IAAI,EAAE,CAAC;gBACT,MAAM;YACR,CAAC;YAED,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC;YAEzB,IAAI,QAAQ,GAAG,QAAQ,EAAE,CAAC;gBACxB,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;gBACtB,MAAM,QAAQ,CAAC;oBACb,KAAK,EAAE,eAAe,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/** 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,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,OAAO,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC;YACpC,MAAM;SACP,CAAC,CAAC;QAEH,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,CAAC;YACtB,MAAM,QAAQ,CAAC;gBACb,KAAK,EAAE,eAAe,CAAC,WAAW;gBAClC,OAAO,EAAE,uDAAuD,QAAQ,EAAE;aAC3E,CAAC,CAAC;QACL,CAAC;QAED,MAA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E,MAAM,EAAE,CAAC;YAC9B,+FAA+F;YAC/F,+FAA+F;YAC/F,MAAM,QAAQ,CAAC;gBACb,KAAK,EAAE,eAAe,CAAC,WAAW;gBAClC,OAAO,EAAE,qDAAqD,cAAc,WAAW,QAAQ,EAAE;aAClG,CAAC,CAAC;QACL,CAAC;QAED,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,EAAE,SAAS,EAAE,CAAC;QAE1C,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,MAAM,QAAQ,CAAC,EAAE,OAAO,EAAE,2CAA2C,EAAE,CAAC,CAAC;QAC3E,CAAC;QAED,MAAM,MAAM,GAAiB,EAAE,CAAC;QAChC,IAAI,QAAQ,GAAG,CAAC,CAAC;QAEjB,SAAS,CAAC;YACR,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAE5C,IAAI,IAAI,EAAE,CAAC;gBACT,MAAM;YACR,CAAC;YAED,QAAQ,IAAI,KAAK,CAAC,MAAM,CAAC;YAEzB,IAAI,QAAQ,GAAG,QAAQ,EAAE,CAAC;gBACxB,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC;gBACtB,MAAM,QAAQ,CAAC;oBACb,KAAK,EAAE,eAAe,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"]}
@@ -41,7 +41,7 @@ export declare abstract class BaseKafkaHelper<TClient extends Base<BaseOptions>>
41
41
  protected swapClient(newClient: TClient): void;
42
42
  protected resetHealthState(): void;
43
43
  protected closeClient(): Promise<void>;
44
- /** Force-close through the callback overload: only Producer and Consumer expose `close(force, cb)`, and the `Base` type this class is generic over declares no such overload - hence the cast. */
44
+ /** Force-close through the callback overload: only Producer and Consumer expose `close(force, cb)`, and the `Base` type this class is generic over declares no such overload - hence the guard. */
45
45
  protected closeClientWithCallback(): Promise<void>;
46
46
  protected gracefulCloseClient(): Promise<void>;
47
47
  }
@@ -2,6 +2,12 @@ import { getError } from '../../error/index.js';
2
2
  import { BaseHelper } from '../../base.js';
3
3
  import { HookUtility } from '../common/index.js';
4
4
  import { KafkaClientEvents, KafkaDefaults, KafkaHealthStatuses, } from './common/constants.js';
5
+ const hasCallbackClose = (client) => {
6
+ return (typeof client === 'object' &&
7
+ client !== null &&
8
+ 'close' in client &&
9
+ typeof client.close === 'function');
10
+ };
5
11
  /**
6
12
  * Shared health tracking and broker event wiring for all Kafka helpers (producer, consumer, admin); `TClient` is the platformatic client type, passed by subclasses via `super({ client })`.
7
13
  *
@@ -91,11 +97,16 @@ export class BaseKafkaHelper extends BaseHelper {
91
97
  closeClient() {
92
98
  return this.client.close();
93
99
  }
94
- /** Force-close through the callback overload: only Producer and Consumer expose `close(force, cb)`, and the `Base` type this class is generic over declares no such overload - hence the cast. */
100
+ /** Force-close through the callback overload: only Producer and Consumer expose `close(force, cb)`, and the `Base` type this class is generic over declares no such overload - hence the guard. */
95
101
  closeClientWithCallback() {
96
102
  const client = this.client;
103
+ if (!hasCallbackClose(client)) {
104
+ return Promise.reject(getError({ message: '[closeClientWithCallback] The client has no close(force, callback)' }));
105
+ }
106
+ const closable = client;
97
107
  return new Promise((resolve, reject) => {
98
- client.close(true, (error) => {
108
+ // Through `ICallbackCloseClient`, not `client`: on the narrowed type the overload of `Base.close` wins and takes no `force`.
109
+ closable.close(true, (error) => {
99
110
  if (error) {
100
111
  reject(error);
101
112
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/queue/kafka/base.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,mBAAmB,GAEpB,MAAM,oBAAoB,CAAC;AAiB5B;;;;GAIG;AACH,MAAM,OAAgB,eAAmD,SAAQ,UAAU;IAYzF,YAAY,IAAgC;QAC1C,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QATlD,iBAAY,GAAuB,mBAAmB,CAAC,OAAO,CAAC;QAEzE,qDAAqD;QAClC,qBAAgB,GAAG,IAAI,GAAG,EAAU,CAAC;QAOtD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAC1B,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,eAAe,IAAI,aAAa,CAAC,gBAAgB,CAAC;QAC9E,IAAI,CAAC,eAAe,GAAG,IAAI,CAAC,eAAe,CAAC;QAC5C,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC,kBAAkB,CAAC;IACpD,CAAC;IAED,SAAS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,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAES,KAAK,CAAC,mBAAmB;QACjC,IAAI,aAAa,GAA0B,IAAI,CAAC;QAEhD,IAAI,CAAC;YACH,2KAA2K;YAC3K,MAAM,OAAO,CAAC,IAAI,CAAC;gBACjB,IAAI,CAAC,WAAW,EAAE;gBAClB,IAAI,OAAO,CAAO,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;oBAC9B,aAAa,GAAG,UAAU,CACxB,GAAG,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,0CAA0C,EAAE,CAAC,CAAC,EAC/E,IAAI,CAAC,eAAe,CACrB,CAAC;gBACJ,CAAC,CAAC;aACH,CAAC,CAAC;QACL,CAAC;gBAAS,CAAC;YACT,IAAI,aAAa,KAAK,IAAI,EAAE,CAAC;gBAC3B,YAAY,CAAC,aAAa,CAAC,CAAC;YAC9B,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { AnyType } from '@/common';\nimport { getError } from '@/modules/error';\nimport { BaseHelper } from '@/modules/base';\nimport type { Base, BaseOptions, ConnectionPoolEventPayload } from '@platformatic/kafka';\nimport { HookUtility } from '../common';\nimport {\n KafkaClientEvents,\n KafkaDefaults,\n KafkaHealthStatuses,\n type TKafkaHealthStatus,\n} from './common/constants';\nimport type { TKafkaBrokerEventCallback } from './common/types';\n\n/** Options shared by the Kafka helpers. */\nexport interface IKafkaBaseOptions<TClient extends Base<BaseOptions>> {\n scope: string;\n identifier: string;\n client: TClient;\n /**\n * Milliseconds the helper waits for in-flight work on shutdown.\n * @default KafkaDefaults.SHUTDOWN_TIMEOUT\n */\n shutdownTimeout?: number;\n onBrokerConnect?: TKafkaBrokerEventCallback;\n onBrokerDisconnect?: TKafkaBrokerEventCallback;\n}\n\n/**\n * Shared health tracking and broker event wiring for all Kafka helpers (producer, consumer, admin); `TClient` is the platformatic client type, passed by subclasses via `super({ client })`.\n *\n * Every member below is `protected`, not `private`, so a producer, consumer, or admin helper can extend this class instead of forking it. That visibility is not a stable contract between minor versions.\n */\nexport abstract class BaseKafkaHelper<TClient extends Base<BaseOptions>> extends BaseHelper {\n protected client: TClient;\n protected readonly shutdownTimeout: number;\n\n protected healthStatus: TKafkaHealthStatus = KafkaHealthStatuses.UNKNOWN;\n\n /** Per-broker connection state. Key = \"host:port\" */\n protected readonly connectedBrokers = new Set<string>();\n\n protected readonly onBrokerConnect?: TKafkaBrokerEventCallback;\n protected readonly onBrokerDisconnect?: TKafkaBrokerEventCallback;\n\n constructor(opts: IKafkaBaseOptions<TClient>) {\n super({ scope: opts.scope, identifier: opts.identifier });\n this.client = opts.client;\n this.shutdownTimeout = opts.shutdownTimeout ?? KafkaDefaults.SHUTDOWN_TIMEOUT;\n this.onBrokerConnect = opts.onBrokerConnect;\n this.onBrokerDisconnect = opts.onBrokerDisconnect;\n }\n\n isHealthy(): boolean {\n return this.connectedBrokers.size > 0;\n }\n\n isReady(): boolean {\n return this.healthStatus === KafkaHealthStatuses.CONNECTED;\n }\n\n getHealthStatus(): TKafkaHealthStatus {\n return this.healthStatus;\n }\n\n getConnectedBrokerCount(): number {\n return this.connectedBrokers.size;\n }\n\n protected configureBrokerConnect() {\n this.client.on(KafkaClientEvents.BROKER_CONNECT, (payload: ConnectionPoolEventPayload) => {\n const brokerKey = `${payload.broker.host}:${payload.broker.port}`;\n this.connectedBrokers.add(brokerKey);\n this.healthStatus = KafkaHealthStatuses.CONNECTED;\n\n this.logger.info(\n '[configureBrokerConnect] Broker CONNECTED | Host: %s | Port: %d | Connected: %d',\n payload.broker.host,\n payload.broker.port,\n this.connectedBrokers.size,\n );\n\n HookUtility.invoke({\n logger: this.logger,\n scope: 'configureBrokerConnect',\n execution: () => this.onBrokerConnect?.({ broker: payload.broker }),\n });\n });\n }\n\n protected configureBrokerDisconnect() {\n this.client.on(KafkaClientEvents.BROKER_DISCONNECT, (payload: ConnectionPoolEventPayload) => {\n const brokerKey = `${payload.broker.host}:${payload.broker.port}`;\n this.connectedBrokers.delete(brokerKey);\n\n if (this.connectedBrokers.size === 0) {\n this.healthStatus = KafkaHealthStatuses.DISCONNECTED;\n }\n\n this.logger.warn(\n '[configureBrokerDisconnect] Broker DISCONNECTED | Host: %s | Port: %d | Remaining: %d',\n payload.broker.host,\n payload.broker.port,\n this.connectedBrokers.size,\n );\n\n HookUtility.invoke({\n logger: this.logger,\n scope: 'configureBrokerDisconnect',\n execution: () => this.onBrokerDisconnect?.({ broker: payload.broker }),\n });\n });\n }\n\n protected configureBrokerFailed() {\n this.client.on(KafkaClientEvents.BROKER_FAILED, (payload: ConnectionPoolEventPayload) => {\n const brokerKey = `${payload.broker.host}:${payload.broker.port}`;\n this.connectedBrokers.delete(brokerKey);\n\n if (this.connectedBrokers.size === 0) {\n this.healthStatus = KafkaHealthStatuses.DISCONNECTED;\n }\n\n this.logger.error(\n '[configureBrokerFailed] Broker connection FAILED | Host: %s | Port: %d | Remaining: %d',\n payload.broker.host,\n payload.broker.port,\n this.connectedBrokers.size,\n );\n });\n }\n\n protected configureBrokerEvents(): void {\n this.configureBrokerConnect();\n this.configureBrokerDisconnect();\n this.configureBrokerFailed();\n }\n\n protected unconfigureBrokerEvents(): void {\n this.client.removeAllListeners(KafkaClientEvents.BROKER_CONNECT);\n this.client.removeAllListeners(KafkaClientEvents.BROKER_DISCONNECT);\n this.client.removeAllListeners(KafkaClientEvents.BROKER_FAILED);\n }\n\n protected swapClient(newClient: TClient): void {\n this.unconfigureBrokerEvents();\n this.client = newClient;\n this.resetHealthState();\n this.configureBrokerEvents();\n }\n\n protected resetHealthState(): void {\n this.connectedBrokers.clear();\n this.healthStatus = KafkaHealthStatuses.DISCONNECTED;\n }\n\n protected closeClient(): Promise<void> {\n return this.client.close();\n }\n\n /** Force-close through the callback overload: only Producer and Consumer expose `close(force, cb)`, and the `Base` type this class is generic over declares no such overload - hence the cast. */\n protected closeClientWithCallback(): Promise<void> {\n const client = this.client as AnyType;\n\n return new Promise<void>((resolve, reject) => {\n client.close(true, (error?: Error | null) => {\n if (error) {\n reject(error);\n\n return;\n }\n\n resolve();\n });\n });\n }\n\n protected async gracefulCloseClient(): Promise<void> {\n let timeoutHandle: NodeJS.Timeout | null = null;\n\n try {\n // The timer MUST be cleared once close() wins: an armed shutdownTimeout timer keeps the event loop alive long after a successful shutdown, so the process refuses to exit.\n await Promise.race([\n this.closeClient(),\n new Promise<void>((_, reject) => {\n timeoutHandle = setTimeout(\n () => reject(getError({ message: '[gracefulCloseClient] Shutdown timed out' })),\n this.shutdownTimeout,\n );\n }),\n ]);\n } finally {\n if (timeoutHandle !== null) {\n clearTimeout(timeoutHandle);\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../../src/modules/queue/kafka/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EACL,iBAAiB,EACjB,aAAa,EACb,mBAAmB,GAEpB,MAAM,oBAAoB,CAAC;AAQ5B,MAAM,gBAAgB,GAAG,CAAC,MAAe,EAAkC,EAAE;IAC3E,OAAO,CACL,OAAO,MAAM,KAAK,QAAQ;QAC1B,MAAM,KAAK,IAAI;QACf,OAAO,IAAI,MAAM;QACjB,OAAO,MAAM,CAAC,KAAK,KAAK,UAAU,CACnC,CAAC;AACJ,CAAC,CAAC;AAgBF;;;;GAIG;AACH,MAAM,OAAgB,eAAmD,SAAQ,UAAU;IAYzF,YAAY,IAAgC;QAC1C,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,UAAU,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QATlD,iBAAY,GAAuB,mBAAmB,CAAC,OAAO,CAAC;QAEzE,qDAAqD;QAClC,qBAAgB,GAAG,IAA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MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;QAE3B,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,EAAE,CAAC;YAC9B,OAAO,OAAO,CAAC,MAAM,CACnB,QAAQ,CAAC,EAAE,OAAO,EAAE,oEAAoE,EAAE,CAAC,CAC5F,CAAC;QACJ,CAAC;QAED,MAAM,QAAQ,GAAyB,MAAM,CAAC;QAE9C,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC3C,6HAA6H;YAC7H,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,KAAoB,EAAE,EAAE;gBAC5C,IAAI,KAAK,EAAE,CAAC;oBACV,MAAM,CAAC,KAAK,CAAC,CAAC;oBAEd,OAAO;gBACT,CAAC;gBAED,OAAO,EAAE,CAAC;YACZ,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAES,KAAK,CAAC,mBAAmB;QACjC,IAAI,aAAa,GAA0B,IAAI,CAAC;QAEhD,IAAI,CAAC;YACH,2KAA2K;YAC3K,MAAM,OAAO,CAAC,IAAI,CAAC;gBACjB,IAAI,CAAC,WAAW,EAAE;gBAClB,IAAI,OAAO,CAAO,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE;oBAC9B,aAAa,GAAG,UAAU,CACxB,GAAG,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,0CAA0C,EAAE,CAAC,CAAC,EAC/E,IAAI,CAAC,eAAe,CACrB,CAAC;gBACJ,CAAC,CAAC;aACH,CAAC,CAAC;QACL,CAAC;gBAAS,CAAC;YACT,IAAI,aAAa,KAAK,IAAI,EAAE,CAAC;gBAC3B,YAAY,CAAC,aAAa,CAAC,CAAC;YAC9B,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import { getError } from '@/modules/error';\nimport { BaseHelper } from '@/modules/base';\nimport type { Base, BaseOptions, ConnectionPoolEventPayload } from '@platformatic/kafka';\nimport { HookUtility } from '../common';\nimport {\n KafkaClientEvents,\n KafkaDefaults,\n KafkaHealthStatuses,\n type TKafkaHealthStatus,\n} from './common/constants';\nimport type { TKafkaBrokerEventCallback } from './common/types';\n\n/** A client that closes through `close(force, callback)`, which only Producer and Consumer expose. */\ninterface ICallbackCloseClient {\n close(force: boolean, callback: (error?: Error | null) => void): void;\n}\n\nconst hasCallbackClose = (client: unknown): client is ICallbackCloseClient => {\n return (\n typeof client === 'object' &&\n client !== null &&\n 'close' in client &&\n typeof client.close === 'function'\n );\n};\n\n/** Options shared by the Kafka helpers. */\nexport interface IKafkaBaseOptions<TClient extends Base<BaseOptions>> {\n scope: string;\n identifier: string;\n client: TClient;\n /**\n * Milliseconds the helper waits for in-flight work on shutdown.\n * @default KafkaDefaults.SHUTDOWN_TIMEOUT\n */\n shutdownTimeout?: number;\n onBrokerConnect?: TKafkaBrokerEventCallback;\n onBrokerDisconnect?: TKafkaBrokerEventCallback;\n}\n\n/**\n * Shared health tracking and broker event wiring for all Kafka helpers (producer, consumer, admin); `TClient` is the platformatic client type, passed by subclasses via `super({ client })`.\n *\n * Every member below is `protected`, not `private`, so a producer, consumer, or admin helper can extend this class instead of forking it. That visibility is not a stable contract between minor versions.\n */\nexport abstract class BaseKafkaHelper<TClient extends Base<BaseOptions>> extends BaseHelper {\n protected client: TClient;\n protected readonly shutdownTimeout: number;\n\n protected healthStatus: TKafkaHealthStatus = KafkaHealthStatuses.UNKNOWN;\n\n /** Per-broker connection state. Key = \"host:port\" */\n protected readonly connectedBrokers = new Set<string>();\n\n protected readonly onBrokerConnect?: TKafkaBrokerEventCallback;\n protected readonly onBrokerDisconnect?: TKafkaBrokerEventCallback;\n\n constructor(opts: IKafkaBaseOptions<TClient>) {\n super({ scope: opts.scope, identifier: opts.identifier });\n this.client = opts.client;\n this.shutdownTimeout = opts.shutdownTimeout ?? KafkaDefaults.SHUTDOWN_TIMEOUT;\n this.onBrokerConnect = opts.onBrokerConnect;\n this.onBrokerDisconnect = opts.onBrokerDisconnect;\n }\n\n isHealthy(): boolean {\n return this.connectedBrokers.size > 0;\n }\n\n isReady(): boolean {\n return this.healthStatus === KafkaHealthStatuses.CONNECTED;\n }\n\n getHealthStatus(): TKafkaHealthStatus {\n return this.healthStatus;\n }\n\n getConnectedBrokerCount(): number {\n return this.connectedBrokers.size;\n }\n\n protected configureBrokerConnect() {\n this.client.on(KafkaClientEvents.BROKER_CONNECT, (payload: ConnectionPoolEventPayload) => {\n const brokerKey = `${payload.broker.host}:${payload.broker.port}`;\n this.connectedBrokers.add(brokerKey);\n this.healthStatus = KafkaHealthStatuses.CONNECTED;\n\n this.logger.info(\n '[configureBrokerConnect] Broker CONNECTED | Host: %s | Port: %d | Connected: %d',\n payload.broker.host,\n payload.broker.port,\n this.connectedBrokers.size,\n );\n\n HookUtility.invoke({\n logger: this.logger,\n scope: 'configureBrokerConnect',\n execution: () => this.onBrokerConnect?.({ broker: payload.broker }),\n });\n });\n }\n\n protected configureBrokerDisconnect() {\n this.client.on(KafkaClientEvents.BROKER_DISCONNECT, (payload: ConnectionPoolEventPayload) => {\n const brokerKey = `${payload.broker.host}:${payload.broker.port}`;\n this.connectedBrokers.delete(brokerKey);\n\n if (this.connectedBrokers.size === 0) {\n this.healthStatus = KafkaHealthStatuses.DISCONNECTED;\n }\n\n this.logger.warn(\n '[configureBrokerDisconnect] Broker DISCONNECTED | Host: %s | Port: %d | Remaining: %d',\n payload.broker.host,\n payload.broker.port,\n this.connectedBrokers.size,\n );\n\n HookUtility.invoke({\n logger: this.logger,\n scope: 'configureBrokerDisconnect',\n execution: () => this.onBrokerDisconnect?.({ broker: payload.broker }),\n });\n });\n }\n\n protected configureBrokerFailed() {\n this.client.on(KafkaClientEvents.BROKER_FAILED, (payload: ConnectionPoolEventPayload) => {\n const brokerKey = `${payload.broker.host}:${payload.broker.port}`;\n this.connectedBrokers.delete(brokerKey);\n\n if (this.connectedBrokers.size === 0) {\n this.healthStatus = KafkaHealthStatuses.DISCONNECTED;\n }\n\n this.logger.error(\n '[configureBrokerFailed] Broker connection FAILED | Host: %s | Port: %d | Remaining: %d',\n payload.broker.host,\n payload.broker.port,\n this.connectedBrokers.size,\n );\n });\n }\n\n protected configureBrokerEvents(): void {\n this.configureBrokerConnect();\n this.configureBrokerDisconnect();\n this.configureBrokerFailed();\n }\n\n protected unconfigureBrokerEvents(): void {\n this.client.removeAllListeners(KafkaClientEvents.BROKER_CONNECT);\n this.client.removeAllListeners(KafkaClientEvents.BROKER_DISCONNECT);\n this.client.removeAllListeners(KafkaClientEvents.BROKER_FAILED);\n }\n\n protected swapClient(newClient: TClient): void {\n this.unconfigureBrokerEvents();\n this.client = newClient;\n this.resetHealthState();\n this.configureBrokerEvents();\n }\n\n protected resetHealthState(): void {\n this.connectedBrokers.clear();\n this.healthStatus = KafkaHealthStatuses.DISCONNECTED;\n }\n\n protected closeClient(): Promise<void> {\n return this.client.close();\n }\n\n /** Force-close through the callback overload: only Producer and Consumer expose `close(force, cb)`, and the `Base` type this class is generic over declares no such overload - hence the guard. */\n protected closeClientWithCallback(): Promise<void> {\n const client = this.client;\n\n if (!hasCallbackClose(client)) {\n return Promise.reject(\n getError({ message: '[closeClientWithCallback] The client has no close(force, callback)' }),\n );\n }\n\n const closable: ICallbackCloseClient = client;\n\n return new Promise<void>((resolve, reject) => {\n // Through `ICallbackCloseClient`, not `client`: on the narrowed type the overload of `Base.close` wins and takes no `force`.\n closable.close(true, (error?: Error | null) => {\n if (error) {\n reject(error);\n\n return;\n }\n\n resolve();\n });\n });\n }\n\n protected async gracefulCloseClient(): Promise<void> {\n let timeoutHandle: NodeJS.Timeout | null = null;\n\n try {\n // The timer MUST be cleared once close() wins: an armed shutdownTimeout timer keeps the event loop alive long after a successful shutdown, so the process refuses to exit.\n await Promise.race([\n this.closeClient(),\n new Promise<void>((_, reject) => {\n timeoutHandle = setTimeout(\n () => reject(getError({ message: '[gracefulCloseClient] Shutdown timed out' })),\n this.shutdownTimeout,\n );\n }),\n ]);\n } finally {\n if (timeoutHandle !== null) {\n clearTimeout(timeoutHandle);\n }\n }\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { Cluster } from 'ioredis';
2
2
  import { AbstractRedisHelper } from './../base/index.js';
3
- import { type IRedisClusterHelperOptions } from './../common/index.js';
3
+ import type { IRedisClusterHelperOptions } from './types.js';
4
4
  /** Redis helper over an ioredis `Cluster`. `autoConnect: false` creates the client with `lazyConnect`; `clusterOptions` is applied last and overrides the defaults. */
5
5
  export declare class RedisClusterHelper extends AbstractRedisHelper<Cluster> {
6
6
  private startupNodes;
@@ -8,8 +8,7 @@ export class RedisClusterHelper extends AbstractRedisHelper {
8
8
  const { autoConnect = true, maxRetry = RedisDefaults.MAX_RETRY } = opts;
9
9
  const startupNodes = opts.nodes.map((node) => ({
10
10
  host: node.host,
11
- port: ParseUtility.toInt({ input: node.port }),
12
- password: node.password,
11
+ port: ParseUtility.toInt({ input: node.port ?? RedisDefaults.PORT }),
13
12
  }));
14
13
  // Precedence (low -> high): the framework defaults, then `clusterOptions` verbatim. The raw
15
14
  // hatch stays the last word, because a caller already threading `lazyConnect` through it must
@@ -26,9 +25,17 @@ export class RedisClusterHelper extends AbstractRedisHelper {
26
25
  maxRetry,
27
26
  }),
28
27
  ...opts.clusterOptions,
29
- // Merged, not replaced: node passwords and TLS live in `redisOptions`, and an app that sets them must keep what BullMQ needs. An explicit `maxRetriesPerRequest` still wins.
28
+ // Merged, not replaced: TLS and the like live in `redisOptions`, and an app that sets them must keep what BullMQ needs. An explicit `maxRetriesPerRequest` still wins.
30
29
  redisOptions: { maxRetriesPerRequest: null, ...opts.clusterOptions?.redisOptions },
31
30
  };
31
+ // ioredis applies a per-node password to the startup nodes only; nodes found later are built
32
+ // from host:port and `redisOptions`. So the credentials go in `redisOptions`, where every node
33
+ // gets them. The rule is the Sentinel helper's: a first-class credential that is given wins,
34
+ // and `redisOptions` only fills what is unset. (The other cluster knobs keep `clusterOptions`
35
+ // as the last word, because callers already thread timing through it.)
36
+ clusterOpts.redisOptions ??= {};
37
+ clusterOpts.redisOptions.username = opts.username ?? clusterOpts.redisOptions.username;
38
+ clusterOpts.redisOptions.password = opts.password ?? clusterOpts.redisOptions.password;
32
39
  const ioredis = opts.module ?? ModuleUtility.loadSync({ module: 'ioredis' });
33
40
  super({
34
41
  ...opts,
@@ -1 +1 @@
1
- {"version":3,"file":"cluster.helper.js","sourceRoot":"","sources":["../../../../../src/modules/redis/cluster/cluster.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAE3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,aAAa,EAAmC,MAAM,aAAa,CAAC;AAE7E,uKAAuK;AACvK,MAAM,OAAO,kBAAmB,SAAQ,mBAA4B;IAKlE,YAAY,IAAgC;QAC1C,MAAM,EAAE,WAAW,GAAG,IAAI,EAAE,QAAQ,GAAG,aAAa,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC;QAExE,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YAC7C,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC;YAC9C,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACxB,CAAC,CAAC,CAAC;QAEJ,4FAA4F;QAC5F,8FAA8F;QAC9F,0FAA0F;QAC1F,yFAAyF;QACzF,0FAA0F;QAC1F,4FAA4F;QAC5F,MAAM,WAAW,GAAmB;YAClC,kBAAkB,EAAE,IAAI;YACxB,WAAW,EAAE,CAAC,WAAW;YACzB,oBAAoB,EAAE,mBAAmB,CAAC,kBAAkB,CAAC;gBAC3D,KAAK,EAAE,kBAAkB,CAAC,IAAI;gBAC9B,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,QAAQ;aACT,CAAC;YACF,GAAG,IAAI,CAAC,cAAc;YACtB,6KAA6K;YAC7K,YAAY,EAAE,EAAE,oBAAoB,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC,cAAc,EAAE,YAAY,EAAE;SACnF,CAAC;QAEF,MAAM,OAAO,GACX,IAAI,CAAC,MAAM,IAAI,aAAa,CAAC,QAAQ,CAA2B,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;QAEzF,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,KAAK,EAAE,kBAAkB,CAAC,IAAI;YAC9B,UAAU,EAAE,IAAI,CAAC,IAAI;YACrB,MAAM,EAAE,IAAI,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,WAAW,CAAC;SACvD,CAAC,CAAC;QAEH,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAEQ,eAAe;QACtB,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IACvE,CAAC;CACF","sourcesContent":["import { ParseUtility } from '@/utilities';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport type { Cluster, ClusterOptions } from 'ioredis';\nimport { AbstractRedisHelper } from './../base';\nimport { RedisDefaults, type IRedisClusterHelperOptions } from './../common';\n\n/** Redis helper over an ioredis `Cluster`. `autoConnect: false` creates the client with `lazyConnect`; `clusterOptions` is applied last and overrides the defaults. */\nexport class RedisClusterHelper extends AbstractRedisHelper<Cluster> {\n private startupNodes: Array<{ host: string; port: number; password?: string }>;\n private clusterOpts: ClusterOptions;\n private ioredis: typeof import('ioredis');\n\n constructor(opts: IRedisClusterHelperOptions) {\n const { autoConnect = true, maxRetry = RedisDefaults.MAX_RETRY } = opts;\n\n const startupNodes = opts.nodes.map((node) => ({\n host: node.host,\n port: ParseUtility.toInt({ input: node.port }),\n password: node.password,\n }));\n\n // Precedence (low -> high): the framework defaults, then `clusterOptions` verbatim. The raw\n // hatch stays the last word, because a caller already threading `lazyConnect` through it must\n // keep the timing it has today. `enableOfflineQueue` is stated rather than inherited from\n // ioredis, so the queue a cluster needs between bind and connect cannot go missing on an\n // ioredis default change. `maxRetriesPerRequest: null` is what a BullMQ worker needs; the\n // cluster-level `clusterRetryStrategy` reconnects with the same backoff as the other modes.\n const clusterOpts: ClusterOptions = {\n enableOfflineQueue: true,\n lazyConnect: !autoConnect,\n clusterRetryStrategy: AbstractRedisHelper.buildRetryStrategy({\n scope: RedisClusterHelper.name,\n name: opts.name,\n maxRetry,\n }),\n ...opts.clusterOptions,\n // Merged, not replaced: node passwords and TLS live in `redisOptions`, and an app that sets them must keep what BullMQ needs. An explicit `maxRetriesPerRequest` still wins.\n redisOptions: { maxRetriesPerRequest: null, ...opts.clusterOptions?.redisOptions },\n };\n\n const ioredis =\n opts.module ?? ModuleUtility.loadSync<typeof import('ioredis')>({ module: 'ioredis' });\n\n super({\n ...opts,\n scope: RedisClusterHelper.name,\n identifier: opts.name,\n client: new ioredis.Cluster(startupNodes, clusterOpts),\n });\n\n this.startupNodes = startupNodes;\n this.clusterOpts = clusterOpts;\n this.ioredis = ioredis;\n }\n\n override duplicateClient(): Cluster {\n return new this.ioredis.Cluster(this.startupNodes, this.clusterOpts);\n }\n}\n"]}
1
+ {"version":3,"file":"cluster.helper.js","sourceRoot":"","sources":["../../../../../src/modules/redis/cluster/cluster.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAE3D,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,a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W,CAAC,YAAY,CAAC,QAAQ,CAAC;QAEvF,MAAM,OAAO,GACX,IAAI,CAAC,MAAM,IAAI,aAAa,CAAC,QAAQ,CAA2B,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;QAEzF,KAAK,CAAC;YACJ,GAAG,IAAI;YACP,KAAK,EAAE,kBAAkB,CAAC,IAAI;YAC9B,UAAU,EAAE,IAAI,CAAC,IAAI;YACrB,MAAM,EAAE,IAAI,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,WAAW,CAAC;SACvD,CAAC,CAAC;QAEH,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAEQ,eAAe;QACtB,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IACvE,CAAC;CACF","sourcesContent":["import { ParseUtility } from '@/utilities';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport type { Cluster, ClusterOptions } from 'ioredis';\nimport { AbstractRedisHelper } from './../base';\nimport { RedisDefaults } from './../common';\nimport type { IRedisClusterHelperOptions } from './types';\n\n/** Redis helper over an ioredis `Cluster`. `autoConnect: false` creates the client with `lazyConnect`; `clusterOptions` is applied last and overrides the defaults. */\nexport class RedisClusterHelper extends AbstractRedisHelper<Cluster> {\n private startupNodes: Array<{ host: string; port: number }>;\n private clusterOpts: ClusterOptions;\n private ioredis: typeof import('ioredis');\n\n constructor(opts: IRedisClusterHelperOptions) {\n const { autoConnect = true, maxRetry = RedisDefaults.MAX_RETRY } = opts;\n\n const startupNodes = opts.nodes.map((node) => ({\n host: node.host,\n port: ParseUtility.toInt({ input: node.port ?? RedisDefaults.PORT }),\n }));\n\n // Precedence (low -> high): the framework defaults, then `clusterOptions` verbatim. The raw\n // hatch stays the last word, because a caller already threading `lazyConnect` through it must\n // keep the timing it has today. `enableOfflineQueue` is stated rather than inherited from\n // ioredis, so the queue a cluster needs between bind and connect cannot go missing on an\n // ioredis default change. `maxRetriesPerRequest: null` is what a BullMQ worker needs; the\n // cluster-level `clusterRetryStrategy` reconnects with the same backoff as the other modes.\n const clusterOpts: ClusterOptions = {\n enableOfflineQueue: true,\n lazyConnect: !autoConnect,\n clusterRetryStrategy: AbstractRedisHelper.buildRetryStrategy({\n scope: RedisClusterHelper.name,\n name: opts.name,\n maxRetry,\n }),\n ...opts.clusterOptions,\n // Merged, not replaced: TLS and the like live in `redisOptions`, and an app that sets them must keep what BullMQ needs. An explicit `maxRetriesPerRequest` still wins.\n redisOptions: { maxRetriesPerRequest: null, ...opts.clusterOptions?.redisOptions },\n };\n\n // ioredis applies a per-node password to the startup nodes only; nodes found later are built\n // from host:port and `redisOptions`. So the credentials go in `redisOptions`, where every node\n // gets them. The rule is the Sentinel helper's: a first-class credential that is given wins,\n // and `redisOptions` only fills what is unset. (The other cluster knobs keep `clusterOptions`\n // as the last word, because callers already thread timing through it.)\n clusterOpts.redisOptions ??= {};\n clusterOpts.redisOptions.username = opts.username ?? clusterOpts.redisOptions.username;\n clusterOpts.redisOptions.password = opts.password ?? clusterOpts.redisOptions.password;\n\n const ioredis =\n opts.module ?? ModuleUtility.loadSync<typeof import('ioredis')>({ module: 'ioredis' });\n\n super({\n ...opts,\n scope: RedisClusterHelper.name,\n identifier: opts.name,\n client: new ioredis.Cluster(startupNodes, clusterOpts),\n });\n\n this.startupNodes = startupNodes;\n this.clusterOpts = clusterOpts;\n this.ioredis = ioredis;\n }\n\n override duplicateClient(): Cluster {\n return new this.ioredis.Cluster(this.startupNodes, this.clusterOpts);\n }\n}\n"]}
@@ -1,2 +1,3 @@
1
+ export * from './types.js';
1
2
  export * from './cluster.helper.js';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,3 @@
1
+ export * from './types.js';
1
2
  export * from './cluster.helper.js';
2
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/modules/redis/cluster/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC","sourcesContent":["export * from './cluster.helper';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/modules/redis/cluster/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,kBAAkB,CAAC","sourcesContent":["export * from './types';\nexport * from './cluster.helper';\n"]}
@@ -0,0 +1,20 @@
1
+ import type { ClusterOptions } from 'ioredis';
2
+ import type { IRedisCredentials, IRedisHelperCallbacks, IRedisModuleOption, IRedisNode } from './../common/index.js';
3
+ /** Connection settings for a Redis Cluster: the startup `nodes` and one credential pair for every node, plus raw ioredis `clusterOptions` that override the helper defaults. The credentials go through `redisOptions`, so nodes found after startup get them too. */
4
+ export interface IRedisClusterHelperProps extends IRedisCredentials {
5
+ name: string;
6
+ nodes: IRedisNode[];
7
+ /**
8
+ * Same meaning as on single and sentinel: `false` holds the client open for a later `connect()`.
9
+ *
10
+ * @default true
11
+ */
12
+ autoConnect?: boolean;
13
+ /** Reconnect attempts: `0` never reconnects, `-1` never gives up; any other value is refused. `clusterOptions` still overrides. @default RedisDefaults.MAX_RETRY (5) */
14
+ maxRetry?: number;
15
+ clusterOptions?: ClusterOptions;
16
+ }
17
+ /** Options for `RedisClusterHelper`: connection props, lifecycle callbacks and an optional `ioredis` module. */
18
+ export interface IRedisClusterHelperOptions extends IRedisClusterHelperProps, IRedisHelperCallbacks, IRedisModuleOption {
19
+ }
20
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/redis/cluster/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ClusterOptions } from 'ioredis';\nimport type {\n IRedisCredentials,\n IRedisHelperCallbacks,\n IRedisModuleOption,\n IRedisNode,\n} from './../common';\n\n/** Connection settings for a Redis Cluster: the startup `nodes` and one credential pair for every node, plus raw ioredis `clusterOptions` that override the helper defaults. The credentials go through `redisOptions`, so nodes found after startup get them too. */\nexport interface IRedisClusterHelperProps extends IRedisCredentials {\n name: string;\n nodes: IRedisNode[];\n /**\n * Same meaning as on single and sentinel: `false` holds the client open for a later `connect()`.\n *\n * @default true\n */\n autoConnect?: boolean;\n /** Reconnect attempts: `0` never reconnects, `-1` never gives up; any other value is refused. `clusterOptions` still overrides. @default RedisDefaults.MAX_RETRY (5) */\n maxRetry?: number;\n clusterOptions?: ClusterOptions;\n}\n\n/** Options for `RedisClusterHelper`: connection props, lifecycle callbacks and an optional `ioredis` module. */\nexport interface IRedisClusterHelperOptions\n extends IRedisClusterHelperProps, IRedisHelperCallbacks, IRedisModuleOption {}\n"]}
@@ -1,13 +1,7 @@
1
- import type { TConstValue } from '../../../common/types/index.js';
2
- /** Role of the node a Sentinel-backed client connects to. */
3
- export declare class RedisSentinelRoles {
4
- static readonly MASTER = "master";
5
- static readonly SLAVE = "slave";
6
- }
7
- /** Union of the `RedisSentinelRoles` values. */
8
- export type TRedisSentinelRole = TConstValue<typeof RedisSentinelRoles>;
9
1
  /** Reconnect defaults of a Redis helper. */
10
2
  export declare class RedisDefaults {
3
+ /** The port of a data node when none is given. */
4
+ static readonly PORT = 6379;
11
5
  /** Reconnect attempts before the helper gives up: `0` never reconnects, `RETRY_FOREVER` never stops. */
12
6
  static readonly MAX_RETRY = 5;
13
7
  static readonly RETRY_FOREVER = -1;
@@ -1,11 +1,8 @@
1
1
  import { RetryBackoffStrategies, RetryJitterModes, } from '../../retry/index.js';
2
- /** Role of the node a Sentinel-backed client connects to. */
3
- export class RedisSentinelRoles {
4
- static { this.MASTER = 'master'; }
5
- static { this.SLAVE = 'slave'; }
6
- }
7
2
  /** Reconnect defaults of a Redis helper. */
8
3
  export class RedisDefaults {
4
+ /** The port of a data node when none is given. */
5
+ static { this.PORT = 6379; }
9
6
  /** Reconnect attempts before the helper gives up: `0` never reconnects, `RETRY_FOREVER` never stops. */
10
7
  static { this.MAX_RETRY = 5; }
11
8
  static { this.RETRY_FOREVER = -1; }
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/modules/redis/common/constants.ts"],"names":[],"mappings":"AACA,OAAO,EACL,sBAAsB,EACtB,gBAAgB,GAEjB,MAAM,iBAAiB,CAAC;AAEzB,6DAA6D;AAC7D,MAAM,OAAO,kBAAkB;aACb,WAAM,GAAG,QAAQ,CAAC;aAClB,UAAK,GAAG,OAAO,CAAC;;AAMlC,4CAA4C;AAC5C,MAAM,OAAO,aAAa;IACxB,wGAAwG;aACxF,cAAS,GAAG,CAAC,CAAC;aACd,kBAAa,GAAG,CAAC,CAAC,CAAC;IAEnC,4FAA4F;aAC5E,sBAAiB,GAAG;QAClC,QAAQ,EAAE,sBAAsB,CAAC,WAAW;QAC5C,cAAc,EAAE,IAAI;QACpB,UAAU,EAAE,CAAC;QACb,UAAU,EAAE,MAAM;QAClB,MAAM,EAAE,gBAAgB,CAAC,KAAK;KACA,CAAC;;AAGnC,mHAAmH;AACnH,MAAM,OAAO,gBAAgB;aACX,kBAAa,GAAG,EAAE,CAAC","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport {\n RetryBackoffStrategies,\n RetryJitterModes,\n type IRetryBackoffOptions,\n} from '@/modules/retry';\n\n/** Role of the node a Sentinel-backed client connects to. */\nexport class RedisSentinelRoles {\n static readonly MASTER = 'master';\n static readonly SLAVE = 'slave';\n}\n\n/** Union of the `RedisSentinelRoles` values. */\nexport type TRedisSentinelRole = TConstValue<typeof RedisSentinelRoles>;\n\n/** Reconnect defaults of a Redis helper. */\nexport class RedisDefaults {\n /** Reconnect attempts before the helper gives up: `0` never reconnects, `RETRY_FOREVER` never stops. */\n static readonly MAX_RETRY = 5;\n static readonly RETRY_FOREVER = -1;\n\n /** The wait before reconnect attempt N, computed by `RetryHelper.computeBackoffDelayMs`. */\n static readonly RECONNECT_BACKOFF = {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: 1000,\n multiplier: 2,\n maxDelayMs: 30_000,\n jitter: RetryJitterModes.EQUAL,\n } satisfies IRetryBackoffOptions;\n}\n\n/** Ceiling on a caller-sized fan-out over one connection; a burst larger than this queues rather than piles up. */\nexport class RedisConcurrency {\n static readonly PUBLISH_LIMIT = 32;\n}\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/modules/redis/common/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,gBAAgB,GAEjB,MAAM,iBAAiB,CAAC;AAEzB,4CAA4C;AAC5C,MAAM,OAAO,aAAa;IACxB,kDAAkD;aAClC,SAAI,GAAG,IAAI,CAAC;IAC5B,wGAAwG;aACxF,cAAS,GAAG,CAAC,CAAC;aACd,kBAAa,GAAG,CAAC,CAAC,CAAC;IAEnC,4FAA4F;aAC5E,sBAAiB,GAAG;QAClC,QAAQ,EAAE,sBAAsB,CAAC,WAAW;QAC5C,cAAc,EAAE,IAAI;QACpB,UAAU,EAAE,CAAC;QACb,UAAU,EAAE,MAAM;QAClB,MAAM,EAAE,gBAAgB,CAAC,KAAK;KACA,CAAC;;AAGnC,mHAAmH;AACnH,MAAM,OAAO,gBAAgB;aACX,kBAAa,GAAG,EAAE,CAAC","sourcesContent":["import {\n RetryBackoffStrategies,\n RetryJitterModes,\n type IRetryBackoffOptions,\n} from '@/modules/retry';\n\n/** Reconnect defaults of a Redis helper. */\nexport class RedisDefaults {\n /** The port of a data node when none is given. */\n static readonly PORT = 6379;\n /** Reconnect attempts before the helper gives up: `0` never reconnects, `RETRY_FOREVER` never stops. */\n static readonly MAX_RETRY = 5;\n static readonly RETRY_FOREVER = -1;\n\n /** The wait before reconnect attempt N, computed by `RetryHelper.computeBackoffDelayMs`. */\n static readonly RECONNECT_BACKOFF = {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: 1000,\n multiplier: 2,\n maxDelayMs: 30_000,\n jitter: RetryJitterModes.EQUAL,\n } satisfies IRetryBackoffOptions;\n}\n\n/** Ceiling on a caller-sized fan-out over one connection; a burst larger than this queues rather than piles up. */\nexport class RedisConcurrency {\n static readonly PUBLISH_LIMIT = 32;\n}\n"]}