@wopee-io/wopee.pw 4.24.0 → 4.24.3

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 (85) hide show
  1. package/.github/workflows/ci_cd.yaml +30 -12
  2. package/README.md +13 -0
  3. package/build/core/ports/configPort/configPort.js +2 -0
  4. package/build/core/ports/configPort/configPort.js.map +1 -1
  5. package/build/core/ports/configPort/configValidation.d.ts +2 -0
  6. package/build/core/ports/configPort/configValidation.js +49 -0
  7. package/build/core/ports/configPort/configValidation.js.map +1 -0
  8. package/build/core/services/wopeeService/wopee.js +7 -0
  9. package/build/core/services/wopeeService/wopee.js.map +1 -1
  10. package/build/shared/metadata/versionMetadata.js +15 -6
  11. package/build/shared/metadata/versionMetadata.js.map +1 -1
  12. package/build/tools/wopee-reporter/wopeeReporter.d.ts +6 -0
  13. package/build/tools/wopee-reporter/wopeeReporter.js +73 -11
  14. package/build/tools/wopee-reporter/wopeeReporter.js.map +1 -1
  15. package/docs/configuration.md +39 -15
  16. package/docs/troubleshooting.md +59 -0
  17. package/node_modules/@autonomous-testing/sdk/.github/workflows/ci_cd.yaml +47 -20
  18. package/node_modules/@autonomous-testing/sdk/README.md +129 -36
  19. package/node_modules/@autonomous-testing/sdk/build/infrastructure/adapters/apolloAdapter/adapter.js +4 -8
  20. package/node_modules/@autonomous-testing/sdk/build/infrastructure/adapters/apolloAdapter/axios-config.d.ts +12 -0
  21. package/node_modules/@autonomous-testing/sdk/build/infrastructure/adapters/apolloAdapter/axios-config.js +5 -4
  22. package/node_modules/@autonomous-testing/sdk/build/infrastructure/adapters/apolloAdapter/errors.d.ts +20 -0
  23. package/node_modules/@autonomous-testing/sdk/build/infrastructure/adapters/apolloAdapter/errors.js +178 -0
  24. package/node_modules/@autonomous-testing/sdk/build/infrastructure/adapters/apolloAdapter/interface.d.ts +1 -1
  25. package/node_modules/@autonomous-testing/sdk/build/infrastructure/adapters/apolloAdapter/interface.js +13 -3
  26. package/node_modules/@autonomous-testing/sdk/build/infrastructure/services/apolloAdapterService/apolloAdapterService.js +6 -2
  27. package/node_modules/@autonomous-testing/sdk/build/shared/metadata/versionMetadata.js +2 -2
  28. package/node_modules/@autonomous-testing/sdk/build/shared/utils/error.interface.d.ts +13 -1
  29. package/node_modules/@autonomous-testing/sdk/build/shared/utils/error.interface.js +8 -1
  30. package/node_modules/@autonomous-testing/sdk/build/shared/utils/index.d.ts +2 -2
  31. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/README.md +145 -0
  32. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/dist/src/index.d.ts +78 -0
  33. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/dist/src/index.js +203 -0
  34. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/dist/src/index.js.map +1 -0
  35. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/dist/src/promisify.d.ts +4 -0
  36. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/dist/src/promisify.js +18 -0
  37. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/dist/src/promisify.js.map +1 -0
  38. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/package.json +64 -0
  39. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/src/index.ts +345 -0
  40. package/node_modules/@autonomous-testing/sdk/node_modules/agent-base/src/promisify.ts +33 -0
  41. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/README.md +137 -0
  42. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/dist/agent.d.ts +30 -0
  43. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/dist/agent.js +177 -0
  44. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/dist/agent.js.map +1 -0
  45. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/dist/index.d.ts +23 -0
  46. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/dist/index.js +14 -0
  47. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/dist/index.js.map +1 -0
  48. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts +7 -0
  49. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/dist/parse-proxy-response.js +66 -0
  50. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map +1 -0
  51. package/node_modules/@autonomous-testing/sdk/node_modules/https-proxy-agent/package.json +56 -0
  52. package/node_modules/@autonomous-testing/sdk/package.json +18 -6
  53. package/node_modules/agent-base/LICENSE +22 -0
  54. package/node_modules/agent-base/README.md +69 -0
  55. package/node_modules/agent-base/dist/helpers.d.ts +15 -0
  56. package/node_modules/agent-base/dist/helpers.d.ts.map +1 -0
  57. package/node_modules/agent-base/dist/helpers.js +66 -0
  58. package/node_modules/agent-base/dist/helpers.js.map +1 -0
  59. package/node_modules/agent-base/dist/index.d.ts +41 -0
  60. package/node_modules/agent-base/dist/index.d.ts.map +1 -0
  61. package/node_modules/agent-base/dist/index.js +178 -0
  62. package/node_modules/agent-base/dist/index.js.map +1 -0
  63. package/node_modules/agent-base/package.json +46 -0
  64. package/node_modules/debug/LICENSE +20 -0
  65. package/node_modules/debug/README.md +481 -0
  66. package/node_modules/debug/package.json +64 -0
  67. package/node_modules/debug/src/browser.js +272 -0
  68. package/node_modules/debug/src/common.js +292 -0
  69. package/node_modules/debug/src/index.js +10 -0
  70. package/node_modules/debug/src/node.js +263 -0
  71. package/node_modules/http-proxy-agent/LICENSE +22 -0
  72. package/node_modules/http-proxy-agent/README.md +44 -0
  73. package/node_modules/http-proxy-agent/dist/index.d.ts +44 -0
  74. package/node_modules/http-proxy-agent/dist/index.d.ts.map +1 -0
  75. package/node_modules/http-proxy-agent/dist/index.js +148 -0
  76. package/node_modules/http-proxy-agent/dist/index.js.map +1 -0
  77. package/node_modules/http-proxy-agent/package.json +47 -0
  78. package/node_modules/ms/index.js +162 -0
  79. package/node_modules/ms/license.md +21 -0
  80. package/node_modules/ms/package.json +38 -0
  81. package/node_modules/ms/readme.md +59 -0
  82. package/package.json +3 -3
  83. package/tsconfig.build.json +4 -0
  84. package/.github/actions/npm_clean_install/action.yaml +0 -35
  85. package/node_modules/@autonomous-testing/sdk/.github/actions/npm_clean_install/action.yaml +0 -35
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.toConfigError = toConfigError;
7
+ exports.toApiRequestError = toApiRequestError;
8
+ const shared_1 = require("../../../shared");
9
+ const axios_config_1 = require("./axios-config");
10
+ const axios_1 = __importDefault(require("axios"));
11
+ const DOCS_URL = 'https://docs.wopee.io/';
12
+ const CMD_URL = 'https://cmd.wopee.io';
13
+ const DEFAULT_API_URL = 'https://api.wopee.io';
14
+ /**
15
+ * Where each configuration value comes from. The SDK is handed a config object
16
+ * and never reads the environment itself, so the environment variable is named
17
+ * as the usual source rather than as the thing that was validated.
18
+ */
19
+ const CONFIG_FIELD_HINTS = {
20
+ apiKey: `Get it from Project Settings → API Keys at ${CMD_URL}\n (usually the WOPEE_API_KEY environment variable).`,
21
+ projectUuid: `Get it from Project Settings at ${CMD_URL}\n (usually the WOPEE_PROJECT_UUID environment variable).`,
22
+ apiUrl: `This is your Wopee instance URL (usually the WOPEE_API_URL environment\n variable). The default SaaS endpoint is ${DEFAULT_API_URL}.`,
23
+ };
24
+ /**
25
+ * Strips credentials out of a proxy URL. `HTTPS_PROXY` commonly embeds
26
+ * `user:password@`, and these messages end up in CI logs.
27
+ */
28
+ function redactProxyUrl(raw) {
29
+ try {
30
+ const parsed = new URL(raw);
31
+ if (parsed.username || parsed.password) {
32
+ parsed.username = '***';
33
+ parsed.password = '***';
34
+ }
35
+ return parsed.toString();
36
+ }
37
+ catch {
38
+ return '(unparsable proxy URL)';
39
+ }
40
+ }
41
+ function describeProxy(decision) {
42
+ if (decision.proxyUrl) {
43
+ return `${redactProxyUrl(decision.proxyUrl)} (from HTTPS_PROXY/HTTP_PROXY)`;
44
+ }
45
+ if (decision.bypassedByNoProxy) {
46
+ return `bypassed — this host matches NO_PROXY="${decision.noProxy}"`;
47
+ }
48
+ return `none — no HTTP_PROXY/HTTPS_PROXY matched this URL (NO_PROXY="${decision.noProxy}")`;
49
+ }
50
+ /**
51
+ * The middle "likely cause" is the one that changes with the proxy situation —
52
+ * telling someone to set HTTPS_PROXY when it is already set is noise.
53
+ */
54
+ function proxyCause(decision) {
55
+ if (decision.proxyUrl) {
56
+ return [
57
+ '2. The proxy itself may be down, or may not allow this host. Verify the',
58
+ ' proxy is reachable, or add the host to NO_PROXY if it should be',
59
+ ' reached directly.',
60
+ ].join('\n ');
61
+ }
62
+ if (decision.bypassedByNoProxy) {
63
+ return [
64
+ '2. This host is excluded from the proxy by NO_PROXY. Remove the matching',
65
+ ' entry if the proxy is how you reach it.',
66
+ ].join('\n ');
67
+ }
68
+ return [
69
+ '2. A corporate proxy is required to reach it. The Wopee SDK honours',
70
+ ' HTTP_PROXY, HTTPS_PROXY and NO_PROXY — set HTTPS_PROXY and retry.',
71
+ ].join('\n ');
72
+ }
73
+ /**
74
+ * Turns a zod validation failure into readable prose. Fields without a hint fall
75
+ * back to the bare zod message, so every config failure reads as a sentence
76
+ * rather than a ZodError dump.
77
+ */
78
+ function toConfigError(error) {
79
+ const details = error.issues.map((issue) => {
80
+ const field = issue.path.join('.');
81
+ const hint = CONFIG_FIELD_HINTS[field];
82
+ const headline = ` • ${field || 'configuration'}: ${issue.message}.`;
83
+ return hint ? `${headline}\n ${hint}` : headline;
84
+ });
85
+ const message = [
86
+ 'Wopee SDK configuration is invalid — cannot initialize.',
87
+ '',
88
+ ...details,
89
+ '',
90
+ `Docs: ${DOCS_URL}`,
91
+ ].join('\n');
92
+ return new shared_1.WopeeError(message, { code: 'WOPEE_CONFIG_INVALID', cause: error });
93
+ }
94
+ function unreachableMessage(apiUrl, failure, code) {
95
+ const decision = (0, axios_config_1.getProxyDecision)(apiUrl);
96
+ const failureLine = code ? `${failure} (${code})` : failure;
97
+ return [
98
+ `Cannot reach the Wopee API at ${apiUrl}.`,
99
+ '',
100
+ ` Attempted: POST ${apiUrl}`,
101
+ ` Failure: ${failureLine}`,
102
+ ` Proxy: ${describeProxy(decision)}`,
103
+ '',
104
+ ' Likely causes:',
105
+ ' 1. This is a self-hosted Wopee instance that is only reachable from the',
106
+ ' customer network. Connect to the VPN, or run the tests from a CI',
107
+ ' runner inside that network.',
108
+ ` ${proxyCause(decision)}`,
109
+ ' 3. WOPEE_API_URL points at the wrong host. Confirm the value with your',
110
+ ` Wopee administrator; the default SaaS endpoint is ${DEFAULT_API_URL}.`,
111
+ '',
112
+ ` Docs: ${DOCS_URL}`,
113
+ ].join('\n');
114
+ }
115
+ function unauthorizedMessage(apiUrl, status, projectUuid) {
116
+ const label = status === 403 ? 'Forbidden' : 'Unauthorized';
117
+ return [
118
+ `Wopee API rejected the request: ${status} ${label}.`,
119
+ '',
120
+ ` Endpoint: ${apiUrl}`,
121
+ ` Project: ${projectUuid ?? '(not set)'}`,
122
+ '',
123
+ ' The API key was not accepted. Check WOPEE_API_KEY — you can view or',
124
+ ` regenerate it under Project Settings → API Keys at ${CMD_URL}.`,
125
+ ' Make sure the key belongs to the project above.',
126
+ '',
127
+ ` Docs: ${DOCS_URL}`,
128
+ ].join('\n');
129
+ }
130
+ /**
131
+ * Pulls the GraphQL error the API returns in the response body, which the
132
+ * previous implementation discarded.
133
+ */
134
+ function serverMessage(data) {
135
+ const errors = data?.errors;
136
+ const message = Array.isArray(errors) ? errors[0]?.message : undefined;
137
+ return typeof message === 'string' && message.length > 0 ? message : null;
138
+ }
139
+ /**
140
+ * Wraps a failed API call in a `WopeeError` that says what to do about it.
141
+ *
142
+ * The discriminator for "unreachable" is the absence of a response rather than
143
+ * an errno allowlist — that covers DNS, TCP, TLS and proxy-tunnel failures
144
+ * without going stale.
145
+ */
146
+ function toApiRequestError(error, context) {
147
+ const { apiUrl, projectUuid } = context;
148
+ if (axios_1.default.isAxiosError(error)) {
149
+ if (!error.response) {
150
+ return new shared_1.WopeeError(unreachableMessage(apiUrl, error.message, error.code), {
151
+ code: 'WOPEE_API_UNREACHABLE',
152
+ cause: error,
153
+ });
154
+ }
155
+ const status = error.response.status;
156
+ if (status === 401 || status === 403) {
157
+ return new shared_1.WopeeError(unauthorizedMessage(apiUrl, status, projectUuid), {
158
+ code: 'WOPEE_API_UNAUTHORIZED',
159
+ cause: error,
160
+ });
161
+ }
162
+ // Keeps the historical "API request failed with status code" wording so
163
+ // anything matching on it keeps working.
164
+ const details = serverMessage(error.response.data);
165
+ const message = [
166
+ `Wopee API request failed with status code ${status} at ${apiUrl}.`,
167
+ error.message,
168
+ ...(details ? [`Server said: ${details}`] : []),
169
+ ].join('\n');
170
+ return new shared_1.WopeeError(message, { code: 'WOPEE_API_ERROR', cause: error });
171
+ }
172
+ const description = error instanceof Error ? error.message : String(error);
173
+ return new shared_1.WopeeError(`Unexpected error during the Wopee API call: ${description}`, {
174
+ code: 'WOPEE_API_ERROR',
175
+ cause: error,
176
+ });
177
+ }
178
+ //# sourceMappingURL=errors.js.map
@@ -16,10 +16,10 @@ declare const ApolloAdapterConfigSchema: z.ZodObject<{
16
16
  suiteUuid: z.ZodOptional<z.ZodString>;
17
17
  }, "strip", z.ZodTypeAny, {
18
18
  apiKey: string;
19
+ projectUuid: string;
19
20
  apiUrl: string;
20
21
  branchName: string;
21
22
  enableSoftAssert: boolean;
22
- projectUuid: string;
23
23
  browser?: string | undefined;
24
24
  comment?: string | undefined;
25
25
  customTags?: string | undefined;
@@ -3,9 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VisualAssertApolloResponseSchema = exports.VisualAssertApolloPayloadSchema = exports.SuiteIntegrationConfigApolloPayloadSchema = exports.StopIntegrationScenarioApolloPayloadSchema = exports.IgnoreAreaApolloPayloadSchema = exports.CreateIntegrationSuiteApolloPayloadSchema = exports.CreateIntegrationStepConfigApolloPayloadSchema = exports.CreateIntegrationStepApolloResponseSchema = exports.CreateIntegrationStepApolloPayloadSchema = exports.CreateIntegrationScenarioApolloPayloadSchema = exports.ApolloAdapterConfigSchema = void 0;
4
4
  const shared_1 = require("../../../shared");
5
5
  const zod_1 = require("zod");
6
+ // The messages below are rendered into a human-readable summary by
7
+ // `toConfigError` in ./errors.ts, so they read as a sentence fragment following
8
+ // the field name, e.g. "apiKey: missing.".
6
9
  const ApolloAdapterConfigSchema = zod_1.z.object({
7
- apiKey: zod_1.z.string(),
8
- apiUrl: zod_1.z.string().default('https://api.wopee.io'),
10
+ apiKey: zod_1.z
11
+ .string({ required_error: 'missing', invalid_type_error: 'must be a string' })
12
+ .min(1, 'missing (empty string)'),
13
+ apiUrl: zod_1.z
14
+ .string({ invalid_type_error: 'must be a string' })
15
+ .url('must be an absolute URL including the scheme, e.g. https://api.wopee.io')
16
+ .default('https://api.wopee.io'),
9
17
  branchName: zod_1.z.string().default('master'),
10
18
  browser: zod_1.z.string().optional(),
11
19
  comment: zod_1.z.string().optional(),
@@ -14,7 +22,9 @@ const ApolloAdapterConfigSchema = zod_1.z.object({
14
22
  enableSoftAssert: shared_1.ZodHelper.parseStringToBoolean().default(true),
15
23
  os: zod_1.z.string().optional(),
16
24
  pixelToPixelDiffTolerance: shared_1.ZodHelper.parseStringToNumberSchema().optional(),
17
- projectUuid: zod_1.z.string(),
25
+ projectUuid: zod_1.z
26
+ .string({ required_error: 'missing', invalid_type_error: 'must be a string' })
27
+ .min(1, 'missing (empty string)'),
18
28
  viewport: zod_1.z.string().optional(),
19
29
  baselineBranchName: zod_1.z.string().optional(),
20
30
  suiteUuid: zod_1.z.string().optional(),
@@ -3,10 +3,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createApolloTrackAdapter = createApolloTrackAdapter;
4
4
  const adapters_1 = require("../../adapters");
5
5
  const adapters_2 = require("../../adapters");
6
+ const errors_1 = require("../../adapters/apolloAdapter/errors");
6
7
  const loggerService_1 = require("../loggerService");
7
8
  function createApolloTrackAdapter(apolloAdapterOptions) {
8
9
  const logger = (0, loggerService_1.createLogger)(apolloAdapterOptions.loggerOptions);
9
- const apolloAdapterConfig = adapters_2.ApolloAdapterConfigSchema.parse(apolloAdapterOptions.apolloAdapterConfig);
10
- return new adapters_1.ApolloAdapter(apolloAdapterConfig, logger);
10
+ const parsed = adapters_2.ApolloAdapterConfigSchema.safeParse(apolloAdapterOptions.apolloAdapterConfig);
11
+ if (!parsed.success) {
12
+ throw (0, errors_1.toConfigError)(parsed.error);
13
+ }
14
+ return new adapters_1.ApolloAdapter(parsed.data, logger);
11
15
  }
12
16
  //# sourceMappingURL=apolloAdapterService.js.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.hash = exports.version = void 0;
4
- exports.version = "3.7.2"
5
- exports.hash = "da0292dbeb19cb22287fbd510eac05290f7fc61f"
4
+ exports.version = "3.8.4"
5
+ exports.hash = "64bf6b138b6473ba74ee69c82e7440dda5f19ada"
6
6
  //# sourceMappingURL=versionMetadata.js.map
@@ -1,4 +1,16 @@
1
+ /**
2
+ * Stable, machine-readable identifiers for the failure modes the SDK reports.
3
+ *
4
+ * Prefer branching on `WopeeError.code` over matching on the message text —
5
+ * messages are written for humans and may be reworded.
6
+ */
7
+ export type WopeeErrorCode = 'WOPEE_CONFIG_INVALID' | 'WOPEE_API_UNREACHABLE' | 'WOPEE_API_UNAUTHORIZED' | 'WOPEE_API_ERROR';
8
+ export interface WopeeErrorOptions {
9
+ code?: WopeeErrorCode;
10
+ cause?: unknown;
11
+ }
1
12
  export declare class WopeeError extends Error {
2
- constructor(message: string);
13
+ readonly code?: WopeeErrorCode;
14
+ constructor(message: string, options?: WopeeErrorOptions);
3
15
  }
4
16
  //# sourceMappingURL=error.interface.d.ts.map
@@ -2,9 +2,16 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WopeeError = void 0;
4
4
  class WopeeError extends Error {
5
- constructor(message) {
5
+ code;
6
+ constructor(message, options = {}) {
6
7
  super(message);
7
8
  this.name = 'WopeeError';
9
+ this.code = options.code;
10
+ // Assigned rather than passed to `super` so the SDK does not depend on
11
+ // the Error constructor accepting an options bag.
12
+ if (options.cause !== undefined) {
13
+ this.cause = options.cause;
14
+ }
8
15
  Object.setPrototypeOf(this, WopeeError.prototype);
9
16
  }
10
17
  }
@@ -1,5 +1,5 @@
1
- import { WopeeError } from './error.interface';
1
+ import { WopeeError, WopeeErrorCode, WopeeErrorOptions } from './error.interface';
2
2
  export * from './mergeDicts';
3
3
  export * from './zodHelper';
4
- export { WopeeError };
4
+ export { WopeeError, WopeeErrorCode, WopeeErrorOptions };
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,145 @@
1
+ agent-base
2
+ ==========
3
+ ### Turn a function into an [`http.Agent`][http.Agent] instance
4
+ [![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI)
5
+
6
+ This module provides an `http.Agent` generator. That is, you pass it an async
7
+ callback function, and it returns a new `http.Agent` instance that will invoke the
8
+ given callback function when sending outbound HTTP requests.
9
+
10
+ #### Some subclasses:
11
+
12
+ Here's some more interesting uses of `agent-base`.
13
+ Send a pull request to list yours!
14
+
15
+ * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints
16
+ * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints
17
+ * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS
18
+ * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS
19
+
20
+
21
+ Installation
22
+ ------------
23
+
24
+ Install with `npm`:
25
+
26
+ ``` bash
27
+ $ npm install agent-base
28
+ ```
29
+
30
+
31
+ Example
32
+ -------
33
+
34
+ Here's a minimal example that creates a new `net.Socket` connection to the server
35
+ for every HTTP request (i.e. the equivalent of `agent: false` option):
36
+
37
+ ```js
38
+ var net = require('net');
39
+ var tls = require('tls');
40
+ var url = require('url');
41
+ var http = require('http');
42
+ var agent = require('agent-base');
43
+
44
+ var endpoint = 'http://nodejs.org/api/';
45
+ var parsed = url.parse(endpoint);
46
+
47
+ // This is the important part!
48
+ parsed.agent = agent(function (req, opts) {
49
+ var socket;
50
+ // `secureEndpoint` is true when using the https module
51
+ if (opts.secureEndpoint) {
52
+ socket = tls.connect(opts);
53
+ } else {
54
+ socket = net.connect(opts);
55
+ }
56
+ return socket;
57
+ });
58
+
59
+ // Everything else works just like normal...
60
+ http.get(parsed, function (res) {
61
+ console.log('"response" event!', res.headers);
62
+ res.pipe(process.stdout);
63
+ });
64
+ ```
65
+
66
+ Returning a Promise or using an `async` function is also supported:
67
+
68
+ ```js
69
+ agent(async function (req, opts) {
70
+ await sleep(1000);
71
+ // etc…
72
+ });
73
+ ```
74
+
75
+ Return another `http.Agent` instance to "pass through" the responsibility
76
+ for that HTTP request to that agent:
77
+
78
+ ```js
79
+ agent(function (req, opts) {
80
+ return opts.secureEndpoint ? https.globalAgent : http.globalAgent;
81
+ });
82
+ ```
83
+
84
+
85
+ API
86
+ ---
87
+
88
+ ## Agent(Function callback[, Object options]) → [http.Agent][]
89
+
90
+ Creates a base `http.Agent` that will execute the callback function `callback`
91
+ for every HTTP request that it is used as the `agent` for. The callback function
92
+ is responsible for creating a `stream.Duplex` instance of some kind that will be
93
+ used as the underlying socket in the HTTP request.
94
+
95
+ The `options` object accepts the following properties:
96
+
97
+ * `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional).
98
+
99
+ The callback function should have the following signature:
100
+
101
+ ### callback(http.ClientRequest req, Object options, Function cb) → undefined
102
+
103
+ The ClientRequest `req` can be accessed to read request headers and
104
+ and the path, etc. The `options` object contains the options passed
105
+ to the `http.request()`/`https.request()` function call, and is formatted
106
+ to be directly passed to `net.connect()`/`tls.connect()`, or however
107
+ else you want a Socket to be created. Pass the created socket to
108
+ the callback function `cb` once created, and the HTTP request will
109
+ continue to proceed.
110
+
111
+ If the `https` module is used to invoke the HTTP request, then the
112
+ `secureEndpoint` property on `options` _will be set to `true`_.
113
+
114
+
115
+ License
116
+ -------
117
+
118
+ (The MIT License)
119
+
120
+ Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
121
+
122
+ Permission is hereby granted, free of charge, to any person obtaining
123
+ a copy of this software and associated documentation files (the
124
+ 'Software'), to deal in the Software without restriction, including
125
+ without limitation the rights to use, copy, modify, merge, publish,
126
+ distribute, sublicense, and/or sell copies of the Software, and to
127
+ permit persons to whom the Software is furnished to do so, subject to
128
+ the following conditions:
129
+
130
+ The above copyright notice and this permission notice shall be
131
+ included in all copies or substantial portions of the Software.
132
+
133
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
134
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
135
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
136
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
137
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
138
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
139
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
140
+
141
+ [http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent
142
+ [https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
143
+ [pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent
144
+ [socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
145
+ [http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent
@@ -0,0 +1,78 @@
1
+ /// <reference types="node" />
2
+ import net from 'net';
3
+ import http from 'http';
4
+ import https from 'https';
5
+ import { Duplex } from 'stream';
6
+ import { EventEmitter } from 'events';
7
+ declare function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent;
8
+ declare function createAgent(callback: createAgent.AgentCallback, opts?: createAgent.AgentOptions): createAgent.Agent;
9
+ declare namespace createAgent {
10
+ interface ClientRequest extends http.ClientRequest {
11
+ _last?: boolean;
12
+ _hadError?: boolean;
13
+ method: string;
14
+ }
15
+ interface AgentRequestOptions {
16
+ host?: string;
17
+ path?: string;
18
+ port: number;
19
+ }
20
+ interface HttpRequestOptions extends AgentRequestOptions, Omit<http.RequestOptions, keyof AgentRequestOptions> {
21
+ secureEndpoint: false;
22
+ }
23
+ interface HttpsRequestOptions extends AgentRequestOptions, Omit<https.RequestOptions, keyof AgentRequestOptions> {
24
+ secureEndpoint: true;
25
+ }
26
+ type RequestOptions = HttpRequestOptions | HttpsRequestOptions;
27
+ type AgentLike = Pick<createAgent.Agent, 'addRequest'> | http.Agent;
28
+ type AgentCallbackReturn = Duplex | AgentLike;
29
+ type AgentCallbackCallback = (err?: Error | null, socket?: createAgent.AgentCallbackReturn) => void;
30
+ type AgentCallbackPromise = (req: createAgent.ClientRequest, opts: createAgent.RequestOptions) => createAgent.AgentCallbackReturn | Promise<createAgent.AgentCallbackReturn>;
31
+ type AgentCallback = typeof Agent.prototype.callback;
32
+ type AgentOptions = {
33
+ timeout?: number;
34
+ };
35
+ /**
36
+ * Base `http.Agent` implementation.
37
+ * No pooling/keep-alive is implemented by default.
38
+ *
39
+ * @param {Function} callback
40
+ * @api public
41
+ */
42
+ class Agent extends EventEmitter {
43
+ timeout: number | null;
44
+ maxFreeSockets: number;
45
+ maxTotalSockets: number;
46
+ maxSockets: number;
47
+ sockets: {
48
+ [key: string]: net.Socket[];
49
+ };
50
+ freeSockets: {
51
+ [key: string]: net.Socket[];
52
+ };
53
+ requests: {
54
+ [key: string]: http.IncomingMessage[];
55
+ };
56
+ options: https.AgentOptions;
57
+ private promisifiedCallback?;
58
+ private explicitDefaultPort?;
59
+ private explicitProtocol?;
60
+ constructor(callback?: createAgent.AgentCallback | createAgent.AgentOptions, _opts?: createAgent.AgentOptions);
61
+ get defaultPort(): number;
62
+ set defaultPort(v: number);
63
+ get protocol(): string;
64
+ set protocol(v: string);
65
+ callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions, fn: createAgent.AgentCallbackCallback): void;
66
+ callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions): createAgent.AgentCallbackReturn | Promise<createAgent.AgentCallbackReturn>;
67
+ /**
68
+ * Called by node-core's "_http_client.js" module when creating
69
+ * a new HTTP request with this Agent instance.
70
+ *
71
+ * @api public
72
+ */
73
+ addRequest(req: ClientRequest, _opts: RequestOptions): void;
74
+ freeSocket(socket: net.Socket, opts: AgentOptions): void;
75
+ destroy(): void;
76
+ }
77
+ }
78
+ export = createAgent;